How To Create a MySQL Database In cPanel With PHP

When you need to create a new database on a shared hosting account you normally need to log in to cPanel, create the database, create a user, and add the user to the database. That may not sound like a big deal, but it gets annoying fast when you need more than a couple of databases, or when you’re trying to find a way to quickly install some kind of a script or CMS (e.g. WordPress) on multiple domains.

There are various hacks & PHP scripts that automatically access cPanel and create a database - or so I’ve heard. I couldn’t find anything that would work on my host without modification. So I wrote my own basic cPanel class that can create MySQL databases and users (based in part on 5ubliminal’s script). You can use it as a building block for your own PHP scripts and tools.

Download The Script

cpanel.class.zip (8 Kb)

The archive contains :

  • includes/cpanel.class.php - the class itself. Feel free to extend or modify it. Links/credits are appreciated.
  • includes/ecurl.class.php - a cURL wrapper class. This is a modified version of another 5ubliminal’s script.
  • cpanel_createdb.php - a simple example that demonstrates how to use the class.

Notes

As you might have guessed, the script needs the cURL module to function. I haven’t tested it extensively; some small modifications might be necessary to make it work with cPanel skins other than x3. For example, the mysql_list_databases() function would probably need different regexps. Feel free to report any incompatibilities in the comments.

By the way, if you make a one-step WordPress using this, let me know - I was too lazy to program it myself ;)

Related posts:

2 Responses to “How To Create a MySQL Database In cPanel With PHP”

  1. 1
    David Grega Says:

    For those with reseller access, you may wish to consider using our APIs for this task. Unlike individual theme pages that can change, the APIs will function for a long time to come and are theme-independent. Contact sales at cPanel.net if you need assistance with the APIs. Note, you will need reseller access or higher to be able to use the APIs.

  2. 2
    White Shadow Says:

    I’d have to agree with you there. Users who have the required level of access should probably use an “official” API, that’s more reliable than theme-dependent hacks.

    My post was intended for people who are using shared hosting, which often has many limitations. Still, even experienced developers sometimes use shared hosts due to price and some marginal SEO benefits.

    Edit : Spoke too soon. Interestingly enough, there doesn’t appear to be any way to create databases with the official API.

Leave a Reply