prevent sql injection for $_GET values

Security issues related to php and mysql usage. How to make your code secure? Security measures and configurations? It's all in here!

Moderators: egami, macek, gesf

Post Reply
OliverWeitman
New php-forum User
New php-forum User
Posts: 6
Joined: Fri Jul 17, 2015 9:06 am

Sat Jul 18, 2015 1:29 am

Try this

Code: Select all

<html>
<head>
<title>intval</title>
</head>
<body>
<a href="intval.php?cid=<?php echo urlencode(5); ?>">link cid</a>
<a href="intval.php?sid=<?php echo urlencode(2); ?>">link sid</a>
<a href="intval.php?pid=<?php echo urlencode(3); ?>">link pid</a>
</body>
</html>
<?php
function cleanInput($input) {
 
  $search = array(
    '@<script[^>]*?>.*?</script>@si',  
    '@<[\/\!]*?[^<>]*?>@si',           
    '@<style[^>]*?>.*?</style>@siU',   
    '@<![\s\S]*?--[ \t\n\r]*>@'       
  );
 
    $output = preg_replace($search, '', $input);
   
    return $output;
  }


$cid = trim(cleanInput(mysqli_real_escape_string($con,$_GET['cid'])));
$_GET['cid']= htmlspecialchars($cid);

$sid = trim(cleanInput(mysqli_real_escape_string($con,$_GET['sid'])));
$_GET['sid'] = htmlspecialchars($_sid);

$pid = trim(cleanInput(mysqli_real_escape_string($con,$_GET['pid'])));
$_GET['pid'] = htmlspecialchars($pid);

// function to redirect the page if the url value is not an positive interger
function redirect_to($location=NULL){
if($location!=NULL){
header("Location:{$location}");
exit;
}
}
//function to check the url values ($_GET[];) coming from index.php
function url_intval_check(){
if(isset($_GET['cid'])){
if(intval($_GET['cid'])==0){
redirect_to("index.php");
}
}elseif(isset($_GET['sid'])){
if(intval($_GET['sid'])==0){
redirect_to("index.php");
}	
}elseif(isset($_GET['pid'])){
if(intval($_GET['pid'])==0){
redirect_to("index.php");
}	
}else{

#if get value is a valid number then do this.
#this is where i call below function..
#find_selected_cid_sid_pid();
}
}
?>
<?php
url_intval_check();
if(isset($_GET['cid'])){echo "<br>cid ", $_GET['cid'];}
if(isset($_GET['sid'])){echo "<br>sid ", $_GET['sid'];}
if(isset($_GET['pid'])){echo "<br>pid ", $_GET['pid'];}
?>

Post Reply