Hi Everyone,
I am trying to test a simple email validation form using $_SERVER at the same page as

<?php 
if (isset($_POST['submitted'])) {
$email = $_POST['email'];
$result = filter_var($email, FILTER_VALIDATE_EMAIL) ;
if($result)
{ 
  echo "Valid email address."; 
} 
else { 
  echo "Invalid email address."; 
  } 
}
?>
<html>
<body>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
<p>E-mail: <input type="text" name="email" /></p>
<p><input type="submit" name="submitted" value="Validate Email"></p>
</form>
</body>
</html>

Now the validaion part works fine and PHP validate the user input but when I refresh the page the last validation result still remains in the page!
I tried to fix the issue by adding following after the echo functions

header("Location: ".$_SERVER['PHP_SELF']);

which refresh the page but this time I am not getting the results of validations.
Can you please let me know how I can fix the issue?
Thanks for your time in advance.

Recommended Answers

All 4 Replies

Member Avatar for diafol

You shouldn't send a form to itself, as refreshing will cause the form to re-submit.

Usually you can send a form to a form handler which does all the processing and then redirect back to the form page.

hi ardav,
Thanks for your comment, but honestly I didn't get this part:
you can send a form to a form handler which does all the processing and then redirect back to the form page.

Can you please tell me how I can use a form handler for this specific example?

Thansk

Use the following :

<?php 
if (isset($_POST['submitted'])) {
$email = $_POST['email'];
$result = filter_var($email, FILTER_VALIDATE_EMAIL) ;
if($result)
{ 
  echo "Valid email address."; 
  header("Location: ".$_SERVER['PHP_SELF']);
} 
else { 
  echo "Invalid email address."; 
  header("Location: ".$_SERVER['PHP_SELF']);
  } 
}
?>

Think this will do...

Member Avatar for diafol

you send the form to say formhandler.php

It runs all the php code. Instead of echoing out the response you can do something like this:

if($result){
  $msg="valid";
}else{
  $msg="invalid";
}
header("Location: form.php?msg=$msg");
exit;

Then in your form page, you could do something like this:

if(isset($_GET['msg'])){
  $msg = ($_GET['msg']=='valid')? '<p class="green">Valid email address.</p>' : '<p class="red">Invalid email address.</p>';
}
...
<p>E-mail: <input type="text" name="email" /></p><?php if(isset($msg))echo $msg;?>

To show the colours you need this in CSS or a style tag in the head:

.green{
  color: green;
}
.red{
  color: red;
}
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.