Hello all!

Sorry in advance if this seem like a really dumb question.

I have one page where a client posts their personal info. One way I check the post is to use htmlspecialchars and then store it in a session. For example...

<?php
session_start();
include ("databaseinfo.php");

//Form validation:
if ((!empty($_POST['username']))
&& (strlen($_POST['username']) >5)
&& (strlen($_POST['username']) <21))
{
$username=$_POST['username'];
$username=htmlspecialchars($username);
$_SESSION['username']=$username;
}
elseif (!empty($_POST['username']))
{
$errors[]= "You forgot to enter a valid entry=User Name!";
}

if (!empty($errors) && is_array($errors))
{
echo "<html><head><meta http-equiv=\"Refresh\"
content=\"5;url=http://www.thispage.com\"></head>";
echo '<h1>Error!</h1>
The following error(s) occured:<br/>';
foreach ($errors as $msg)
{
echo " - $msg<br />\n";
}
echo "<p>You are being redirected.  If you do not redirect in 5 seconds, <a 
href=\"http://www.thispage.com\">click 
here</a>";
}
?>

When they submit it takes them to 2 more pages to fill out info. After they fill out all of the forms, it will take them to a preview page to view their answers. If they accept their client page, it is going to put the info in the database. So, my question is do I have to once again use htmlspecialchars like this...

<?php
$username=$_SESSION['username'];
$username=htmlspecialchars($username);
$username_sq=mysql_real_escape_string($username);
?>

or is this enough...

<?php
$username=$_SESSION['username'];
$username_sq=mysql_real_escape_string($username);
?>

I know it may not matter much, but I was thinking if it's possible for a hacker to change anything between those few pages. I'm trying to be as safe as I can be.

Thank you in advance for any info you can provide.
~Amy

You should always check the data just before it is entered into the SQL query, especially with POST and REQUEST values, so it is not a bad idea to check this twice (even though you are using sessions).

It may also be a good idea to restrict the characters in the username, so if you only want to have alphanumeric characters and select symbols then use preg_replace() to stop entry of anything else.

commented: Spot on! +1

Thanks so much! I haven't looked into preg_match that much, so I'll definitely hit some google tonight :) Thanks for advice.

Oops, I mean preg_replace(). Sorry!

They are both good to learn :)

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.