Breaking out of a PHP script - php

I have a simple form below where I check for zero field values in a submitted form. If I find a zero field I set the $register_failed_message accordingly, identifying the field. At that point I just want to skip the rest of the form processing and display the form because the form includes a
<?=$register_failed_message?>
to tell the user, right on the form, what the problem is.
But it's not clear how to break out of the processing loop and jump down to the form display HTML. I have exits there, now, but that's not going to work because they stop the entire script. I need a goto to ?>.
Is there a standard way to program this kind of thing?
Thanks
<?php
if(!empty($_POST)){
// Form was submitted.
if(empty($_POST['firstName'])) {
$register_failed_message = "Please enter a firstName.";
exit;
}
if(empty($_POST['lastName'])) {
$register_failed = "Please enter a lastName.";
exit;
}
if(empty($_POST['email'])) {
$register_failed = "Please enter an email.";
exit;
}
[Process form]
header("Location: login.php");
exit;
}
?>
<!doctype html>
<!-- HTML5 -->
<html>
<head>
<body>
<div id="content">
<h2 id="heading">Open a Free Account . . .</h2>
<form id='register' action=<?= $_SERVER["PHP_SELF"] ?> autocomplete="off" method="post">
<div id='fname_label' class='label'>First Name:</div>
<input id='fname' type="text" name="firstName" />
<div id='lname_label' class='label'>Last Name:</div>
<input type="text" name="lastName" />
<div id='email_label' class='label'>Email:</div>
<input type="text" name="email" autocomplete="off" />
<input id='register_button' type="submit" value="Open your Free Account" />
</form>
<div id='register_failed'><?=$register_failed_message?></div>
</div>
</div>
</body>
</head>
</html>

There are a couple problems with your code. Firstly, you have two message variables, $register_failed_message and $register_failed, but you only reference one later. Secondly, your messages are going to overwrite each other. If you put them in an array, you can display all the messages, not just one, if necessary.
Here is how you do what you're trying to do, plus those two mistakes fixed.
<?php
$register_failed = array();
if(!empty($_POST)){
// Form was submitted.
if(empty($_POST['firstName'])) {
$register_failed[] = "Please enter a firstName.";
}
if(empty($_POST['lastName'])) {
$register_failed[] = "Please enter a lastName.";
}
if(empty($_POST['email'])) {
$register_failed[] = "Please enter an email.";
}
//If there are no error messages, we can process the form
if(sizeof($register_failed) == 0) { //This means there are 0 messages collected
[Process form]
header("Location: login.php");
exit; //we exit here to get to the other page
}
}
?>
Later:
<div id='register_failed'>
<?php echo implode('<br>',$register_failed); ?>
</div>

<?php
$register_failed_message = '';
if(isset($_POST))
{
// Form was submitted.
$error = array();
if(empty($_POST['firstName']))
{
$error[] = "Please enter a firstName.";
}
if(empty($_POST['lastName']))
{
$error[] = "Please enter a lastName.";
}
if(!preg_match('#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+#([0-9.]+|([^\s]+\.+[a-z]{2,6}))$#si', $_POST['email']))
{
$error[] = "Please enter an email.";
}
if(count($register_failed_message) == 0)
{
header("Location: login.php");
die();
}
$register_failed_message = implode('<br />',$error);
}
?>

You can break out of scripts with "return", but it will stop the page content too.
You can put your script into another file, use "return" to stop your script, and then include it on the page you have provided.

I was going to just suggest break() as I did in the comments, but that is not your best solution here. You really don't want to throw a message "please enter a first name" and have them enter a first name THEN throw ANOTHER message "please enter a last name". So don't break, just gather ALL the error messages and display them:
(also did you notice that you named the the message inconsistently?)
<?php
if(!empty($_POST)){
// Form was submitted.
$register_failed_message = "";
if(empty($_POST['firstName'])) {
$register_failed_message .= "Please enter a firstName.<br />";
}
if(empty($_POST['lastName'])) {
$register_failed_message .= "Please enter a lastName.<br />";
}
if(empty($_POST['email'])) {
$register_failed_message .= "Please enter an email.<br />";
}
header("Location: login.php");
}
?>
Notice how I use .= . This is a handy shortcut that means "append to" instead of "set to".

Related

Display form validation error message on same page using only PHP?

I'm very new to PHP and I've cobbled this together from some other answers on here. Can anyone show me how to get the $errMsg to display? At present, a blank or incorrect name leads to a blank page. Is this because the form isn't being displayed again? If so, how should I go about 'reloading' the form with the error message?
<?php
$name = "Fred";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["name"])) {
if ($_POST["name"] == $name) {
include("welcomeFred.php");
}
else {
$errMsg = "Incorrect name";
}
}
else {
$errMsg = "Name required";
}
}
else { ?>
<html>
...
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" required>
<span><?php echo $errMsg;?></span>
<input type="submit" value="Submit">
</form>
...
</html>
<?php } ?>
You shouldn't put the rendering of the form in the else of your if structure. This is the reason your form isn't loaded when you submit the form.
Remove the else { ?> and <?php } ?> at the end of your file and it should work fine.

Redirecting page to a Success page if server validation is positive

I have a form with an action that is linked to the same PHP page contact.php. I have all the server side validation inside the form and it's all fine. It redirects the user to the same page with error messages echoed if needed while making the form STICKY (that is the main point of using the same page for errors).
What I would like is for there to be a success page redirect if the form was okay. I've read other posts on how to implement this, but I don't quite understand how to implement it in my code.
<?php
$fullname = $email = $reason = $contactbox = '';
$fullnameerr = $emailerr = $reasonerr = $contactboxerr = '';
if(data_post('submit')){
if(empty(data_post('firstname'))){
$fullnameerr = "Please enter a valid name";
}
else {
$fullname = clean_data(data_post('firstname'));
if (!preg_match("/^[a-zA-Z '']*$/", $fullname)){
$fullnameerr = "Please enter only alphabetical characters and white spaces";
}
}
if(empty(data_post('email'))){
$emailerr = "Please enter a valid e-mail";
}
else {
$email = clean_data(data_post('email'));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailerr = "Please enter a correct e-mail format (ex 'joe#cornell.edu')";
}
}
if(empty(data_post('reason'))){
$reasonerr = "Please select a reason for contact";
}
else{
$reason = clean_data(data_post('reason'));
}
if(empty(data_post('contacttext'))){
$contactboxerr = "Please elaborate on your reason";
}
else{
$contactbox = clean_data(data_post('contacttext'));
if(!preg_match("/^[\w\S\s]*$/", $contactbox )){
$contactboxerr = "Please enter only valid characters you would use in writing (ex 'abcABC123')";
}
if(strlen($contactbox) > 2000){
$contactboxerr = "Please enter a response with with a max of 2000 characters.";
}
}
}
function clean_data($field){
$field = trim($field);
$field = stripslashes($field);
return $field;
}
function data_post($param){
if (isset($_POST[$param])){
return $_POST[$param];
}
else{
return '';
}
}
?>
With this being the code for the form:
<div class="sidesection" id="survey">
<h3>Contact Form</h3>
<form action="contact.php" method="POST" novalidate>
<span class="required_asterick">* Is Required</span>
<fieldset>
<legend>Contact Us</legend>
<span class="required_asterick">* </span><label>Name:</label><span class="help" data-tooltip="Please enter a valid name (Ex. 'John Doe')"></span><br />
<input type="text" name="firstname" required pattern="[a-zA-Z '']+" maxlength="25" title="Enter only characters from (a-z) and (A-Z)" value="<?php echo "$fullname";?>"><span class="errormessage"><?php echo "$fullnameerr";?></span><br /><br />
<span class="required_asterick">* </span><label>Email:</label><span class="help" data-tooltip="Please enter a valid email with a max of 50 characters. (Ex. 'xxx#yyy.com')"></span><br />
<input type="email" name="email" required maxlength="50" value="<?php echo "$email";?>">
<span class="errormessage"><?php echo "$emailerr"; ?></span><br /><br />
<span class="required_asterick">* </span><label>Reason For Contact:</label>
<select name="reason" required>
<option value=""> </option>
<option value="general">General</option>
<option value="concern">Concern</option>
<option value="feedback">Feedback</option>
</select><span class="help" data-tooltip="Choose a topic for which you are contacting us so we can process your request faster. General is for any broad topics not listed. Concern is for any pressing matter you may have about the Ithaca Apple Harvest Festival. Feedback is for any suggestions or opinions you wish to share with us about our festivals. "></span><span class="errormessage"><?php echo "$reasonerr";?></span><br /> <br />
<span class="required_asterick">* </span><label>What Would You Like To Tell Us?</label><span class="help" data-tooltip="Use this section to write what you are contacting us for."></span><br />
<textarea name="contacttext" rows="7" cols="60" required><?php echo "$contactbox";?></textarea><span class="errormessage"><?php echo "$contactboxerr"; ?></span><br />
<input type="submit" value="Submit" name="submit">
</fieldset>
</form>
You can see I made the form sticky by adding echoes to errors, so I want to keep that if there are errors. However if it is successful, redirect to a success page.
Just check if you have no errors (i.e. your error variables are empty) and use header()
$fullname = $email = $reason = $contactbox = '';
$fullnameerr = $emailerr = $reasonerr = $contactboxerr = '';
if(data_post('submit')){
// your validations go here
// ......
if (empty($fullnameerr) && empty($emailerr) && empty($reasonerr) && empty($contactboxerr)) {
header('Location: success.php');
}
}
You don't have a control to check whether the validation passed or failed. As a suggestion user a boolean variable to indicate it:
if(data_post('submit')){
$valid=true;
if(empty(data_post('firstname'))){
$fullnameerr = "Please enter a valid name";
$valid=false;
}
if(empty(data_post('email'))){
$emailerr = "Please enter a valid e-mail";
$valid=false;
}
//other validations
if($valid){
//validation passed
header('Location: destination.php');
}
}
In addition to #Deimoks answer, you may need to call exit(); after calling the header() function. If you have any code after the header redirection, it could still be executed even you requested a redirection. exit() prevents that. Also, if you get the "headers already sent" error, look into output buffering.

Clear form fields after a successful submit

well im working on a small html form.
<form class="contact" action="" method="POST">
<label>Name : </label><input type="text" name="name" value="<? echo $name; ?>"/>
<p class="middle"><label>Comment : </label><textarea name="message"></textarea><? echo $message; ?></p>
<label class="captcha"><img src="captcha.php" style="line-height: 30px;"></label><input type="text" name="code"/>
<input type="submit" class="csubmit" value="Now !" name="get"/>
</form>
and this is the php code:
<?php
if (isset($_POST['get'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "no name. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "no message <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "wrong captcha <br />";
}
if (!empty($error)) {
echo '<p class="error">Error :<br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
if (empty($error)) {
$message = mysql_real_escape_string($message);
$name = mysql_real_escape_string($name);
$id = mysql_real_escape_string($_GET['id']);
$date = date("Y-m-d H:i:s");
mysql_query("INSERT INTO comments(id, name, comment, time,approved)VALUES('$id', '$name', '$message', '$date', '0')");
echo "thank you";
}
}
?>
As you can see i user $message and $name to keep informations after a submit with wrong captcha code, but the problem is that i want to clear those fields after a submit with correct informations. Can you please tell me how can i clear form fields after a succesfull submit ?
You can use .reset() on your form.
$("#form")[0].reset();
You could follow that with Javascript too
document.getElementById('form').reset();
Or, if successful, redirect the user back to your contact page:
header("Location: contact.php"); // redirect back to your contact form
exit;
EDIT
<input type="submit" class="csubmit" value="Now !" name="get" onClick="clearform();" />
function clearform()
{
document.getElementById("name").value=""; //don't forget to set the textbox ID
document.getElementById("message").value=""; //don't forget to set the textbox ID
document.getElementById("code").value=""; //don't forget to set the textbox ID
}
Also use:
required="required"
so people will be required to fill out the input fields :)
Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.

How to replace die() statement?

if(!empty($_POST))
{
if(empty($_POST['username'])) {die("Please enter a username.");}
....
Result is blank page - with the above alert.
I want to keep the form on the page. Something like:
if(empty($_POST['username']))?> <div id="info"><?php{echo "Please enter a username"};?></div>
So, just write an info, and stop the code execution from this point.
To Stop execution but you can use:
die( ' <div id="info">Please enter a username</div> ');
To allow the rest of the page to load you can use:
$errors = array();
if(empty($_POST['username'])) {
$errors[] = 'Please enter your username';
}
Then later in your html you can add
foreach($errors as $error){
echo "<div class='error'>$error</div>;
}
Rather than "stopping execution" on a single validation error, get all the errors and display them to the user:
<?php
if (!empty($_POST))
{
// validate form
$errors = array();
if (empty($_POST['username']))
{
$errors['username'] = 'Please enter a username.';
}
if (empty($_POST['address']))
{
$errors['address'] = 'Please enter an address.';
}
if (empty($errors))
{
// save to database then redirect
}
}
?>
<form>
Username:<br />
<input type="text" name="username" value="" /><br />
<?php if (!empty($errors['username'])): ?>
<div class="error">
<?php echo $errors['username'] ?>
</div>
<?php endif ?>
Address:<br />
<input type="text" name="address" value="" /><br />
<?php if (!empty($errors['address'])): ?>
<div class="error">
<?php echo $errors['address'] ?>
</div>
<?php endif ?>
</form>
Set some flag and returns/redirects to the same page. On the same page (script with form), check for the flag set and display the message.

redirect to php page if fields are empty

I want to redirect to the page which has a form when user submit the form without any parameters, also I want to return an error message, how can I redirect from controller to the form?
<form action="controllers/Customer.controller.php" method="post">
<label for="cellPhoneNo">cell phone number</label>
<input type="text" name="cellPhoneNo" class="textField"/>
<label for="telephone">telephone number</label>
<input type="text" name="telephone" class="textField"/>
<input type="submit" name="searchCustomer" value="بحث"/>
</form>
and here's the Customer.controller.php page
if(trim($_POST['cellPhoneNo']) == "" && trim($_POST['telephone']) ==""){
//include('Location:index.php'); //what I supposed to write here?
echo "empty";
}
<?php
session_start();
if(isset($_POST)){
$cont=true;
//cellPhoneNo
if(!isset($_POST['cellPhoneNo']) || strlen($_POST['cellPhoneNo'])< 13){ //13 being the telephone count
$cont=false;
$_SESSION['error']['cellPhoneNo']='Cell phone is required & must be 13 in length';
header('Location: ./index.php');
die();
}
//telephone
if(!isset($_POST['telephone']) || strlen($_POST['telephone'])< 13){ //13 being the telephone count
$cont=false;
$_SESSION['error']['telephone']='Telephone is required & must be 13 in length';
header('Location: ./index.php');
die();
}
if($cont===true){
//continue to submit user form
}else{
header('Location: ./index.php');
die();
}
}else{
header('Location: ./index.php');
}
?>
Not knowing the structure of your framework, you can use php's header
if(trim($_POST['cellPhoneNo']) == "" && trim($_POST['telephone']) ==""){
$_SESSION['error'] = 'Fields cannot be empty!';
header('Location: myformlocation.php');
exit();
}
And just above your form:
<?php if(isset($_SESSION['error'] )) : ?>
<div class="error"><?php echo $_SESSION['error'];?></div>
<?php
unset($_SESSION['error']);
endif; ?>
<form action="controllers/Customer.controller.php" method="post">
So, whenever the form submits, if fields are empty, the form page is reloaded and, since $_SESSION error is now set, it will be displayed. You might want to make a function out of $_SESSION['error'] displaying, so you won't writing all that code in each form.
EDIT after comment:
Uhm, I'm not really sure to understand your question, you can use either $_GET:
header("Location: ../index.php?page=customerSearch");
and you retrieve it in index with
$pageToInclude = $_GET['page']; //properly sanitized
or use
$_SESSION['pageToInclude'] = 'CustomerSearch';
$_SESSION['error'] = 'Fields cannot be empty!';
header('Location: myformlocation.php');
....
and in index you use
$pageToInclude = isset($_SESSION['pageToInclude']) ? $_SESSION['pageToInclude'] : 'someotherdefaultpage';

Categories