I have an ajax call calling the following chunk of code to make sure users don't input an invalid name. everything works as expected, except when they insert a '#', obviously its commenting out the rest of one of my if statements, but why isn't it causing a syntax error (it instead just takes the final else branch) or anything like that. I'm assuming the fix is as simple as a addslashes call (or something similar), i'm just trying to get a feel for why it is failing in this particular way.
PHP Code:
<?php
$q=mysql_real_escape_string($_GET['val']);
if(mysql_num_rows(mysql_query("SELECT * FROM `table` WHERE `value`='$q'"))!=0)
{
?>
<span class="red"><?php echo $q;?> is not available</span>
<?php
}
elseif(!preg_match('/^[a-z0-9_]+$/i',$q)||is_numeric($q))
{
?>
<span class="red"><?php echo stripslashes($q);?> is not allowed</span>
<?php
}
elseif(strlen($q)>16)
{
?>
<span class="red"><?php echo $q;?> is too long</span>
<?php
}
else
{
?>
<span class="green"><?php echo $q;?> is available</span>
<?php
}
?>
You're probably not encoding the username. Here's the explanation: if you simply compose your Ajax url like:
Code:
var url = "nameCheck.php?val=" + document.getElementById('userName').value;
then if the username contains a #, the url will look like this: nameCheck.php?val=some#Name. In this case, the value of $_GET['val'] will be "some", because what's after the # is considered an anchor name. And the username "some" indeed validates. You should use the encodeURIComponent function, like this:
Code:
var url = "nameCheck.php?val=" + encodeURIComponent(document.getElementById('userName').value);
Let us know if that was the problem
PS: Even though you said the problem was obviously the # commenting out the rest of the code, your problem has nothing to do with that. echo "#"; works perfectly and doesn't comment anything. As long as you don't eval() it or use it in a create_function() statement, there's no way a simple string containing a # could comment anything.
Bookmarks