Complete List of PHP Security Guideline Coding Examples

Below are the examples which have been used within this document.

input maxlength attribute

<input type=”text” name=”userName” maxlength=”25″/>

input password attribute

<input type=”password” name=”userPassword”/>

Checking variable length with PHP

<?php

if( strlen($_POST[‘userName] <= 25 ){
$userName = $_POST[‘userName];
}
else{
echo “You have entered a user name containing too many characters. Please use 25 characters or less.”;
}
?>

Filtering User Input

<?php
switch ($_POST[‘acadYear’])
{
case ‘Freshman':
case ‘Sophomore':
case ‘Junior':
case ‘Senior':
$acadYear = $_POST[‘acadYear’];
break;
default:
echo “Invalid academic year selection.”;
}
?>

Type Casting

<?php

$intNum = (int) $_POST[‘age’];

$floatNum = (float) $_POST[‘price’];

$inputString = (string) $_POST[‘name’];

?>

Validate Email with Regular Expression

<?php

if ( preg_match(“/^[^@\s<&>]+@([-a-z0-9]+\.)+[a-z]{2,}$/i”, $_POST[’email’]))
{
$email = $_POST[’email’];
}

?>

Preventing XSS and SQL Injection with a Single Function

<?php

function validate_input($input)
{
// Removes any script tags
$input = strip_tags($input);

// Stripslashes
if (get_magic_quotes_gpc())
{
$input = stripslashes($input);
}

// Escape special characters (Must have database connection previously made)
if (!is_numeric($input))
{
$input = mysql_real_escape_string($input);
}

// Validate numeric number
if (is_numeric($input))
{
$input = intval($input);
}

return $input;

}
?>

File Uploading

$validMimes = array(
‘image/png’=> ‘.png’,
‘image/x-png’ => ‘.png’,
‘image/gif’ => ‘.gif’,
‘image/jpeg’ => ‘.jpg’,
‘image/pjpeg’ => ‘.jpg’
);

$image = $_FILES[‘image’];

if(!array_key_exists($image[‘type’], $validMimes)){
die(‘Sorry, but the file type you tried to upload is invalid; only images are allowed.’);

// Get the filename minus the file extension:
$filename = substr($image[‘name’], 0, strrpos($image[‘name’], ‘.’));

// Append the appropriate extension:
$filename .= $validMimes[$image[‘type’]];

// Do something with the uploaded file