Execute PHP Code from Database

Hi there,
Recently in a project  I need to execute PHP text from database. Primarily I was confused how to execute text. But it is solved using the eval() function.  The eval() function evaluates a string as PHP code.  The string must be valid PHP code and must end with semicolon. In this tutorial You will learn how to get data from mysql database   and execute the PHP text. Let’s see how the eval() function works:

Step 1: 
Create a Database, a Table, and insert some data with a column containing valid PHP text. For example you can use the below sql –

CREATE TABLE IF NOT EXISTS test (
id int(11) NOT NULL AUTO_INCREMENT,
contents text CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

INSERT INTO test (id, contents) VALUES
(1, ‘for($i=1;$i<=10;$i++){echo $i.”<br />”;}’),
(2, ‘?>\r\n<table style=”border:1px solid #CCCCCC; background-color:#F0F0F0; font-family:verdana; font-size:12px; margin:0 auto;” cellpadding=”5″ cellspacing=”2″ width=”600px”> \r\n    <tr>\r\n    <td colspan=”4″ align =”center”><h3>Server Information</h3></td>\r\n    </tr>\r\n    <tr>\r\n        <td>Server Name: <?php echo $_SERVER[”SERVER_NAME”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>Server Address: <?php echo $_SERVER[”SERVER_ADDR”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>Server Protocol: <?php echo $_SERVER[”SERVER_PROTOCOL”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>Server Method: <?php echo $_SERVER[”REQUEST_METHOD”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>Server Software: <?php echo $_SERVER[”SERVER_SOFTWARE”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>Server Request Time: <?php echo $_SERVER[”REQUEST_TIME”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>Server Gaetway Interface: <?php echo $_SERVER[”GATEWAY_INTERFACE”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>Document Root: <?php echo $_SERVER[”DOCUMENT_ROOT”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>HTTP_Accept Language: <?php echo $_SERVER[”HTTP_ACCEPT_LANGUAGE”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>HTTP Connection: <?php echo $_SERVER[”HTTP_CONNECTION”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>HTTP Host: <?php echo $_SERVER[”HTTP_HOST”]; ?></td></tr>\r\n    <tr>\r\n        <td>HTTP User Agent: <?php echo $_SERVER[”HTTP_USER_AGENT”]; ?></td>\r\n    </tr>\r\n    \r\n    <tr>\r\n        <td>Remote Address: <?php echo $_SERVER[”REMOTE_ADDR”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>Remote Host: <?php echo $_SERVER[”HTTP_HOST”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>Remote Port: <?php echo $_SERVER[”REMOTE_PORT”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>Server_Admin: <?php echo $_SERVER[”SERVER_ADMIN”]; ?></td>\r\n    </tr>\r\n    <tr>\r\n        <td>Server Port: <?php echo $_SERVER[”SERVER_PORT”]; ?></td>\r\n    </tr>\r\n</table>’),
(3, ‘    /*\r\n    * Getting IP Configuration related information using PHP\r\n    * Md. Shah Alom\r\n    * Web Site: http://web.tutpub.com\r\n    */\r\n\r\n    ob_start(); // Turn on output buffering\r\n    system(”ipconfig /all”); //Execute external program to display output\r\n    $com_result=ob_get_contents(); // Capture the output into a variable\r\n    ob_clean(); // Clean (erase) the output buffer\r\n?>\r\n<table style=”border:1px solid #CCCCCC; background-color:#F0F0F0; font-family:verdana; font-size:12px; margin:0 auto;” cellpadding=”5″ cellspacing=”2″ width=”600px”> \r\n    <tr>\r\n        <td colspan=”2″ align =”center”>\r\n        <h3>NIC Information</h3>\r\n        </td>\r\n    </tr>\r\n    <tr>\r\n        <td width=”250″><b>NIC:</b></td>\r\n        <td>\r\n        <?php\r\n            $desc = “Description”;\r\n            $desc_pos = strpos($com_result, $desc); // Find the position of Description text\r\n            $physical = “Physical”;\r\n            $physical_pos = strpos($com_result, $physical); // Find the position of Physical text\r\n            $nic_size = $physical_pos – ($desc_pos+36);\r\n            \r\n            $desc=substr($com_result,($desc_pos+36),$nic_size); // Get Full line of Description Address\r\n            echo $desc;\r\n        ?>\r\n        </td>\r\n    </tr>\r\n    <tr>\r\n        <td width=”200″><b>Physical Address (MAC Address):</b></td>\r\n        <td>\r\n        <?php\r\n            $findme = “Physical”;\r\n            $str_pos = strpos($com_result, $findme); // Find the position of Physical text\r\n            $mac=substr($com_result,($str_pos+36),17); // Get Full line of Physical Address\r\n            echo $mac;\r\n        ?>\r\n        </td>\r\n    </tr>\r\n</table>’);

Step 2:
Create a PHP class file so that we can execute our sql with the Object Oriented Programming(OOP) feature. We name the PHP file as “db.php” and the class name is “dbClass”. Below is the PHP class code:

<?php
/**
* @author            Md. Shah Alom (shahalom.amin@gmail.com)
* @Web                http://web.tutpub.com
* @author address:    http://bd.linkedin.com/in/shahalom
*/

class dbClass {
var $server;
var $username;
var $password;
var $db;
var $link;
function __construct($server, $username, $password, $db) {
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->connect();
}
function connect() {
$this->link = mysql_connect($this->server, $this->username, $this->password);
mysql_select_db($this->db, $this->link);
}
function runPHPfromDB($query) {
return mysql_query($query);
}
function __destruct() {

}
}
?>

__construct() function is the class constructor and get four(4) parameters. The parameter defines the database server, database user name, database password, database name.

connect() function used to create MySQL connection for this class. And this function is called from class constructor.

runPHPfromDB() function get sql query as parameter and return the result.

Step 3: 
Now we will create the main page. we name it “index.php”. In this page we will create a form with a combo box so that we can change the option to execute different code from database.

    <div style=”clear:both; width:250px; height:50px; margin:20px auto 10px; border:1px solid #EEEEEE; padding: 20px; text-align:center;”>
<form action=”” method=”post”>
<label for=”select_opt”>Select:</label>
<select name=”select_opt” id=”select_opt”>
<option value=””>Select</option>
<option value=”1″>Loop Result</option>
<option value=”2″>Server Information</option>
<option value=”3″>NIC Information</option>
</select><br /><br />
<input type=”submit” value=”Execute From DB” />
</form>
</div>

Step 4:  
Now in the “index.php” we will add some more script to execute the PHP text from database. Below is the script:

<?php
if(isset($_POST[‘select_opt’]) && !empty($_POST[‘select_opt’])) {
include “db.php”;

$select_opt = $_POST[‘select_opt’];
$res = new dbClass(‘localhost’,’root’,”,’php_code’);
$query=”select * from test where id=$select_opt”;
$result = $res->runPHPfromDB($query);
$data = mysql_fetch_array($result);
eval($data[‘contents’]); // Evaluate a string as PHP code
}
?>

Firstly in the if condition we check that the form has submitted with an option or not. If the form has submitted, then include the database class file(db.php). After getting the record from database with the selected option we pass PHP text into the eval() function.

It’s time to run the package. Wish the result will same as below screen shot:

 Execute PHP Code from Database Screen Shot

To download the full script Click Here. Cheers!!!

Author Info

Shah Alom

Hi, This is Mohammad Shah Alom, My passion is Programming & Web Development. I am Founder of Micro Solutions Bangladesh. My Facebook profile shahalom1983 & Twitter Profile shahalom_83