Section 5a.7. Protecting against SQL injection in your PHP scripts


5a.7. Protecting against SQL injection in your PHP scripts

There's no reason to stop with your JavaScript. Let's help Frank make a few upgrades to his PHP to help protect the server from SQL injection attacks, too.

 <?php // Connect to database $conn = @mysql_connect("mysql.headfirstlabs.com",                        "secret", "really-secret"); if (!$conn)     die("Error connecting to MySQL: " . mysql_error()); if (!mysql_select_db("headfirst", $conn))     die("Error selecting Head First database: " . mysql_error()); $phone = preg_replace("/[\. \(\)\-]/", "", $_REQUEST['phone']); This is the most important change. This function will take care of escaping any special  characters, like those single quotes in the input string you entered. $phone = mysql_real_escape_string($phone); $select = 'SELECT *'; $from = ' FROM hraj_breakneck'; $where = ' WHERE phone = \'' . $phone . '\''; $queryResult = @mysql_query($select . $from . $where); if (!$queryResult)        die('Error retrieving customer from the database.'); We really shouldn't be looping through the results. There should never be more than one customer displayed at a time. while ($row = mysql_fetch_array($queryResult)) { Now, no matter what the phone number is, only one customer (at most) is returned in the server's response. $row = mysql_fetch_array($queryResult); echo $row['name'] . "\n" .      $row['street1'] . "\n" .      $row['city'] . ", " .      $row['state'] . " " .      $row['zipCode']; } mysql_close($conn); ?> lookupCustomer.php With these changes, lookupCustomer.php is protected from most SQL injection attacks. Nice work! 




Head Rush Ajax
Head Rush Ajax (Head First)
ISBN: 0596102259
EAN: 2147483647
Year: 2004
Pages: 241

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net