Sanitize Your Input In PHP

Here’s a quick and tiny PHP function that I’ve used on many projects to sanitize my input forms. As you are aware of, HTML forms are one source for injecting malicious code in programs to manipulate databases or traverse server directories. To make your programs much more secure, you’ll need to sanitize your inputs before doing anything, especially when dealing with databases. One function I’ve used repeatedly in my scripts is called sanitize(). Here’s the code:

The Code

// Sanitize input
function sanitize($in) {
 return addslashes(htmlspecialchars(strip_tags(trim($in))));
}

The addslashes function returns a string with backslashes to single quote (‘), double quote (“), backslash (\) and NUL (the NULL byte). This is particularly helpful when escaping special characters when dealing with database queries. The htmlspecialchars function converts special characters to HTML entities. For example & (ampersand) becomes & and ‘”‘ (double quote) becomes &quot. This function prevents user-supplied text from containing unintended HTML markup.

The strip_tags function strips HTML and PHP tags from a string. It suppresses unwanted HTML markups from being displayed and prevents malicious PHP code from being executed. The trim function strips white space from the beginning and end of a string. For example, the string ” apple ” with white spaces will become “apple” without white spaces when the trim function is applied.

Usage

You can use the sanitize function to clean up the $_GET, $_POST, $_REQUEST and $_COOKIE input variables. In this example, we will use the sanitize function to clean up the form input called $_POST[‘name’].

$name = sanitize($_POST['name']);

Database Use

Before you can query, insert or update the database, you can use mysql_real_escape_string to escape special characters within your SQL statement to prevent SQL injections.

$name = sanitize($_POST['name']);
$name = mysql_real_escape_string($name);

There you have it. Two short and deliciously simple functions to sanitize your input and prevent malicious code from wrecking your programs. Let me know what you think.

PHP: Generate Random Alphanumeric Keys

Occasionally, you might need to generate a random alphanumeric key in your project or within your script. This article will show you how to generate a random key using several PHP functions such as: mt_rand(), in_array() and the staple while and foreach loops.

The mt_rand() function generates a random key based on the characters supplied to it. mt_round() is a direct replacement for the original rand() function. The mt_rand() function is recommended since it’s considerably faster (4 times faster) than rand().

The in_array() function checks to see if the value is already in array. in_array() prevents duplication of the randomly chosen characters within the script.

Let’s get started.

Assign Characters

In this code, several alphanumeric characters are assigned to the variable $characters. I omitted all vowels and will use both uppercase and lowercase alpha characters. In addition, I’m using numbers 1 through 9 only. I ommited zero since it can be confused with the letter O, although I’m not using the letter O in this example.

// Random characters
$characters = array("B","C","D","F","G","H","J","K","L","M","N",
"P","Q","R","S","T","V","W","X","Y","Z","b","c","d","f","g","h",
"j","k","l","m","n","p","q","r","s","t","v","w","x","y","z",
"1","2","3","4","5","6","7","8","9");

Set The Array

We will set the variable $keys as an array.

// set the array
$keys = array();

Set The Key Length

This is the length of the random key. It’s originally set for 7 characters and can be changed to a length of your choosing.

// set length
$length = 7;

Generate The Random Key

This is main code that generates the random key. The code loops 7 times and assigns a random character to the variable $x. If $x is not in the array, it will assign the value of $x to the array called $keys[].

// loop to generate random keys and assign to an array
while(count($keys) < $length) {
       $x = mt_rand(0, count($characters)-1);
       if(!in_array($x, $keys)) {
       $keys[] = $x;
    }
}

Display The Random Key

We will use the foreach loop to display the random key stored in the $keys array. We will loop and extract each key and assign it the $random_chars variable. Finally, we will echo the $random_chars variable to display our random generated key.

// extract each key from array
foreach($keys as $key){
   $random_chars .= $characters[$key];
}
 
// display random key
echo $random_chars;

The Script

All together now. Here’s the entire script pieced together.

// Random characters
$characters = array("B","C","D","F","G","H","J","K","L","M","N",
"P","Q","R","S","T","V","W","X","Y","Z","b","c","d","f","g","h",
"j","k","l","m","n","p","q","r","s","t","v","w","x","y","z",
"1","2","3","4","5","6","7","8","9");
 
// set the array
$keys = array();
 
// set length
$length = 7;
 
// loop to generate random keys and assign to an array
while(count($keys) < $length) {
	$x = mt_rand(0, count($characters)-1);
	if(!in_array($x, $keys)) {
       $keys[] = $x;
    }
}
 
// extract each key from array
foreach($keys as $key){
   $random_chars .= $characters[$key];
}
 
// display random key
echo $random_chars;

There you have it, a random generated key based on the assigned characters and length that we indicated in our tiny PHP script. I hope you find this short article useful on future projects. By the way, you can also use this script to generate random passwords.

Display PHP Arrays

One of the big challenges when working with any programming language is working with arrays. In this article, I will give out an example how to display arrays and how to assign variables to them. These variables can be used later on for other purposes such as storing to a database, etc.

Simple Array

In this example, we will use an array containing the following values:

$a = array('one','two','three','four');

Using Print_r

We can output the array using the print_r() function. I’ve encapsulated the output using HTML <pre> markup for readability purposes. You don’t have to use <pre>, but it just makes it easier to read especially when debugging.

echo '<pre>';
print_r($a);
// echo your closing pre tags

Output

This is the output from the code above:

Array
(
    [0] =&gt; one
    [1] =&gt; two
    [2] =&gt; three
    [3] =&gt; four
)

Using Foreach

Another way of displaying an array is using foreach. I’m using HTML <br/> break for readability purposes.

foreach($a as $b ) :
  echo $b ."&lt;br/&gt;";
endforeach;

Output

This is the output from the code above:

one
two
three
four

Variables

In addition, you can also use the following variables to display its values.

echo $a[0];     // one
echo $a[1];     // two
echo $a[2];     // three
echo $a[3];     // four

So, there you have it. A simple article explaining how to display arrays and how to assign variables to them. The fun really starts when dealing with multidimensional arrays. I will have a follow up article in the next couple days to detail multidimensional arrays.

PHP Explode

The PHP explode function can break apart variables into several smaller pieces. You can specify the splitting parameter, and the result will be returned in an array which can be echoed or use for other purposes within your script. If I have a variable called “$string” that contains a very long string, I can use PHP explode to break it apart into smaller pieces. In this example, I have a variable that contains both the directory and filename. I will use PHP explode to break them apart.

Example:

$string = "thisisalongstring/breakmeapart.php";
$shorten = explode("/", $string);

The Result:

echo $shorten[0];    // thisisalongstring
echo $shorten[1];    // breakmeapart.php

PHP explode is a fun little function.

PHP And MSSQL

This article will show you how to connect to Microsoft’s MSSQL database via PHP. Typically, most PHP configurations involves the use of MySQL database, but every once in a while, there might be a need to connect PHP with MSSQL. So, here’s a sample script to get you started.

<?php
$sql_server = "localhost";
$sql_user   = "username";
$sql_pass   = "password";
$sql_db     = "database"; 
 
// Connect to the database
$db = mssql_connect($sql_server, $sql_user, $sql_pass)
or die("Can't connect to the MSSQL Server."); 
 
// Select a database
$select = mssql_select_db($sql_db, $db)
or die("Can't open the database " .$sql_db); 
 
// SQL statement
$query = "SELECT * FROM tablename WHERE id='3'";
 
// Execute the SQL query
$result = mssql_query($query);
 
// Display rows returned
$num_rows = mssql_num_rows($result); 
echo $num_rows." rows"; 
 
// Display results 
while($row = mssql_fetch_array($result)) {
  echo $row["id"];
  echo $row["first"];
}
 
// Close DB connection
mssql_close($db);
?>

Validate Email Addresses

Here’s one way to validate email addresses using the regular expression I found online that works great for me. You can use this little piece of PHP code in your forms or just about any place you need it. The regular expression should be typed in one continuous line, but I added a couple of line breaks for legibility purposes, in this example. You can also place this code  inside a function, so you can use it repeatedly by simply calling the function, in this case, validate_email(). If you have a better regular expression for validating email addresses, please share.

The Code

if (!eregi("
  ^[_a-z0-9-]+(\.[_a-z0-9-]+)*
  @[a-z0-9-]+(\.[a-z0-9-]+)*
  (\.[a-z]{2,3})$", $email)):
 echo "Invalid email.";
else:
 echo "Valid Email.";
endif;

The Function

function validate_email($email) {
 if (!eregi("
   ^[_a-z0-9-]+(\.[_a-z0-9-]+)*
   @[a-z0-9-]+(\.[a-z0-9-]+)*
   (\.[a-z]{2,3})$", $email)):
  echo "Invalid email.";
 else:
  echo "Valid Email.";
 endif;
}

Leaving Out the PHP Closing Tags

Typically, you will open and close PHP files like this:

<?php
// php code here
?>

Recently, I was introduced to another way. You leave them out!

<?php
// php code here
/* end of php file */

It seems a little weird at first leaving out the PHP closing tag. Feeling a little exposed and naked? It will take a little getting used to this way of closing out PHP. Somehow, it just doesn’t seem normal. This was done mainly to avoid the extra characters at the end of the file. You normally get a warning that headers were already sent or you cannot modify header information, if you have extra characters at the end of the PHP file.

I realized that you can only do this with certain files that end with PHP. For files that end with HTML or Javascript code, you will still need to close PHP further up the chain, otherwise the sky will fall on your head, and you don’t want that to happen. So, what do you think of think of leaving out the PHP closing tags?

Fuel PHP

I recently started looking into Fuel PHP. As much as I love CodeIgniter, it’s far from perfect. I’m more than curious if Fuel PHP can offer anything new to a glut of PHP frameworks that is already out there. There is Zend, CakePHP, CodeIgniter – which is my current favorite at the moment, and now Fuel. I was introduced to Fuel because some of the main supporters of CodeIgniter are now working with Fuel.

Here are some details from Fuel’s website.

Fuel is a simple, flexible, community driven PHP 5.3 web framework based on the best ideas of other frameworks with a fresh start.

The framework was started in late 2010 by Dan Horrigan then shortly after the team grew to include Phil Sturgeon, Jelmer Schreuder and Harro Verton. The team has decades of PHP experience between them and have all been involved with Open-Source projects such as CodeIgniter, PyroCMS, ExciteCMS and DataMapper ORM to name but a few.

April 1st, 2011 was the date of the first feature frozen Release Candidate, marking Fuel as ready to be used for development of new projects. v1.0 final is not yet ready but the only changes will be bug-fixes.

 

Adding Search to CodeIgniter Projects

This is a little tutorial that will add a Search function to your CodeIgniter projects. As you may already know, CodeIgniter is a PHP Framework that uses the MVC model. MVC stands for Model, Views and Controller. This article assumes you’ve work with CodeIgniter before and that you are looking for a search feature that you can add to your application. To add the search feature, we will get started with the Controller.

Controller

This is assuming you already loaded your libraries, helpers and database model. Lets add the Search function.

function search()
{
$data['query'] = $this->Books_model->get_search();
$this->load->view(‘books’, $data);
}

Model

In this database query, I am searching for any matches in any of the 4 fields: bookname, author, characters and synopsis. If there are matches, it will return the results.

function get_search() {
  $match = $this->input->post(‘search’);
  $this->db->like(‘bookname’,$match);
  $this->db->or_like(‘author’,$match);
  $this->db->or_like(‘characters’,$match);
  $this->db->or_like(‘synopsis’,$match);
  $query = $this->db->get(‘books’);
  return $query->result();
}

Views

Here’s the search form.

<?=form_open(‘books/search’);?>
<?php $search = array(‘name’=>’search’,'id’=>’search’,'value’=>,);?>
<?=form_input($search);?><input type=submit value=’Search’ /></p>
<?=form_close();?>

The result can be displayed using a HTML table.

<table>
<tr><th>ID</th><th>Book</th><th>Author</th><th>Published</th><th>Price</th></tr>
<?php foreach($query as $item):?>
<tr>
<td><?= $item->id ?></td>
<td><?= $item->bookname ?></td>
<td><?= $item->author ?></td>
<td><?= $item->datepublished ?></td>
<td><?= $item->price ?></td>
</tr>
<?php endforeach;?>
</table>

Let me know what you think.

CodeIgniter: Two Ways of Writing Arrays

There are two ways of writing arrays in PHP. We will use CodeIgniter in this example. Since CodeIgniter is a MVC framework, we will look at code in models. Assuming that a form is being submitted, and data is saved to the database. In this example, we will use a function called ‘add_entry.’

The add entry function is empty at the moment.

function add_entry() {
}

We will now add post data to our function. In this example, we will use the ‘url’ and ‘anchor’ fields. To sanitize, we set both values to TRUE. We assign it to a variable called $data in an array.

function add_entry() {
$data->url = $this->input->post(‘url’,true);
$data->anchor = $this->input->post(‘anchor’,true);
}

We will now insert data to a database table called ‘bookmarks.’

function add_entry() {
$data->url = $this->input->post(‘url’,true);
$data->anchor = $this->input->post(‘anchor’,true);
$this->db->insert(‘bookmarks’, $data);
}

The other way of writing an array is this:

function add_entry() {
$data = array(
‘url’ => $this->input->post(‘url’,true),
‘anchor’ => $this->input->post(‘anchor’,true));
$this->db->insert(‘bookmarks’, $data);
}

Essentially, both are the same. Somehow, I prefer the second. It seems cleaner somehow. It seems like, I only have to deal with a single variable called $data. What’s your preferred method?