Cannot find my problem with this form submission

My code gives me an error when I run it. I’m following a course to learn PHP, but the code in the course of this section doesn’t throw an error like that.

<?php

if ($_POST['send'] && array_key_exists('fName', $_POST)) {

    $fName = $_POST['fName'];
    echo empty($fName) ? 'No Name' : 'Welcome ' . $fName;

}
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Submission</title>
</head>
<body>
<form method="post" action="index.php">
    <input type="text" name="fName">
    <input type="submit" name="send" value="Send">
</form>
</body>
</html>

image

The course you are following has shown you everything you could do wrong in a small bit of code. Find another tutorial.

As far as the error, you are trying to us a variable before it has been set. You first need to check the REQUEST METHOD.

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Do Stuff
}
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo empty($_POST['fName']) ? 'No Name' : 'Welcome ' . htmlspecialchars($_POST['fName']);
}
?>
<!doctype html>
<html lang="en">
<head>
        <meta charset="UTF-8">
        <title>Submission</title>
</head>
<body>
    <form method="post">
    <input type="text" name="fName">
    <input type="submit" value="Send">
</form>
</body>
</html>
1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service