WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Mobile Dev World

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : cPanel database administering
Categories : PHP, PHP Classes, Databases, MySQL, CURL Click here to Update Your Picture
Md. Zakir Hossain
Date : Aug 21st 2009
Grade : 2 of 5 (graded 3 times)
Viewed : 3404
File : 4990.php
Images : No Images for this code example.
Search : More code by Md. Zakir Hossain
Action : Grade This Code Example
Tools : My Examples List

 
Like this code?
Show the author your appreciation.
Submit your own code examples 
 

This class can be used to manage hosted databases using cPanel.

It can sent HTTP requests to the cPanel API Web server to perform several types of MySQL database administration tasks.

Currently it can check if a database or an user record exists, create or delete a database, create or delete a database user, and grant access privileges to a database user.


<?php

/**
* Name: cPanel Database Class
* Version: 1.0
* Author:     The HungryCoder
* Contact:    thehungrycoder@gmail.com
* Homepage: www.hungrycoder.xenexbd.com
*
* This class will create mysql database and users in cPanel. This is my first PHP work in my new job. Thanks for my collegues who inspired me while working.
*/

class cpanel_db {
    protected
$cpdomain;
    protected
$cpuser;
    protected
$cppass;
    protected
$cptheme;
    private
$error;
    public
$callresult;

   
    function
__construct($cpdomain,$cpuser,$cppass,$cptheme='x3'){
       
$this->cpdomain = $cpdomain;
       
$this->cpuser = $cpuser;
       
$this->cppass = $cppass;
       
$this->cptheme = $cptheme;
       
       
    }
   
    private function
callUrl($urlsuffix){
        if(empty(
$urlsuffix)) return $this->error('URL is empty');
               
       
$url = "http://".$this->cpdomain.":2082/frontend/".$this->cptheme.$urlsuffix;
       
$this->callresult=''; //reset
       
$ch = curl_init($url);
       
curl_setopt($ch, CURLOPT_HEADER, 1);
       
curl_setopt($ch, CURLOPT_USERPWD, "$this->cpuser:$this->cppass");
       
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   
//    curl_setopt($ch, CURLOPT_VERBOSE , 1 );
       
$this->callresult = curl_exec($ch);
       
$info = curl_getinfo($ch);
       
curl_close($ch);
        return
$info;
    }
   
   
/**
     * Create Database
     *
     * @param string $dbname
     * @return boolean
     */
   
public function createDb($dbname){
       
$suffix = "/sql/addb.html?db=$dbname";
       
       
//return $this->callresult;
       
$this->callUrl($suffix);
       
        return
$this->isSuccess('db');
    }   
   
    public function
createUser($username,$pass){
       
$suffix = "/sql/adduser.html?user=$username&pass=$pass&pass2=$pass";
       
       
//return $this->callresult;
       
$this->callUrl($suffix);
       
        return
$this->isSuccess('user');
    }
       
    public function
grantPriv($db,$user){
       
//prepare the params
       
$params = "db=$db&user=$user&update=&ALL=ALL&SELECT=SELECT&CREATE=CREATE&INSERT=INSERT&ALTER=ALTER&UPDATE=UPDATE&DROP=DROP&DELETE=DELETE&LOCKTABLES=LOCK&INDEX=INDEX&REFERENCES=REFERENCES&CREATETEMPORARYTABLES=TEMPORARY&CREATEROUTINE=CREATEROUTINE";
       
$callurl = "/sql/addusertodb.html?$params";
       
       
$this->callUrl($callurl);
       
        return
$this->isSuccess('grant');
    }
   
    private function
isSuccess($type='db'){
        switch (
$type){
            case
'db':
                if(
eregi('Added the database',$this->callresult)){
                    return
true;
                } else {
                    return
false;
                }
                break;
               
            case
'user':
                if(
eregi('Added user',$this->callresult)){
                    return
true;
                } else {
                    return
false;
                }
                break;
               
            case
'grant':
                if(
eregi('was added to the database',$this->callresult)){
                    return
true;
                } else {
                    return
false;
                }
                break;               
            case
'deldb':
                if(
eregi('deleted the database',$this->callresult)){
                    return
true;
                } else {
                    return
false;
                }
                break;               
            case
'deluser':
                if(
eregi('Deleted the user',$this->callresult)){
                    return
true;
                } else {
                    return
false;
                }
                break;   
        }
    }

    public function
error($msg){
       
$this->error = $msg;
        return
false;
    }
   
    public function
runBatch($dbname,$dbuser,$dbpass){
        if(empty(
$dbname) OR empty($dbuser) OR empty($dbpass)) return false;
       
$result = array();
       
//create the database
       
$result['db'] = $this->createDb($dbname);
       
       
//create the user
       
$result['user'] = $this->createUser($dbuser,$dbpass);
       
       
//grant the access with real db name and username
       
$result['grant'] = $this->grantPriv($this->cpuser.'_'.$dbname,$this->cpuser.'_'.$dbuser);
       
        return
$result;
    }
   
   
/**
     * This method deletes a number of databases from cpanel.
     *
     * @param array $dbs
     * @return array
     */
   
public function delDb($dbs){
       
//this method will delete a number of dbs.
       
if(is_array($dbs)){
            foreach (
$dbs as $db){
               
$db_full_name = $this->cpuser .'_'.$db;
               
$suffix = "/sql/deldb.html?db=$db_full_name";
               
$this->callUrl($suffix);
               
$result[$db] = $this->isSuccess('deldb');
            }
            return
$result;
        } else {
           
$this->error('Not an array');
        }
        return
false;
    }   
   
/**
     * This method deletes a number of users from cpanel.
     *
     * @param array $dbs
     * @return array
     */
   
public function delUser($users){
       
//this method will delete a number of dbs.
       
if(is_array($users)){
            foreach (
$users as $user){
               
$user_full_name = $this->cpuser .'_'.$user;
               
$suffix = "/sql/deluser.html?user=$user_full_name";
               
$this->callUrl($suffix);
               
$result[$user] = $this->isSuccess('deluser');
            }
            return
$result;
        } else {
           
$this->error('Not an array');
        }
        return
false;
    }
   
   
/**
     * Find whether a database is exists in cPanel or not!
     *
     * @param string $dbname Do not include the database name prefix (anything before _).
     * @return boolean
     */
   
public function isDbExists($dbname,$limit=100){
       
$suffix = "/sql/index.html?itemsperpage=$limit";
       
$this->callUrl($suffix);
       
$html = $this->callresult;
       
$html = substr($html,stripos($html,'<select name=db>')-1);
       
$html = substr($html,1,stripos($html,'</select>'));
       
$html = str_ireplace('</option>','BR',$html);
       
$html = strip_tags($html);
       
$all_db = explode('BR',$html); //array of all databases.
       
        //trim the whitespaces surrounding the dbname
       
$all_db = array_map('trim',$all_db);
       
//print_r($all_db);
       
       
if(in_array($this->cpuser.'_'.$dbname,$all_db)){
            return
true;
        } else {
            return
false;
        }
    }   
   
    public function
isUserExists($username,$limit=100){
       
$suffix = "/sql/index.html?itemsperpage=$limit";
       
$this->callUrl($suffix);
       
$html = $this->callresult;
       
       
$html = substr($html,stripos($html,'<select name=user>')-1);
       
       
$html = substr($html,1,stripos($html,'</select>'));

       
$html = str_ireplace('</option>','BR',$html);
       
$html = strip_tags($html);
       
$all_user = explode('BR',$html); //array of all databases.
       
        //trim the whitespaces surrounding the dbname
       
$all_user = array_map('trim',$all_user);
       
//print_r($all_db);
       
       
if(in_array($this->cpuser.'_'.$username,$all_user)){
            return
true;
        } else {
            return
false;
        }
    }
}
?>



Usage
<?php
error_reporting
(E_ALL);
include(
'cpanel_mysql.class.php');

$db = new cpanel_db('domain','user','pass');

//create db
if($db->createDb('cpdb')){
    echo
'Db Created';
} else {
    echo
'Db not created';
}


//create user
if($db->createUser('cpuser','3837djd')){
    echo
'User Created';
} else {
    echo
'User not created';
}

//grant access
if($db->grantPriv('cpdb','cpuser')){
    echo
'Priv granted';
} else {
    echo
'Priv not granted';
}


//we can run the above three by this single line:
//$result = $db->runBatch('batch','batch','elkdrlfd');
    //we can now check the result
   
print_r($result);

//del database
$db->delDb(array('db1','db2','db3'));

//del users
$db->delUser(array('user1','user1','user3'));


//we can also check whether a db/user exists
if($db->isUserExists('cpuser')) echo 'User exists';

if(
$db->isDbExists('cpdb')) echo 'Db exists';






Link Manager for Link Exchangers
Categories : PHP, PHP Classes, Databases, MySQL, CURL
Simple database class
Categories : PHP, PHP Classes, MySQL, Databases
Simple usersOnline class - keep track of how many users are online on your site
Categories : PHP, PHP Classes, Databases, MySQL
This class splits the results of the query into multiple pages like what the search engine does.
Categories : PHP Classes, PHP, MySQL, Databases
A script to generate a report from a valid mysql connection. The user has to supply which fields he wants to display in table. All properties are changable.
Categories : PHP, PHP Classes, Databases, MySQL, HTML and PHP
Simple Mini Poll class library (SimPoll)
Categories : PHP, PHP Classes, Databases, MySQL, Complete Programs
[PHP5] aDB PDO LIKE Database Abstraction. Switch easily from one db server to another, strong errors management, manage transactions, queries preparation and more.
Categories : PHP, PHP Classes, Databases, MS SQL Server, MySQL
MySQL Handler
Categories : PHP, Databases, MySQL, Classes and Objects, PHP Classes
bookmarker - PHP, PHPLIB, MySQL WWW based bookmark manager
Categories : MySQL, PHP, MySQL, Complete Programs, Databases
PHP Object Example of the Perl DBI with MySQL
Categories : PHP, PHP Classes, MySQL, Databases, Perl
Setting up InnoDB on MySQL and using Transactions Begin, Commit, Rollback in PHP.
Categories : PHP Classes, Databases, PHP, MySQL, InnoDB
Ajax PHP Tree (Left and Right) with MySQL
Categories : PHP, Databases, MySQL, AJAX, PHP Classes
PostGreSQL and MySQL 2 in 1 db Manager
Categories : PHP, PHP Classes, Databases, PostgreSQL, MySQL
MySQL Connection/Query Class
Categories : Databases, MySQL, PHP, PHP Classes
usercounter class
Categories : PHP, PHP Classes, Databases, MySQL, Environment Variables