How to kill PHP (on purpose)

1. Stack overflow (e.g calling a function inside itself).

function a()
{ a(); }

a();

First you define a function called a() and the function’s sole purpose is to call itself again, causing an infinite loop. Then you just call the function.

2. Excessive Memory Allocation Using str_repeat

str_repeat("a", 10000000000);

The above code will cause PHP to use too much memory (which will cause the process to close), if the correct memory or script runtime limits are not properly configured.

3. Kill the Apache Process with PHP Script

shell_exec("killall -11 httpd");

This simple code will kill (end) all running Apache processes, except the Daemon (which runs as Root). All other Apache processes run under the same user, which means that one of them with the harmful script, mentioned above can easily kill the rest. The best way to ensure Apache’s protection in this case is to disable execution commands such as exec() or shell_exec() using the disable_functions() directive.

Easy PHP Debugging

Spotting errors inside PHP is a difficult task. Especially if you try to understand the default messages, given by the PHP interpreter. If you want to effectively debug your PHP script, you can use the following code:

error_reporting(E_ALL);

This code will show all errors, notices and warnings generated during the script’s run. It’s very useful for PHP developers.

Also, if you are passing variables via POST or GET requests and you are wondering if the correct variables are transmitted to the script, you can show the full contents of these two request types, by using the simple PHP snippet:

print_r($_REQUEST);

If you need more information, you can check the PHP’s error reporting article.

Connect to a MySQL Database

This is the very basic step, needed to work with MySQL databases. Before trying to do any actions on the database itself, such as: creating tables, querying rows, dropping tables or else, you have to make your PHP script connect to the MySQL database.

$host = "mysql_host";
$user = "mysql_user";
$pass = "mysql_password";
$db = "mysql_databasename";

$connect = mysql_connect($host, $user, $pass) or die(mysql_error());
$dbselect = mysql_select_db($db) or die(mysql_error());

$host – Your database hostname. The default is “localhost” but some hosts use a separate servers for the databases and files.
$user – The MySQL username. You need to create one through a web-based SQL interface if none exists (e.g through phpMyAdmin)
$pass – The login password associated with the above username.
$db – The name of the database you want to select. You are required to select one that your PHP script will work with later on.

Of course, for performance improvement, it is recommended that you close your database connections when you don’t need them anymore. You can use the following script:

$close = mysql_close($connect) or die(mysql_error());