php-beginner Posted April 28, 2011 Share Posted April 28, 2011 Hello everyone, I want my input to stay after I have clicked submit so that if the input is wrong, a message is presented and the input stays so they don't have to write everything again. Is this the way to do it?: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head xmlns='http://www.w3.org/1999/xhtml'> <title>registration</title> <link rel="stylesheet" type="text/css" href="opmaak.css" /> </head> <body> <?php function __autoload($class){ require('classes/' . strtolower($class) . '.class.php'); } if ($_SERVER['REQUEST_METHOD'] == 'POST'){ if(isset($_POST['firstname'])){ $firstname = $_POST['firstname']; } if(isset($_POST['lastname'])){ $lastname = $_POST['lastname']; } if(isset($_POST['address'])){ $address = $_POST['address']; } if(isset($_POST['postcode'])){ $postcode = $_POST['postcode']; } if(isset($_POST['city'])){ $city = $_POST['city']; } if(isset($_POST['username'])){ $username = $_POST['username']; } if(isset($_POST['password'])){ $password = $_POST['password']; } if(isset($_POST['email'])){ $email = $_POST['email']; } if(isset($_POST['kvk'])){ $kvk = $_POST['kvk']; } try{ $user = new User; $user->createUser($firstname, $lastname, $address, $postcode, $city, $username, $password, $email, $kvk); } catch(Mysql_Exception $error){ echo $error->getError(); } echo "<html>"; echo "<head xmlns='http://www.w3.org/1999/xhtml'>"; echo "<title>registration</title>"; echo "<link rel='stylesheet' type='text/css' href='opmaak.css' />"; echo "</head>"; echo "<body>"; echo "<div id='registration_container'>"; echo "<form class='registration' method='post' action='registration.php'>"; echo "<div id='registration_left'>"; echo "<label class='user'>Voornaam: *</label> <input class='registration' type='text' size='10' maxlength='40' name='firstname' value='".$firstname."'/>"; echo "<label class='user'>Achternaam: *</label> <input class='registration' type='text' size='10' maxlength='40' name='lastname' value='".$lastname."'/>"; echo "<label class='user'>Adres: *</label> <input class='registration' type='text' size='10' maxlength='40' name='address' value='".$address."'/>"; echo "<label class='user_postcode_plaats'>Postcode / Plaats: *</label> <input class='registration_postcode' type='text' size='10' maxlength='40' name='postcode' value='".$postcode."'/>"; echo " "; echo "<input class='registration_city' type='text' size='10' maxlength='40' name='city' value='".$city."'/>"; echo "</div>"; echo "<div id='registration_right'>"; echo "<label class='user'>Gebruikersnaam: *</label> <span class='inputeisen'>4 of meer</span><input class='registration' type='text' size='10' maxlength='40' name='username' value='".$username."'/>"; echo "<label class='user'>Wachtwoord: *</label> <span class='inputeisen'>6 of meer</span><input class='registration' type='text' size='10' maxlength='40' name='password' value='".$password."'/>"; echo "<label class='user'>E-mail: *</label> <input class='registration' type='text' size='10' maxlength='40' name='email' value='".$email."'/>"; echo "<label class='user'>KvK nummer:</label> <input class='registration' type='text' size='10' maxlength='40' name='kvk' value='".$kvk."'/>"; echo "</div>"; echo "<div id='registration_bottom'>"; echo "<p>Het KvK nummer is alleen verplicht indien u wilt adverteren met uw bedrijf.<br/> U kunt dit ook later toevoegen.</p>"; echo "<input class='submit_registration_user' type='submit' value='Registreren'/>"; echo "</div>"; echo "</form>"; echo "</div>"; echo "</body>"; echo "</html>"; }else{ ?> <div id="registration_container"> <form class="registration" method="post" action="registration.php"> <div id="registration_left"> <label class="user">Voornaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="firstname"/> <label class="user">Achternaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="lastname"/> <label class="user">Adres: *</label> <input class="registration" type="text" size="10" maxlength="40" name="address"/> <label class="user_postcode_plaats">Postcode / Plaats: *</label> <input class="registration_postcode" type="text" size="10" maxlength="40" name="postcode"/> <input class="registration_city" type="text" size="10" maxlength="40" name="city"/> </div> <div id="registration_right"> <label class="user">Gebruikersnaam: *</label><span class="inputeisen">4 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="username"/> <label class="user">Wachtwoord: *</label><span class="inputeisen">6 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="password"/> <label class="user">E-mail: *</label> <input class="registration" type="text" size="10" maxlength="40" name="email"/> <label class="user">KvK nummer:</label> <input class="registration" type="text" size="10" maxlength="40" name="kvk"/> </div> <div id="registration_bottom"> <p>Het KvK nummer is alleen verplicht indien u wilt adverteren met uw bedrijf.<br/> U kunt dit ook later toevoegen.</p> <input class="submit_registration_user" type="submit" value="Registreren"/> </div> </form> </div> </body> </html> <?php } ?> Quote Link to comment Share on other sites More sharing options...
JKG Posted April 28, 2011 Share Posted April 28, 2011 if they have entered something wrong, in the error message i put this: <?php echo "<fieldset>Please make sure you have filled in all fields before sending this form. Thank You. <br /> <input type=button value=\"Back\" class=\"submit\" onClick=\"history.go(-1)\"></fieldset>"; ?> then the browser cache does all the hard work Quote Link to comment Share on other sites More sharing options...
JKG Posted April 28, 2011 Share Posted April 28, 2011 Also, its pretty hard work echo-ing all that html, just use php where you need it to do something html can't... Quote Link to comment Share on other sites More sharing options...
Undrium Posted April 28, 2011 Share Posted April 28, 2011 Also the code you're presenting is very redundant, a tips is to use the already existing HTML and inject the variables there. Quote Link to comment Share on other sites More sharing options...
php-beginner Posted April 28, 2011 Author Share Posted April 28, 2011 Also, its pretty hard work echo-ing all that html, just use php where you need it to do something html can't... Do you mean something like this? This won't work. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head xmlns='http://www.w3.org/1999/xhtml'> <title>registration</title> <link rel="stylesheet" type="text/css" href="opmaak.css" /> </head> <body> <?php function __autoload($class){ require('classes/' . strtolower($class) . '.class.php'); } if ($_SERVER['REQUEST_METHOD'] == 'POST'){ if(isset($_POST['firstname'])){ $firstname = $_POST['firstname']; } if(isset($_POST['lastname'])){ $lastname = $_POST['lastname']; } if(isset($_POST['address'])){ $address = $_POST['address']; } if(isset($_POST['postcode'])){ $postcode = $_POST['postcode']; } if(isset($_POST['city'])){ $city = $_POST['city']; } if(isset($_POST['username'])){ $username = $_POST['username']; } if(isset($_POST['password'])){ $password = $_POST['password']; } if(isset($_POST['email'])){ $email = $_POST['email']; } if(isset($_POST['kvk'])){ $kvk = $_POST['kvk']; } try{ $user = new User; $user->createUser($firstname, $lastname, $address, $postcode, $city, $username, $password, $email, $kvk); } catch(Mysql_Exception $error){ echo $error->getError(); } ?> <div id="registration_container"> <form class="registration" method="post" action="registration.php"> <div id="registration_left"> <label class="user">Voornaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="firstname" value="<?php $firstname ?>"/> <label class="user">Achternaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="lastname"/> <label class="user">Adres: *</label> <input class="registration" type="text" size="10" maxlength="40" name="address"/> <label class="user_postcode_plaats">Postcode / Plaats: *</label> <input class="registration_postcode" type="text" size="10" maxlength="40" name="postcode"/> <input class="registration_city" type="text" size="10" maxlength="40" name="city"/> </div> <div id="registration_right"> <label class="user">Gebruikersnaam: *</label><span class="inputeisen">4 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="username"/> <label class="user">Wachtwoord: *</label><span class="inputeisen">6 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="password"/> <label class="user">E-mail: *</label> <input class="registration" type="text" size="10" maxlength="40" name="email"/> <label class="user">KvK nummer:</label> <input class="registration" type="text" size="10" maxlength="40" name="kvk"/> </div> <div id="registration_bottom"> <p>Het KvK nummer is alleen verplicht indien u wilt adverteren met uw bedrijf.<br/> U kunt dit ook later toevoegen.</p> <input class="submit_registration_user" type="submit" value="Registreren"/> </div> </form> </div> </body> </html> <?php }else{ ?> <div id="registration_container"> <form class="registration" method="post" action="registration.php"> <div id="registration_left"> <label class="user">Voornaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="firstname"/> <label class="user">Achternaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="lastname"/> <label class="user">Adres: *</label> <input class="registration" type="text" size="10" maxlength="40" name="address"/> <label class="user_postcode_plaats">Postcode / Plaats: *</label> <input class="registration_postcode" type="text" size="10" maxlength="40" name="postcode"/> <input class="registration_city" type="text" size="10" maxlength="40" name="city"/> </div> <div id="registration_right"> <label class="user">Gebruikersnaam: *</label><span class="inputeisen">4 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="username"/> <label class="user">Wachtwoord: *</label><span class="inputeisen">6 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="password"/> <label class="user">E-mail: *</label> <input class="registration" type="text" size="10" maxlength="40" name="email"/> <label class="user">KvK nummer:</label> <input class="registration" type="text" size="10" maxlength="40" name="kvk"/> </div> <div id="registration_bottom"> <p>Het KvK nummer is alleen verplicht indien u wilt adverteren met uw bedrijf.<br/> U kunt dit ook later toevoegen.</p> <input class="submit_registration_user" type="submit" value="Registreren"/> </div> </form> </div> </body> </html> <?php } ?> Quote Link to comment Share on other sites More sharing options...
JKG Posted April 28, 2011 Share Posted April 28, 2011 writing out the form twice is crazy, use something like this (this is my starting point): <?php if (!isset($_POST['submit'])) { ?> <form></form> <?php } else { // Website Contact Form Generator // http://www.tele-pro.co.uk/scripts/contact_form/ // This script is free to use as long as you // retain the credit link // get posted data into local variables $EmailFrom = "Website"; $EmailTo = "email"; $Subject = "Contact from Your Website"; $Name = Trim(stripslashes($_POST['Name'])); $Contact = Trim(stripslashes($_POST['Contact'])); $Subjectmes = Trim(stripslashes($_POST['Subject'])); $Message = Trim(stripslashes($_POST['Message'])); // validation $validationOK=true; if (Trim($Name)==""){$validationOK=false;} if (Trim($Message)==""){$validationOK=false;} if (Trim($Contact)==""){$validationOK=false;} if(!$validationOK){echo "<fieldset>Please make sure you have filled in all fields before sending this form. Thank You. <br /> <input type=button value=\"Back\" class=\"submit\" onClick=\"history.go(-1)\"></fieldset>";} else { // prepare email body text $Body = ""; $Body .= "Name: "; $Body .= $Name; $Body .= "\n"; $Body .= "Contact Detail: "; $Body .= $Contact; $Body .= "\n"; $Body .= "Subject: "; $Body .= $Subjectmes; $Body .= "\n"; $Body .= "Message: "; $Body .= $Message; $Body .= "\n"; $Body .= "\n"; $Body .= "\n"; $Body .= "----------------\n"; $Body .= "Contact Form"; // send email $success = mail($EmailTo, $Subject, $Body, "From: ".$EmailFrom); // redirect to success page if ($success){ print "<fieldset>Thank you for filling in the contact form, we will be in touch as soon as we can. Thank You.</fieldset>"; } else{ print "<fieldset>Sorry, there has been an error, please try again. Thank You.</fieldset>"; }}} ?> this says, display the form, unless it has been submitted, in which case, validate the form, if thats ok, send the form. Quote Link to comment Share on other sites More sharing options...
php-beginner Posted April 28, 2011 Author Share Posted April 28, 2011 Thankyou for your reply. Also sorry for my last post. I forgot the echo xD, so it does work. If a user types in wrong characters, they get a message from my message object etc. But, when I do that the user input is gone. I don't want that. I want to hold the user input so that they don't have to rewrite everything and see what they have done wrong. In your example, the user input is not remembered. So I am forced to write my html code twice. Correct me if I'm wrong. Quote Link to comment Share on other sites More sharing options...
JKG Posted April 28, 2011 Share Posted April 28, 2011 my comment before said that browser will remember what was in those fields. so we just use a bit of javascript to go back a page, then voila! all the users data is still in the fields! Quote Link to comment Share on other sites More sharing options...
php-beginner Posted April 28, 2011 Author Share Posted April 28, 2011 Ah ok. Yes I saw that. But this is more user friendly then your way. Also, it doesn't always remember the input in some cases (that's what I've been told). But if I want it my way, I have to do it this way (right?): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head xmlns='http://www.w3.org/1999/xhtml'> <title>registration</title> <link rel="stylesheet" type="text/css" href="opmaak.css" /> </head> <body> <?php function __autoload($class){ require('classes/' . strtolower($class) . '.class.php'); } if ($_SERVER['REQUEST_METHOD'] == 'POST'){ if(isset($_POST['firstname'])){ $firstname = $_POST['firstname']; } if(isset($_POST['lastname'])){ $lastname = $_POST['lastname']; } if(isset($_POST['address'])){ $address = $_POST['address']; } if(isset($_POST['postcode'])){ $postcode = $_POST['postcode']; } if(isset($_POST['city'])){ $city = $_POST['city']; } if(isset($_POST['username'])){ $username = $_POST['username']; } if(isset($_POST['password'])){ $password = $_POST['password']; } if(isset($_POST['email'])){ $email = $_POST['email']; } if(isset($_POST['kvk'])){ $kvk = $_POST['kvk']; } try{ $user = new User; $user->createUser($firstname, $lastname, $address, $postcode, $city, $username, $password, $email, $kvk); } catch(Mysql_Exception $error){ echo $error->getError(); } ?> <div id="registration_container"> <form class="registration" method="post" action="registration.php"> <div id="registration_left"> <label class="user">Voornaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="firstname" value="<?php echo $firstname; ?>"/> <label class="user">Achternaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="lastname" value="<?php echo $lastname; ?>"/> <label class="user">Adres: *</label> <input class="registration" type="text" size="10" maxlength="40" name="address" value="<?php echo $address; ?>"/> <label class="user_postcode_plaats">Postcode / Plaats: *</label> <input class="registration_postcode" type="text" size="10" maxlength="40" name="postcode" value="<?php echo $postcode; ?>"/> <input class="registration_city" type="text" size="10" maxlength="40" name="city" value="<?php echo $city; ?>"/> </div> <div id="registration_right"> <label class="user">Gebruikersnaam: *</label><span class="inputeisen">4 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="username" value="<?php echo $username; ?>"/> <label class="user">Wachtwoord: *</label><span class="inputeisen">6 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="password" value="<?php echo $password; ?>"/> <label class="user">E-mail: *</label> <input class="registration" type="text" size="10" maxlength="40" name="email" value="<?php echo $email; ?>"/> <label class="user">KvK nummer:</label> <input class="registration" type="text" size="10" maxlength="40" name="kvk" value="<?php echo $kvk; ?>"/> </div> <div id="registration_bottom"> <p>Het KvK nummer is alleen verplicht indien u wilt adverteren met uw bedrijf.<br/> U kunt dit ook later toevoegen.</p> <input class="submit_registration_user" type="submit" value="Registreren"/> </div> </form> </div> </body> </html> <?php }else{ ?> <div id="registration_container"> <form class="registration" method="post" action="registration.php"> <div id="registration_left"> <label class="user">Voornaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="firstname"/> <label class="user">Achternaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="lastname"/> <label class="user">Adres: *</label> <input class="registration" type="text" size="10" maxlength="40" name="address"/> <label class="user_postcode_plaats">Postcode / Plaats: *</label> <input class="registration_postcode" type="text" size="10" maxlength="40" name="postcode"/> <input class="registration_city" type="text" size="10" maxlength="40" name="city"/> </div> <div id="registration_right"> <label class="user">Gebruikersnaam: *</label><span class="inputeisen">4 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="username"/> <label class="user">Wachtwoord: *</label><span class="inputeisen">6 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="password"/> <label class="user">E-mail: *</label> <input class="registration" type="text" size="10" maxlength="40" name="email"/> <label class="user">KvK nummer:</label> <input class="registration" type="text" size="10" maxlength="40" name="kvk"/> </div> <div id="registration_bottom"> <p>Het KvK nummer is alleen verplicht indien u wilt adverteren met uw bedrijf.<br/> U kunt dit ook later toevoegen.</p> <input class="submit_registration_user" type="submit" value="Registreren"/> </div> </form> </div> </body> </html> <?php } ?> Quote Link to comment Share on other sites More sharing options...
JKG Posted April 28, 2011 Share Posted April 28, 2011 ok, why not just have one form but do this on your fields: <input class="registration_postcode" type="text" size="10" maxlength="40" name="postcode" <?php if(isset($_POST['postcode'])){echo 'value="'.$_POST['postcode'].'"';} ?>/> Quote Link to comment Share on other sites More sharing options...
Muddy_Funster Posted April 28, 2011 Share Posted April 28, 2011 my comment before said that browser will remember what was in those fields. so we just use a bit of javascript to go back a page, then voila! all the users data is still in the fields! You should never depend on javascript to do anything. javascript is an optional enhancement, not a core component. Quote Link to comment Share on other sites More sharing options...
php-beginner Posted April 28, 2011 Author Share Posted April 28, 2011 ok, why not just have one form but do this on your fields: <input class="registration_postcode" type="text" size="10" maxlength="40" name="postcode" <?php if(isset($_POST['postcode'])){echo 'value="'.$_POST['postcode'].'"';} ?>/> Great fix, thankyou (no it was not, see next comment(s)) Quote Link to comment Share on other sites More sharing options...
JKG Posted April 28, 2011 Share Posted April 28, 2011 @Muddy_Funster ...true... Quote Link to comment Share on other sites More sharing options...
php-beginner Posted April 28, 2011 Author Share Posted April 28, 2011 @JKG No it was not a fix, I am very sorry xD This is because I check if the form has been submitted. If so, then show errors with the user input in form. If not, then show the normal form. This means that with this fix, the user can only see the form if it has been submitted. So users that didn't filled in the form, they can't fill it in because they cannot see it. So this is still the best way i think: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head xmlns='http://www.w3.org/1999/xhtml'> <title>registration</title> <link rel="stylesheet" type="text/css" href="opmaak.css" /> </head> <body> <?php function __autoload($class){ require('classes/' . strtolower($class) . '.class.php'); } if ($_SERVER['REQUEST_METHOD'] == 'POST'){ if(isset($_POST['firstname'])){ $firstname = $_POST['firstname']; } if(isset($_POST['lastname'])){ $lastname = $_POST['lastname']; } if(isset($_POST['address'])){ $address = $_POST['address']; } if(isset($_POST['postcode'])){ $postcode = $_POST['postcode']; } if(isset($_POST['city'])){ $city = $_POST['city']; } if(isset($_POST['username'])){ $username = $_POST['username']; } if(isset($_POST['password'])){ $password = $_POST['password']; } if(isset($_POST['email'])){ $email = $_POST['email']; } if(isset($_POST['kvk'])){ $kvk = $_POST['kvk']; } try{ $user = new User; $user->createUser($firstname, $lastname, $address, $postcode, $city, $username, $password, $email, $kvk); } catch(Mysql_Exception $error){ echo $error->getError(); } ?> <div id="registration_container"> <form class="registration" method="post" action="registration.php"> <div id="registration_left"> <label class="user">Voornaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="firstname" value="<?php echo $firstname; ?>"/> <label class="user">Achternaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="lastname" value="<?php echo $lastname; ?>"/> <label class="user">Adres: *</label> <input class="registration" type="text" size="10" maxlength="40" name="address" value="<?php echo $address; ?>"/> <label class="user_postcode_plaats">Postcode / Plaats: *</label> <input class="registration_postcode" type="text" size="10" maxlength="40" name="postcode" value="<?php echo $postcode; ?>"/> <input class="registration_city" type="text" size="10" maxlength="40" name="city" value="<?php echo $city; ?>"/> </div> <div id="registration_right"> <label class="user">Gebruikersnaam: *</label><span class="inputeisen">4 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="username" value="<?php echo $username; ?>"/> <label class="user">Wachtwoord: *</label><span class="inputeisen">6 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="password" value="<?php echo $password; ?>"/> <label class="user">E-mail: *</label> <input class="registration" type="text" size="10" maxlength="40" name="email" value="<?php echo $email; ?>"/> <label class="user">KvK nummer:</label> <input class="registration" type="text" size="10" maxlength="40" name="kvk" value="<?php echo $kvk; ?>"/> </div> <div id="registration_bottom"> <p>Het KvK nummer is alleen verplicht indien u wilt adverteren met uw bedrijf.<br/> U kunt dit ook later toevoegen.</p> <input class="submit_registration_user" type="submit" value="Registreren"/> </div> </form> </div> </body> </html> <?php }else{ ?> <div id="registration_container"> <form class="registration" method="post" action="registration.php"> <div id="registration_left"> <label class="user">Voornaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="firstname"/> <label class="user">Achternaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="lastname"/> <label class="user">Adres: *</label> <input class="registration" type="text" size="10" maxlength="40" name="address"/> <label class="user_postcode_plaats">Postcode / Plaats: *</label> <input class="registration_postcode" type="text" size="10" maxlength="40" name="postcode"/> <input class="registration_city" type="text" size="10" maxlength="40" name="city"/> </div> <div id="registration_right"> <label class="user">Gebruikersnaam: *</label><span class="inputeisen">4 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="username"/> <label class="user">Wachtwoord: *</label><span class="inputeisen">6 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="password"/> <label class="user">E-mail: *</label> <input class="registration" type="text" size="10" maxlength="40" name="email"/> <label class="user">KvK nummer:</label> <input class="registration" type="text" size="10" maxlength="40" name="kvk"/> </div> <div id="registration_bottom"> <p>Het KvK nummer is alleen verplicht indien u wilt adverteren met uw bedrijf.<br/> U kunt dit ook later toevoegen.</p> <input class="submit_registration_user" type="submit" value="Registreren"/> </div> </form> </div> </body> </html> <?php } ?> Quote Link to comment Share on other sites More sharing options...
JKG Posted April 28, 2011 Share Posted April 28, 2011 in that case, just dont wrap the whole form around the if statement. put your 'send form php' above or below the form. Quote Link to comment Share on other sites More sharing options...
KevinM1 Posted April 28, 2011 Share Posted April 28, 2011 The standard pattern for all PHP apps is to process first, then output. So, here's what you do: 1. Remove your autoload code from being hard coded in this page. Instead, put it in a file and include or require it. This will allow you to have autoload in all of your pages with only one line of code rather than needing to write the entire thing over and over. 2. Change your if-conditional from: if ($_SERVER['REQUEST_METHOD'] == 'POST'){ to: if (isset($_POST['submit'])){ After giving your submit button the name of 'submit'. Right now, you're only checking if any POST data was sent, and not if the submit button was actually pressed. It doesn't do much for security, but it is slightly more restrictive than what you currently have. 3. Validate and sanitize your inputs. Never trust incoming data, especially if it's supplied by an end user. 4. Like I said above, process first, then output. So, don't place ANY HTML above your PHP. This includes your doctype declaration, and all the rest. You want: <?php /* all of your non-display PHP code here, * including your inclusion of your autoload * and all of your form handling code * with that said, here's the common pattern * for sticky forms */ if (isset($_POST['submit'])) { // all form handling here if (/* all inputs are valid */) { // try saving data if (/* everything saved correctly */) { // redirect user if everything is saved correctly } else { // error - display on the form } } else { // error - display on the form } } /* Notice there's NO else clause. * Why? Two reasons: * 1. This will make the form be displayed if the submit button WASN'T pressed (the if-conditional failed) * 2. This will make the form be displayed if there are any errors. An else clause would block that */ ?> <!DOCTYPE <!-- ... --> > <!-- All the rest of your HTML --> The only PHP you should have in your HTML is code which will redisplay input values. For that, do what JKG said, and check if they're set before attempting to output them. Why do it this way? There are a couple of reasons. First, it makes your code easier to write, read, and understand. Second, it saves you from those pesky "Headers already sent" errors when you try to use a header redirect or sessions. Since you're likely going to redirect the user when the form submission is successful (it's not like they'll need to see the form again), this makes your job a lot easier. Quote Link to comment Share on other sites More sharing options...
php-beginner Posted April 28, 2011 Author Share Posted April 28, 2011 @JKG Lol. I feel like a fool now Thankyou! @Nightslyr Thankyou for your explanation. I will update my code and never forget that because I had that error once. But the whole input validation is already done. The user object and the objects within the user object take care of this. Quote Link to comment Share on other sites More sharing options...
php-beginner Posted April 28, 2011 Author Share Posted April 28, 2011 I thaught that this was better? if ($_SERVER['REQUEST_METHOD'] == 'POST'){ People told me that this is more secure. Also a dutch website confirms this: http://www.pfz.nl/wiki/isset-vs-request-method/ Quote Link to comment Share on other sites More sharing options...
php-beginner Posted April 28, 2011 Author Share Posted April 28, 2011 Also the doctype should still be above the php because when I submit the form, this is what happens: Oops...<ul><li>Uw voornaam voldoet niet aan de eisen.</li><li>Uw achternaam voldoet niet aan de eisen.</li><li>Uw adres voldoet niet aan de eisen.</li><li>Uw postcode voldoet niet aan de eisen.</li><li>De plaatsnaam voldoet niet aan de eisen.</li><li>De gebruikersnaam voldoet niet aan de eisen.</li><li>Het wachtwoord voldoet niet aan de eisen.</li><li>Ongeldig e-mailadres.</li></ul> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>registration</title> <link rel="stylesheet" type="text/css" href="opmaak.css" /> </head> //etc The <ul> isn't presented under the doctype. Or did I misunderstood something? Quote Link to comment Share on other sites More sharing options...
KevinM1 Posted April 28, 2011 Share Posted April 28, 2011 All your PHP code should be above your HTML. Where is your <ul> coming from? Also, I can't read Dutch, so I can't tell what that article is saying. What $_SERVER['Request_'Method] does is return what request method (GET or POST) was used in accessing your script. Your current if-conditional simply says: "If this was accessed via POST, then handle the form". That really isn't any different than asking whether or not $_POST['submit'] is set. Why? Because $_POST['submit'] will only exist if it was POSTed to the script anyway. Like I said before, checking whether the submit button was pressed doesn't do much aside from providing one more value to check. I personally like checking the button because it's a bit shorter to write, it fits the standard pattern, and it gives someone trying to get into my system an extra input to account for. Not a lot of security help, but I'll take what I can get. And again, to be abundantly clear, I'm not trying to suggest it's a change that will have an appreciable impact on your site security. I'm mostly trying to point out that using $_SERVER['Request_Method'] in this manner does nothing to make your site more secure. For security, real security, you need to: Validate and sanitize all incoming data, which means checking each form field not only contains a value, but contains a properly formed value. So, if a field requires a number, you need to verify it only contains numeric characters, or if you're storing string data in the db, you may want to check for potentially harmful characters like ';'. This is where regular expressions come into play. You need to run any string data that is structurally valid through your database's escape function (like mysql_real_escape_string) to combat SQL injection attacks. You should also setup an anti-forgery token (google cross-site request forgery for more info). Using $_SERVER['Request_Method'] won't make your site more secure. Quote Link to comment Share on other sites More sharing options...
php-beginner Posted April 28, 2011 Author Share Posted April 28, 2011 Allright. Well, like I said, I already have a form validator, mysql_real_escape_string, etc. This is all done by different classes. My problem is now that my message class outputs this error but this is not done within the doctype. So I have a bunch of classes inside the user class that handle this registration. The user class checks with other classes if the input is correct etc and if user already exist etc and if not a message is echo'ed by my message class. Now I know that echoing inside a class/object is not the best method, that turns out now So what is the best way to get the errors outputted inside the doctype? Do I have to return the message and echo it somewhere else? If so, where? So far, thankyou for your help. Quote Link to comment Share on other sites More sharing options...
KevinM1 Posted April 28, 2011 Share Posted April 28, 2011 I can't give you the best course of action without seeing where your messages are formed, and where they're being outputted from. Quote Link to comment Share on other sites More sharing options...
php-beginner Posted April 28, 2011 Author Share Posted April 28, 2011 My registration form: <?php function __autoload($class){ require('classes/' . strtolower($class) . '.class.php'); } if ($_SERVER['REQUEST_METHOD'] == 'POST'){ if(isset($_POST['firstname'])){ $firstname = $_POST['firstname']; } if(isset($_POST['lastname'])){ $lastname = $_POST['lastname']; } if(isset($_POST['address'])){ $address = $_POST['address']; } if(isset($_POST['postcode'])){ $postcode = $_POST['postcode']; } if(isset($_POST['city'])){ $city = $_POST['city']; } if(isset($_POST['username'])){ $username = $_POST['username']; } if(isset($_POST['password'])){ $password = $_POST['password']; } if(isset($_POST['email'])){ $email = $_POST['email']; } if(isset($_POST['kvk'])){ $kvk = $_POST['kvk']; } try{ $user = new User; $user->createUser($firstname, $lastname, $address, $postcode, $city, $username, $password, $email, $kvk); } catch(Mysql_Exception $error){ echo $error->getError(); } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>registration</title> <link rel="stylesheet" type="text/css" href="opmaak.css" /> </head> <body> <div id="registration_container"> <form class="registration" method="post" action="registration.php"> <div id="registration_left"> <label class="user">Voornaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="firstname" <input class="registration_postcode" type="text" size="10" maxlength="40" name="postcode" value="<?php if(isset($firstname)){echo $firstname;} ?>"/> <label class="user">Achternaam: *</label> <input class="registration" type="text" size="10" maxlength="40" name="lastname" value="<?php if(isset($lastname)){echo $lastname;} ?>"/> <label class="user">Adres: *</label> <input class="registration" type="text" size="10" maxlength="40" name="address" value="<?php if(isset($address)){echo $address;} ?>"/> <label class="user_postcode_plaats">Postcode / Plaats: *</label> <input class="registration_postcode" type="text" size="10" maxlength="40" name="postcode" value="<?php if(isset($postcode)){echo $postcode;} ?>"/> <input class="registration_city" type="text" size="10" maxlength="40" name="city" value="<?php if(isset($city)){echo $city;} ?>"/> </div> <div id="registration_right"> <label class="user">Gebruikersnaam: *</label><span class="inputeisen">4 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="username" value="<?php if(isset($username)){echo $username;} ?>"/> <label class="user">Wachtwoord: *</label><span class="inputeisen">6 of meer</span> <input class="registration" type="text" size="10" maxlength="40" name="password" value="<?php if(isset($password)){echo $password;} ?>"/> <label class="user">E-mail: *</label> <input class="registration" type="text" size="10" maxlength="40" name="email" value="<?php if(isset($email)){echo $email;} ?>"/> <label class="user">KvK nummer:</label> <input class="registration" type="text" size="10" maxlength="40" name="kvk" value="<?php if(isset($kvk)){echo $kvk;} ?>"/> </div> <div id="registration_bottom"> <p>Het KvK nummer is alleen verplicht indien u wilt adverteren met uw bedrijf.<br/> U kunt dit ook later toevoegen.</p> <input class="submit_registration_user" type="submit" value="Registreren"/> </div> </form> </div> </body> </html> My user class (not finished yet): <?php class User{ private $formValidator; private $encryption; private $message; private $mysql; private $query; private $session; private $setQuery; private $row; private $username; private $password; private $activationkey; private $alreadyExist = false; public function __construct(){ $this->formValidator = new Form_Validator; $this->encryption = new Encryption; $this->message = new Message; $this->mysql = new Mysql; $this->query = new Query; $this->session = new Session; } public function login($username, $password){ $this->username = $this->mysql->escapeString($username); $this->password = $this->mysql->escapeString($password); if($this->formValidator->isInvalid($username) || $this->formValidator->isInvalid($password)){ $this->message->addMessages('invalid', 'U heeft ongeldige karakters ingevuld.'); } if($this->message->messageStatus != false){ $this->message->showMessages(); } if($this->formValidator->validatorStatus == false){ $this->password = $this->encryption->encryptPassword($password); $this->setQuery = "SELECT userid FROM users WHERE username='" . $this->username . "' AND password='" . $this->password . "'"; $this->query->runQuery($this->setQuery); if($this->query->returnNumRows() > 0){ $this->setQuery = "SELECT username FROM users WHERE username = '".$this->username."'"; $this->query->runQuery($this->setQuery); $this->row = $this->query->returnFetchArray(); echo "Welkom ".$this->session->createSession($this->row['username']).". "."U bent succesvol ingelogd."; }else{ $this->message->addMessages('invalid_data', 'Uw logingegevens kloppen niet.'); $this->message->showMessages(); } } } public function createUser($firstname, $lastname, $address, $postcode, $city, $username, $password, $email, $kvk){ $this->firstname = $this->mysql->escapeString($firstname); $this->lastname = $this->mysql->escapeString($lastname); $this->address = $this->mysql->escapeString($address); $this->postcode = $this->mysql->escapeString($postcode); $this->city = $this->mysql->escapeString($city); $this->username = $this->mysql->escapeString($username); $this->password = $this->mysql->escapeString($password); $this->email = $this->mysql->escapeString($email); $this->kvk = $this->mysql->escapeString($kvk); if($this->formValidator->isInvalidFirstname($firstname)){ $this->message->addMessages('invalid_firstname', 'Uw voornaam voldoet niet aan de eisen.'); } if($this->formValidator->isInvalidLastname($lastname)){ $this->message->addMessages('invalid_lastname', 'Uw achternaam voldoet niet aan de eisen.'); } if($this->formValidator->isInvalidAddress($address)){ $this->message->addMessages('invalid_address', 'Uw adres voldoet niet aan de eisen.'); } if($this->formValidator->isInvalidPostcode($postcode)){ $this->message->addMessages('invalid_postcode', 'Uw postcode voldoet niet aan de eisen.'); } if($this->formValidator->isInvalidCity($city)){ $this->message->addMessages('invalid_city', 'De plaatsnaam voldoet niet aan de eisen.'); } if($this->formValidator->isInvalidUsername($username)){ $this->message->addMessages('invalid_username', 'De gebruikersnaam voldoet niet aan de eisen.'); } if($this->formValidator->isInvalidPassword($password)){ $this->message->addMessages('invalid_password', 'Het wachtwoord voldoet niet aan de eisen.'); } if($this->formValidator->isInvalidEmail($email)){ $this->message->addMessages('invalid_email', 'Ongeldig e-mailadres.'); } if($this->formValidator->isInvalidKvk($kvk)){ $this->message->addMessages('invalid_kvk', 'Ongeldig KvK nummer.'); } if($this->message->messageStatus != false){ $this->message->showMessages(); } if($this->formValidator->validatorStatus == false){ if($this->alreadyExist == false){ $this->setQuery = "SELECT username FROM users WHERE username='" . $this->username . "'"; $this->query->runQuery($this->setQuery); if($this->query->returnNumRows() > 0){ $this->alreadyExist = true; $this->message->addMessages('username_already_exist', 'Gebruikersnaam bestaat al.'); $this->message->showMessages(); }elseif($this->alreadyExist == false){ $this->setQuery = "SELECT email FROM users WHERE email='" . $this->email . "'"; $this->query->runQuery($this->setQuery); if($this->query->returnNumRows() > 0){ $this->alreadyExist = true; $this->message->addMessages('email_already_exist', 'Er is al een account geregistreerd op dit e-mailadres.'); $this->message->showMessages(); }else{ $this->password = $this->encryption->encryptPassword($password); $this->activationkey = mt_rand() . mt_rand() . mt_rand(); $this->setQuery = " INSERT INTO users (status, username, password, email, activationkey, rights, firstname, lastname, address, postcode, city, kvk) VALUES ('Verify', '".$this->username."', '".$this->password."', '".$this->email."', '".$this->activationkey."', 1, '".$this->firstname."', '".$this->lastname."', '".$this->address."', '".$this->postcode."', '".$this->city."', '".$this->kvk."') "; $this->query->runQuery($this->setQuery); echo "U bent geregistreert. Controleer uw e-mailadres om uw account te activeren."; } } } } } } ?> My message class: <?php class Message{ public $messageStatus = false; public $errorMessages = array(); public function addMessages($type, $message) { if ($type != null && $message != null){ $this->messageStatus = true; $this->errorMessages[$type] = $message; }else{ // error } } public function showMessages() { echo 'Oops...'; echo '<ul>'; foreach ($this->errorMessages as $msg){ echo '<li>'. $msg .'</li>'; } echo '</ul>'; } } ?> Quote Link to comment Share on other sites More sharing options...
php-beginner Posted April 28, 2011 Author Share Posted April 28, 2011 Correct me if I'm wrong but, if the error messages should be at the beginning of the page like the rest of the php code then the error message will be above the doctype. So the error message script should be set in the html part? Quote Link to comment Share on other sites More sharing options...
KevinM1 Posted April 29, 2011 Share Posted April 29, 2011 Correct me if I'm wrong but, if the error messages should be at the beginning of the page like the rest of the php code then the error message will be above the doctype. So the error message script should be set in the html part? Like I said before, it's okay to have display logic (read: little bits of PHP that are only used to output values) within your HTML. PHP that actually processes data should be placed above your HTML (or, in larger systems, within separate files altogether). Look into Separation of Concerns and the MVC pattern. EDIT: Okay, your User is automatically spitting out error messages, which is why you're getting a <ul> before your HTML officially begins. You'll need to rework it so you output errors within your HTML. To do this, you'll need to figure out a way to hold onto your errors before outputting them. Instead of having your User contain a FormValidator, you may be better off passing the User to FormValidator as a parameter to a validation method. Something like: <?php $validator = new FormValidator(); $tmpUser = User::create(/* form values */); // look into static methods and the Factory Method pattern if ($validator->isValidUser($tmpUser)) { $tmpUser->login(); } else { $errors = $validator->getErrors(); } ?> <!doctype html> <html> <!-- head tag, and all that jazz --> <?php if (isset($errors)) { echo $errors; } ?> <!-- more HTML --> </html> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.