Code: Select all
// contains constants DB_HOST, DB_USER, etc
include(‘.db_credentials’);
// assign $_POST elements to scalar variables
if (!empty($_POST)){
foreach($_POST as $key=>$value){
${$key} = $value;
// $user_name = $_POST['user_name']
// $user_pwd = $_POST[‘user_pwd’]
}
}
// scrub user input, a belt and suspenders approach
//usage: $var = sanitize_system_string($string,minChar,maxChar)
$user_name = sanitize_system_string($user_name,2,44); //overloading vars
$user_pwd = sanitize_system_string($user_pwd,2,44); //overloading vars
// using Object Oriented style and built in mysqli
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PWD,DB_NAME);
if ($mysqli->connect_errno){
$err = urlencode("Failed to open database connection: ".$mysqli->connect_error);
header("Location: error.php?err=$err");
exit();
}
// using prepared statements
if ($stmt = $mysqli->prepare("SELECT user_id, user_phone FROM usertable WHERE user_name=? AND user_pwd=?")){ // note, no “;” at end of statement
// bind the var to the statement parameter
$stmt->bind_param('ss',$user_name,$user_pwd); // s for string, one per var
$stmt->execute();
// bind $stmt resultset to an object variable
$stmt->bind_result($col1,$col2); // col1:user_id, col2:user_phone
// using fetch() to get a result from the prepared statement
while ($stmt->fetch()){
$userID=$col1;
$userPhone=$col2;
}
$stmt->close();
}
$mysqli->close();
echo $userID; //outputs user id
echo $userPhone; //outputs phone number
# function sanitize_system_string
# sanitize a string in prep for passing a single argument to query
# no piping or passing possible environment variables ($),
# seperate commands, nested execution, file redirection,
# background processing, special commands (backspace, etc.), quotes
# newlines, or some other special characters
function sanitize_system_string($string, $min='', $max='')
{
$pattern = '/(;|\||`|>|<|&|^|"|'."\n|\r|'".'|{|}|[|]|\)|\()/i';
$string = preg_replace($pattern, '', $string);
//make sure this is only interpretted as ONE argument
$string = preg_replace('/\$/', '\\\$', $string);
$len = strlen($string);
if((($min != '') && ($len < $min)) || (($max != '') && ($len > $max)))
return FALSE;
return $string;
}
Good Luck!