At the moment I am trying to validate a form using PHP. The problem is, that even after entering something wrong, PHP interprets it as right. Obviously I don’t now why, although I have an assumption.
This is the code:
if(isset($_GET['contact'])){
// Validation functions
// Name
function validate_name(){
$name = $_POST['customer'];
if(strlen($name) > 0){
trim(mysql_real_escape_string($name));
return true;
}else {
return false;
}
}
// Mail
function validate_mail(){
$mail = $_POST['mail'];
if(preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/', $mail) && strlen($mail) > 0){
return true;
}else {
return false;
}
}
// Message
function validate_message(){
$message = $_POST['message'];
if(strlen($message) > 0){
trim(mysql_real_escape_string($message));
return true;
}else {
return false;
}
}
validate_name();
validate_mail();
validate_message();
if(validate_name == true && validate_mail == true && validate_message == true){
echo "Ok!";
}else{
echo "Error!";
}
}
One thing I know is bad is this: if(validate_name == true && validate_mail == true && validate_message == true){}.
But if I am not mistaken, this still works because PHP can handle something like this (PHP only gives a notice, not an error). But how to do it right, there must be a better way?
The second this I found out is, that PHP basically calls the functions correct, but inside the functions the if-else is not working. Why? I don’t understand this…
OK. Since it is weekend and I have nothing better to do I’ll fix your issues and explain what is wrong with your code.
To start by answering your original question:
As the notice states:
This is because of the line where you do:
validate_nameis nothing. If it were a variable it would have been$validate_nameif it were a function call it would have beenvalidate_name(). So PHP assumes it is a constant. Without ranting about whether this is a smart move of PHP trying to ‘help’ you it does what it does. So basically PHP will handle it as a constant with a value ofvalidate_name.So what PHP does is the following:
Now to further fix / improve your code:
I’m also not sure about your use of superglobals. You use
$_GET['contact']and also$_POST['customer']. So you are mixing_POSTand_GET. This could be correct not sure though.If you have a form with an action of ‘/file.php?contact=something’ and the form method is set to
postthis is perfectly fine.Also it would be better to add params to the functions. So change:
To
In stead of relying on the
_POSTvalues. This way you can test your code without needing any post data.In your
validate_nameandvalidate_messagefunction you are doing this:There are two things wrong with this:
In your validate email function you do the following:
Besides the fact that I’m sure that that regex isn’t getting all valid emailaddresses it would have been better to first check if the string is filled in.
Now to correct all your issues in the following code: