0

I'm currently setting up php scripts for my app and I'm abit clueless about how to obtain a level of safety to prevent injections to the sql server.

there are a few scripts that receive input from the app and not from the user directly such as content browsing and content rating, altho it is eventually an input.

the script that does receive user direct input as "name" and "creator name" is this :

$utc_str = gmdate("M d Y H:i:s", time());
$TIMESTAMP = strtotime($utc_str);
$DATA = $_POST['DATA'];
$NAME = $_POST['NAME'];
$CREATOR = $_POST['CREATOR'];

if(strlen($NAME) > 15 || strlen($CREATOR) > 15) exit("Error 2");

$stmt = $connect->prepare("INSERT INTO `ugcl` (`DATA`,`NAME`,`CREATOR`,`CREATEDSTAMP`) 
                           VALUES (?, ?, ?, ". $TIMESTAMP .")");
$stmt->bind_param("sss", $DATA, $NAME, $CREATOR);

if($stmt->execute())
{
    echo "Successs";
}
else
{
    echo "Error";
}

should i use bind params in all of the scripts that receive input? is there any thing else that is recommended?

3
  • You can do this to increase safety if(preg_match("/^[a-zA-Z0-9]+$/", $str) == 1) { // string only contain the a to z , A to Z, 0 to 9 } Commented Aug 13, 2016 at 11:26
  • @IlayaRajaS That just limits the data a DB can take. Parameterized queries should be used and that is unnecessary. Commented Aug 13, 2016 at 11:55
  • Bind all values going to your SQL query. Also consider XSS injections when you output the values. bind_param is a mysqli function, are you using mysqli with sql server? Commented Aug 13, 2016 at 11:58

1 Answer 1

1

Yes you should use PREPARED STATEMENTS in php whenever making an input or output.

Always bind the parameters so that the server always knows what datatype to expect. This will make sure you've an added security to your application. Everything you enter should be used as a ? in the original statement and bind the variables with the appropriate datatypes.

You're directly entering the $TIMESTAMP which I won't personally recommend either. Running that through a bind_param wont take much effort.

Also, always close your connections with a $stmt->close() and $conn->close() once a query statement is completed. If you have multiple queries in a page, start the connection at the beginning of the queries and end it after all the queries are done.

Also, another note on security- always validate and sanitize user inputs first. Never trust user data. Never take them to be valid in the first place.

Edit: Also consider using PDO for database interaction.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.