"Undefined variable" in contact form

Alles, was PHP betrifft, kann hier besprochen werden.

"Undefined variable" in contact form

Postby c_bauer » 18. August 2017 21:28

Hi all!

My deliberately kept-simple contact form works without errors when uploaded to my webspace, but XAMPP throws several "Notice: Undefined variable" warnings.

Is this to be expected?

This is the entire code from index.php:

Code: Select all

<?php
   if (isset($_POST["submit"])) {
      $name = $_POST['name'];
      $email = $_POST['email'];
      $message = $_POST['message'];

      $from = 'Demo Contact Form';
      $to = 'example@mail.com';
      $subject = 'Message from Contact Demo';
      
      $body ="From: $name\n E-Mail: $email\n Message:\n $message";
      // Check if name has been entered
      if (!$_POST['name'])
      {
         $errName = 'Please enter your name';
      }
      
      // Check if email has been entered and is valid
      if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
      {
         $errEmail = 'Please enter a valid email address';
      }
      
      //Check if message has been entered
      if (!$_POST['message'])
      {
         $errMessage = 'Please enter your message';
      }
      
      // If there are no errors, send the email
      if (!$errName && !$errEmail && !$errMessage)
      {
         if (mail ($to, $subject, $body, $from))
         {
            $result='<div>Thank You!</div>';
         }
         else    
         {
            $result='<div>Sorry there was an error sending your message. Please try again later.</div>';
         }
      }
   }
?>


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Contact Form With PHP Example</title>
   </head>
 
  <body>
   
      <form action="index.php" method="post">
            
         <label for="name">Name</label>               
         <input type="text" id="name" name="name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
         <?php echo "<p>$errName</p>";?>


         <label for="email">Email</label>            
         <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($_POST['email']); ?>">
         <?php echo "<p>$errEmail</p>";?>

   
         <label for="message">Message</label>
         <textarea rows="4" name="message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
         <?php echo "<p>$errMessage</p>";?>
               
               
         <input type="submit" id="submit" name="submit" value="Send" class="btn btn-primary">


         <?php echo $result; ?>   
         
         </form>

  </body>
</html>



Thank you!
Chris
c_bauer
 
Posts: 3
Joined: 18. August 2017 21:21
XAMPP version: 5.6.30
Operating System: Windows 10

Re: "Undefined variable" in contact form

Postby JJ_Tagy » 19. August 2017 00:50

You can turn off the notices in your php.ini
JJ_Tagy
 
Posts: 788
Joined: 30. January 2012 13:44
XAMPP version: 5.5.15
Operating System: Windows 10 Pro x64

Re: "Undefined variable" in contact form

Postby c_bauer » 20. August 2017 01:52

Thanks, that worked.

Still, is there a proper way to get rid of the warnings?
Like why does the PHP interpreter thinks these variables don't exist ?

Thank you!
c_bauer
 
Posts: 3
Joined: 18. August 2017 21:21
XAMPP version: 5.6.30
Operating System: Windows 10

Re: "Undefined variable" in contact form

Postby Nobbie » 20. August 2017 10:07

c_bauer wrote:Still, is there a proper way to get rid of the warnings?


Of course. dont make these errors. Its your code and you specified variables, which do not exist in a certain context.

c_bauer wrote:Like why does the PHP interpreter thinks these variables don't exist ?


Its just vice verse, YOU think, these variables exist, but they dont. The problem is, that your script is called in TWO different request types. As you specified in the form, the script is called with method POST. Thats ok and all $_POST variables do exist.

BUT: as you also have the formular included in your script, you call index.php not only in the form, you also call it via browser URL like http://www.domain.com/index.php and that results in method GET. If you call your form for the first time in your browser, the request type is GET, therefore there is NO array $_POST and therefore you get a notice, that your script is referring to a couple of unknown variables. The PHP interpreter is perfectly right with that, its yourself who is going wrong.

For that reason i dont like this style of programming and mix the form with the action script. As usually the action script is called with method POST, whereas the formular is called with GET. I would put the corresponding code into two different files, one HTML formular and one action script.
Nobbie
 
Posts: 13165
Joined: 09. March 2008 13:04

Re: "Undefined variable" in contact form

Postby c_bauer » 22. August 2017 00:12

That makes a great deal of sense.

I think I understand how it all works in a single file (php above html, file ending is .php to invoke the php interpreter) but what if I have a separate action script?
Lets say index.php includes the html code of the <form>, which calls contact_form.php. How would contact_form.php report back to index.php, to modify the html markup as needed, indicate missing input and so on?

Chris
c_bauer
 
Posts: 3
Joined: 18. August 2017 21:21
XAMPP version: 5.6.30
Operating System: Windows 10

Re: "Undefined variable" in contact form

Postby Nobbie » 22. August 2017 10:12

There is no "report back" in HTML. There is only forward. You have to create a formular as well in the action script as in index.php. To avoid problems, that you might create different looking forms, i recommend the usage of include() function and refer to a single HTML form as well from your index.php as from your action.php (or whatever you call it).

Example: index.php (or contact.php or whatever)

Code: Select all
<?php
     $name = "Please insert name here....";
     $email = "Please insert email here....";
....

    include("form.php");
>?


Then the action.php:

Code: Select all
<?php
      $name = $_POST['name'];
      $email = $_POST['email'];
      $message = $_POST['message'];
....
     include("form.php");
?>


And finally your form.php

Code: Select all
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Contact Form With PHP Example</title>
   </head>
 
  <body>
   
      <form action="action.php" method="post">
           
         <label for="name">Name</label>               
         <input type="text" id="name" name="name" value="<?php echo $name;?>">
         <?php echo "<p>$errName</p>";?>


         <label for="email">Email</label>           
         <input type="email" id="email" name="email" value="<?php echo $email; ?>">
         <?php echo "<p>$errEmail</p>";?>

   
         <label for="message">Message</label>
         <textarea rows="4" name="message"><?php $message;?></textarea>
         <?php echo "<p>$errMessage</p>";?>
               
               
         <input type="submit" id="submit" name="submit" value="Send" class="btn btn-primary">


         <?php echo $result; ?>   
         
         </form>

  </body>
</html>


As you see, the form does NOT use $_POST variables, but the plain variables $name etc. - this makes it independent from GET or POST Request. The code to fill these variables with proper value is given in index.php and action.php, before the form.php is included. The include (which basically results in the output of the HTML code) always should be the very last step in your scripts. This way of programming is the "state of the art" of how to seperate functional code and input/output code.

As you also see, there are a couple of similar php constructs, which are used to show the value of a PHP variable, its like this:

Code: Select all
<php echo $name;?>


There is a special construct in PHP (you must remember, PHP has been a simple template engine in the very first releases), which beautifys the code extremely (i very much like this construct, meanwhile the developers are thinking about dropping the syntax, but that would really be very sad), you can use this syntax instead:

Code: Select all
<?=$name?>


I am not sure if "short_open_tag" in php.ini is required for that syntax, but you should simply give it a try. See how nice it makes your form looking:

Code: Select all
<form action="action.php" method="post">
           
         <label for="name">Name</label>               
         <input type="text" id="name" name="name" value="<?=$name?>">
         <p><?=$errName?></p>
...
Nobbie
 
Posts: 13165
Joined: 09. March 2008 13:04


Return to PHP

Who is online

Users browsing this forum: No registered users and 40 guests