Problem in this code

hey guys. i have problem in this code :

<!DOCTYPE HTML>
<html>
<head><meta charset="utf-8"><title>email</title></head>
<body>
<form method="POST" action="<?php echo($_SERVER["PHP_SELF"]);?>">
<input type="email" name="em">
<input type="submit" value="ok">
</form>
<?php
$ema=$_POST['em'];
$ema=filter_var($ema,FILTER_VALIDATE_EMAIL);
if(empty($email)){
    echo "<br>".'please enter your email';
}
echo $ema;    
?>
</body>
</html>

and see this Error :

Notice: Undefined index: em in on line 10

why??

Your logic is flawed. You need soemthign along these lines

<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
(process form)
} else {
(display form)
}
?>
2 Likes

The php script is running before the form has been submitted, so em has not been defined yet.
You need to add a test to see if the form has been submitted.

if($_SERVER['REQUEST_METHOD'] == 'POST') {}

There are other problems like

if(empty($email)){

Where has $email been defined?
The validation could also be put into an conditional too, so the script only completes if the email is valid.

1 Like

Thanks buddy

$ema was probably $email. So I would assume it was declared, but OP probably had that as a typo. Nevertheless, empty and isset should never be used to check if the form was submitted. The only reason to use empty and isset is to determine if a user has been tampering with the HTML source code. If the HTML source has been tampered with, (e.g. Someone removing the actual field called tamper, that will cause a fatal error if you happen to try and sanitize that post value. This is because there isnā€™t such a field so PHP canā€™t process a field that was never declared.) That is the only reason to use empty and isset as they are not actual methods of checking whether the form was submitted or not as they are ā€œhackedā€ quick ways of doing something and is widely taught in legacy code tutorials.

1 Like

Donā€™t move the field before you validate it - move it AFTER you validate it.

$ema=filter_var($_POST['em'],FILTER_VALIDATE_EMAIL);
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.