University of Connecticut University of UC Title Fallback Connecticut

PHP Security Best Practices

  • Remote File Inclusion

    COMMONLY USED; INCORRECT METHOD

If another file is included into your script it should be known about ahead of time. NOT specified by the user.

<?php
$page = $_GET['page']
require($page . ".php");
?>

CORRECT METHOD

If you need to dynamically include files the best practice is to specify the choices in a conditional or switch statement.

 <?php
$page = $_POST['page'];
if ($page == "home") {
require("./pages/home.php");
} elseif ($page == "athletics") {
require("./pages/athletics.php");
} elseif ($page == "contact") {
require("./pages/contact.php");
}
// ... as many as pages that are possible
else {
require("./pages/not_found.php");
}
?>
  • SQL Statements

    COMMONLY USED; INCORRECT METHOD

Common mistake coding sql request which should NEVER be done.

<?php
$dbh = mysql_connect($SERVER, $USERNAME, $PASSWORD);
$db = mysql_db_connect($DATABASE);
$results = mysql_query("SELECT * FROM `students` WHERE `netid`='$_GET[netid]'");
?>

CORRECT METHOD

The best practices method of accessing data stored in a mysql database via PHP.

 <?php
$dbh = new mysqli($SERVER, $USERNAME, $PASSWORD, $DATABASE)
or die("Failed to connect to server or database.");
$netid = $_POST['netid'];
if ($stmt = mysqli->prepare($dbh, "SELECT * FROM `students` WHERE netid=?")) {
$stmt->bind_param("s", $netid);
$stmt->execute();
$stmt->bind_result($results);
$stmt->fetch();
$stmt->close();
}
// $results now contains the results of the sql query.
?>
    • Under no circumstances should you develop scripts to upload files which can be used without the end user authenticating. This prevents unknown identities from uploading content to the server.

    • Additional Resources