0

I am really new to php but I have previous knowledge in asp.net . I have been reading and trying a lot through https://www.w3schools.com The problem is at posting forms and sending them as emails . so as a first step , I tried the following code from the following link: https://www.w3schools.com/php/php_superglobals.asp

   <html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="fname">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = $_POST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>

I copied it into phpDesigner8 but I got the following error when I press on run : Notice : Undefined index: REQUEST_METHOD in c:\Users\User\AppData\Local\Temp\Untitled 1 on line 10

can anyone please help me and explain to me what is wrong? Thank you much in advance !

Updated version:

<html>
<body>

<form method="post" action="">
  Name: <input type="text" name="fname">

  <input type="submit">
</form>

<?php



if(isset($_POST['fname'])) {
    // collect value of input field
    $name = $_POST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}


?>

now there is no more error but nothing is being output to the screen with echo

  • 1
    why you are checking the request method? you can simply check if the field itself is posted or not, for example: `if(isset($_POST['fname']))` btw, check this http://stackoverflow.com/questions/12754388/serverrequest-method-does-not-exist – Mohammad May 08 '17 at 08:38
  • this removed the error , now I get this page can't be displayed when I press submit –  May 08 '17 at 08:54
  • ok this was caused by action , removed this –  May 08 '17 at 09:14
  • now I can't get any echoed output to the screen. –  May 08 '17 at 09:14
  • could you update your code plz – Mohammad May 08 '17 at 09:42
  • sure , please check –  May 08 '17 at 10:15
  • there are no errors in your code, please put this code `var_dump($_POST)` at the last line and share us the result – Mohammad May 08 '17 at 11:10

1 Answers1

1

Try using this:

$var = $GLOBALS["_SERVER"];
print_r($var);

Gotten from an answer on stackoverflow,

$request_method = strtoupper(getenv('REQUEST_METHOD'));
$http_methods = array('GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS');

    if (in_array($request_method, $http_methods)) {
    //this would only allow the above methods.
    if ($request_method == 'POST') {
        //proceed
       $name = $_POST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
    }
} else {
    die('invalid request');
}
Community
  • 1
  • 1
Rotimi
  • 4,783
  • 4
  • 18
  • 27