Batten Down the Hatches
8/11/2010 9:30 AM By Jeff BWe’re going to take this opportunity to discuss some security items with regards to PHP. It should be noted that, since PHP executes on the server side, it can be used maliciously to take control of your server and repurpose it for various unpleasant activities.
One of the most common efforts to do this is through what’s called a SQL injection. This is when you are utilizing a SQL-based database (MySQL, etc.), and a SQL query is directly injected into your server through a form field, a URL query, or some other mechanism that asks the server to process information. Thankfully, there are a number of ways to prevent this. One of the simplest is this handy little function, culled from the wilds of the internet:
<?php
/*
Function: sql_sanitize( $sCode )
Description: "Sanitize" a string of SQL code to prevent SQL injection.
Parameters: $sCode
The SQL code which you wish to sanitize.
Example: mysql_query('UPDATE table SET value="' . sql_sanitize("' SET id='4'") . '" WHERE id="1"');
Requirements: PHP version 4 or greater
Notes:
Author: engel <engel@engel.uk.to>
*/
function sql_sanitize( $sCode ) {
if ( function_exists( "mysql_real_escape_string" ) ) { // If PHP version > 4.3.0
$sCode = mysql_real_escape_string( $sCode ); // Escape the MySQL string.
} else { // If PHP version < 4.3.0
$sCode = addslashes( $sCode ); // Precede sensitive characters with a backslash \
}
return $sCode; // Return the sanitized code
}
?>
As it says, when you run a query, you’ll want to run the sql_sanitize() function on any value being input into the database, such as a $_POST["variable"] from a form.
One of the other functions that’s wide open by default, and should be disabled for any production server, is error reporting. When you’re writing a site or application using PHP, you’ll definitely want the error reporting to be on so you can see the problem as it happens and where it happens. But once you’ve deployed, you don’t want your visitors seeing anything like that.
The solution is to disable display_errors in the php.ini configuration file, and then enable log_errors, which will write any PHP errors to your server’s error log. In this way, you can still check the logs for any problems that might arise after you’ve deployed to production, but you don’t run the risk of exposing any runtime code to your visitors, who may turn out to be malicious in their intent.
Hopefully, none of this has scared you away from using PHP to develop your sites; it’s a solid, robust programming language still under active development, and as such, is as safe as you make it. Sadly, there will always be people seeking to take advantage.
Tags: PHP








Subscribe by RSS