I'm passing PHPSESSID to a PHP page (via POST) and I was wondering what's the best way of sanitizing the input. Would
mysql_real_escape_string suffice? Is there anything special I should take into account when dealing with session IDs (I mean, they can only be letters and numbers right?)?
To clarify the question, what I really want to know is: if someone tampers with the POST data, can he send a malicious string as PHPSESSID that would do something nasty when I call
I personally cannot think of any, but better safe than sorry...
Good thinking, but as far as I can see, there is no need to sanitize this input. The PHPSESSID will be passed on to
session_id indeed has some limitations:
Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)!
session_id() should deal with deviations from these rules with an error message. (You may want to catch that error message and terminate the script on error.)
The only real danger that I can see is when you use a custom session handler that e.g. connects to a database. You will have to sanitize the input in that case, e.g. using
mysql_real_escape_string(). However, that is something that should take place inside the custom session handler.
It goes without saying that if you use the session ID in some other context - say, as a parameter in a HTML form - you need to take the sanitation measures necessary for that specific output (In that case,
If you really need to pass on a session ID via POST (can´t see why really...) and you know what characters you want to allow, I would use a regular expression to check for that.
mysql_real_escape_string is for database input and requires a database connection and is not sanitizing anything, just escaping some special characters.
Would mysql_real_escape_string suffice?
Wrong. You should always sanitize data using an appropriate method to the place you are writing the value to. You'd only use mysql_real_escape_string() if/when you are writing a value to a MySQL database.
It's not clear from your comment what exactly you are doing. Do you mean you are using curl in PHP to create the POST? If so then there's no sanitization required (not strictly true - but curl does it for you) if you pass CURLOPT_POSTFIELDS as an array - but you need to urlencode the value if you are passing CURLOPT_POSTFIELDS as a string.
Are you writing the value out to the browser so the user can submit the value? In which case you'd use htmlentities() to write the value into the form field.