I hope this is the correct forum for this question. I manage a small website. The site uses a database with MySql. When I launched the site, around 3 years ago, the PHP code I wrote had minimal security and validation in PHP because I relied on javascript validation for the forms involved. Over the 3 years, I learned about the risks of injection attacks and other potential site disruptions via forms and database commands. I found recommendations for using the

myslq_real_escape_string()

to improve security. This past week I decided to implement this security measure by escaping the strings that were added to the database.

My site stopped functioning correctly. It only returned to normal after I removed ALL the escape string codes. My question is: why did this happen?

I escaped the username and password for login, and then the login process generated errors. It would yield a user already logged in error, a user unknown error, and an incorrect password error. I escaped the registration strings and the registration process and generated the error that the requested username was already taken by another user. When I checked the database itself, there were fields that were empty despite being filled in the form.

I thought I understood what the

myslq_real_escape_string()

did. I do not, or at least not well enough. Can someone explain to me what EXACTLY this function does?

you cannot use myslq_real_escape_string() UNLESS you are connected to your DB first. Did you?

WRONG:

<?php
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);

mysql_connect(...) or die( mysql_error() );
mysql_select_db(...) or die( mysql_error() );
mysql_query("SELECT * FROM Person WHERE username='$username' AND password='$password'" ) or die( mysql_error() );
?>

CORRECT:

<?php

mysql_connect(...) or die( mysql_error() );
mysql_select_db(...) or die( mysql_error() );

$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);

mysql_query("SELECT * FROM Person WHERE username='$username' AND password='$password'" ) or die( mysql_error() );
?>

No. The escape lines were prior to the DB connect line. Thank you very much for the essential piece of information.

Glad to help.

Regards,
Hielo

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.