Page 1 of 1

How to remember id in form?

Posted: Mon Feb 01, 2010 6:17 am
by balo
Hi again!
another question about security!
usually i print in my form an hidden field like

Code: Select all

<input type='hidden' name='user_id' id='user_id' value='4' />
where i write the id of the user (or news or anythings i have on my db) and that i read when i submit the form to understand which data i have to update, like

Code: Select all

 
if(isset($_POST['save_user'])){
   $name = clean($_POST['name']);
   $id = (int)$_POST['user_id];
   $sql = "UPDATE user SET name = '$name' WHERE id = '$id";
}
 
first: it's ok

Code: Select all

 
function clean($testo){
  $testo = trim($testo);
  $testo = htmlentities($testo, ENT_QUOTES, "UTF-8");
}
or is not safe and i have to add something?

and then, what can i do to make more sure the form and the id? i come from another page and send the id with get, like:

Code: Select all

<a href='edit_user.php?id=4'>edit</a>
thanks for all the help! as you can see, with me there is lot to do ;)

Re: How to remember id in form?

Posted: Mon Feb 01, 2010 6:31 am
by pbs
You can store user id in session

Re: How to remember id in form?

Posted: Mon Feb 01, 2010 7:39 am
by balo
i have even this idea, but is not the same? i can store whene i open the page where i have the form, not in the other, and so i have the id with the $_GET. is easy as before change the id in the GET and have a different user!
or not?

Re: How to remember id in form?

Posted: Tue Feb 02, 2010 7:53 am
by kaisellgren
balo wrote:

Code: Select all

 
if(isset($_POST['save_user'])){
   $name = clean($_POST['name']);
   $id = (int)$_POST['user_id];
   $sql = "UPDATE user SET name = '$name' WHERE id = '$id";
}
 
You are vulnerable to SQL injections. User input going to the database should be escaped (most likely mysql_real_escape_string() will work for you).
balo wrote:

Code: Select all

<a href='edit_user.php?id=4'>edit</a>
You should protect yourself against CSRF (http://en.wikipedia.org/wiki/Cross-site_request_forgery) attacks.

Re: How to remember id in form?

Posted: Tue Feb 02, 2010 11:45 am
by flying_circus
balo wrote:i have even this idea, but is not the same? i can store whene i open the page where i have the form, not in the other, and so i have the id with the $_GET. is easy as before change the id in the GET and have a different user!
or not?
Yes, if your link points to http://www.example.com/edit_user.php?id=4 but I manually change the id in the querystring, I could potentially harvest a list of usernames, potentially more, depending on how you have written your website.

Any data you retreive from GET, POST, or COOKIE (and some SERVER) data should never be trusted. If you need to store values to manipulate the mechanics or security of your website, the only viable solution is sessions.