Keeping field values if error occurs - php

I have seen some solutions for my problem, but I just don't know how to apply them. I am going post part of my validation file because it is large.
if ($action == "submit" && ($member_submit == 0 || ($member_submit==1
&& $_SESSION['loggedin']==1))){
$frompage = $_SERVER['HTTP_REFERER'];
if($_POST['thumburl']=="http://")
$_POST['thumburl']="";
// Check to see if the user is trying to bypass your requirements, and if so, redirect them!
if ($_SESSION['nosubmit']==1){
$_SESSION['submitstatus'] = "<div class=error><b>Error:</b> There was something wrong with your
submission. Please try again later</div>";
header('Location: '.$frompage.'');
exit;
}
// End Cheat Check
// Check to see if IP address is allowed to submit. If not, redirect!
if (ban_check("submit") == "banned"){
$_SESSION['submitstatus'] = "<div class=error><b>Error:</b> Cannot Add Submission At This Time</div>";
header('Location: '.$frompage.'');
exit;
}
// End Ban Check
$submissiontime = time();
if (($submissiontime - $delay) <= $_SESSION['submission']){
$_SESSION['submitstatus'] = "<div class=error><b>Error:</b> Flood Control Initiated</div>";
header('Location: '.$frompage.'');
exit;
}
$ipaddress = $_SERVER['REMOTE_ADDR'];
$contenttitle = clean_string($_POST['contenttitle']);
$contentdescription = clean_string($_POST['contentdescription']);
$contenturl = clean_string($_POST['contenturl']);
$contenturl2 = strtolower($contenturl);
$category = clean_string($_POST['category']);
// Make sure they selected a category
if ($category == 0){
$_SESSION['submitstatus'] = "<div class=error><b>Error:</b> Please select a category</div>";
header('Location: '.$frompage.'');
exit;
}
// Check to see if have backlink and nofollow atribute
$parse = parse_url($contenturl);
$base_url = $parse["host"]; // domain.com
$linkback1 = reciprocal_linkback($contenturl, "http://www.dumpvid.com", 1);
if ("$linkback1"=="0") {
$_SESSION['submitstatus'] = "<div class=error><b>Error:</b> Backlink was not found, or nofollow detected.</div> ";
header('Location: '.$frompage.'');
exit;
}
// Check to see if have backlink in the main also
$parse = parse_url($contenturl);
$base_url = $parse["host"]; // domain.com
$linkback2 = reciprocal_linkback($base_url, "http://www.dumpvid.com", 1);
if ("$linkback2"=="0") {
$_SESSION['submitstatus'] = "<div class=error><b>Error:</b> Backlink found only on content url.</div> ";
header('Location: '.$frompage.'');
exit;
}
// Check if TITLE and URL are filled in
if (empty($contenttitle) || $contenttitle == "Title?"){
$_SESSION['submitstatus'] = "<div class=error><b>Error:</b> Please Fill In Title</div>";
header('Location: '.$frompage.'');
exit;
}
elseif (empty($contenturl) || $contenttitle == "http://"){
$_SESSION['submitstatus'] = "<div class=error><b>Error:</b>Invalid URL</div>";
header('Location: '.$frompage.'');
exit;
}
elseif (empty($contentdescription) || $contentdescription == "Nice description gets more traffic..."){
$_SESSION['submitstatus'] = "<div class=error><b>Error:</b> Invalid or Missing Descriptio</div>";
header('Location: '.$frompage.'');
exit;
}
// Check if VALID URL
if (is_url("$contenturl")) {
} else {
$_SESSION['submitstatus'] = "<div class=error><b>Error:</b> Doesn't seem to be a valid URL</div>";
header('Location: '.$frompage.'');
exit;
}
The structure of the validation file is basically this, if you need me to post the whole validation file and the form please let me know.
I just want to keep the field values the user filled before in case the validation fails.

You should display form again on error but without using header('Location:...') because you will lost params sent using form after redirect. You may use function for retriving params in html:
function getParam($name, $defaultVal = null){
return isset($_REQUEST[$name]) ? $_REQUEST[$name] : $defaultVal;
}
<input type="text" value="<?php echo getParam('firstname', ''); ?>" name="firstname">
EDIT
If you have 2 files:
form.php - your form definition
save_form.php - form validation,
Then in save_form.php you could use something like this:
//...
if($error){
include 'form.php';
die();
}
and in form.php
<input type="text" value="<?php echo getParam('firstname', ''); ?>" name="firstname">

As i understand i think you have to do this in html like:
<input type="text" value="<?php echo (isset($_REQUEST['firstname'])) ? $_REQUEST['firstname'] : ''; ?>" name="firstname">
this will return you that you want.. Apply something like this to all fields..
EDIT: the above will work when you will click on the submit button then you will get the 'firstname' value else it will show blank.. And Please Never forget to validate on the above of the <form> tag means at the top of the page..

<?php
session_start();
//save post values into session
if(strtolower($_SERVER['REQUEST_METHOD']) == 'post'){
$_SESSION['_postHistory'] = $_POST;
}
//this will restore your previously posted values into $_POST global
if(isset($_SESSION['_postHistory']) && is_array($_SESSION['_postHistory'])){
foreach($_SESSION['_postHistory'] as $key => $val){
if(!isset($_POST[$key])) $_POST[$key] = $val;
}
}
function getPostValue($key, $default = null){
return (isset($_POST[$key])) ? $_POST[$key] : $default;
}
?>
<input type="text" value="<?php echo getPostValue('fieldname')?>" name="fieldname"/>
I don't recommend using $_REQUEST for post as you might have the same param defined in $_GET as well which can conflict each other.

Related

how to store value till it not submit

I have 3 pages:
Register.php
Success.php
Login.php
Now when my user register the it's values validate on success.php and if not correct it returned on register page and if it get correct then it gone to login page. I want when it comes back to register page when values not correct then values which was filled before submit should remain as it.
You can do this by just returning the values the user sent in. Using $_GET
http://php.net/manual/en/reserved.variables.get.php
https://www.w3schools.com/php/php_forms.asp
Just take the paramaters the users sent in and pass them back in the url.
Like if failed, return to url:
register.php?uname=value1&email=value2
Then in register.php get the paramaters with
$username = $_GET['uname'];
Then echo it out in the form again as value:
<input id="uname" value="<?php if(isset($_GET['uname']){
echo $username;
}
else{echo "enter username";} ?>" />
Very simple example here, but just follow w3school and you should have everything you need to get this done.
As you are using PHP, so best option is to use SESSIONS.
You can create something like:
$name = $_SESSION['name'];
$email = $_SESSION['email'];
Than these values can be used in the 3 pages for processing.
Your first page is register.php, so in the beginning of page just add a php function session_destroy(); so that when user open page any live session will be destroyed and new session will be started with that specific user. Also don't forget to start sessions by using function session_start(); on every page. I hope this will solve your requirement.
Take a look at JavaScript's localStorage. (or sessionStorage)
With that you will be able to store information between pages. Then just pass all the information at the same time as POST data on the last page.
Example:
var existing = localStorage.getItem('user_name');
if (existing == null) {
// The user has not set their name, lets assume it's John Doe
existing = 'John Doe';
localStorage.setItem('user_name', existing);
}
alert('Hello ' + existing + '!');
Alternatively, on the pure PHP side of things, you could also use PHP sessions. This way all the information stays on the server instead of in the user's browser.
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
The easiest method, IMO, using PHP would be to use a session variable which holds the values of all POSTed data from register.php
A simple function can be called to retrieve the value from the session variable and consequently displayed in the HTML form fields. This is an example of how you could achieve the desired result.
<?php
/* success.php */
session_start();
function getvalue( $var='register', $field=false ){
if( isset( $_SESSION[ $var ] ) ){
return array_key_exists( $field, $_SESSION[ $var ] ) ? $_SESSION[ $var ][ $field ] : '';
}
return '';
}
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/*
a boolean to indicate if everything is OK with the submitted
data - to be updated later according to your rules
*/
$ok=false;
/* set the session variable */
$_SESSION['register']=$_POST;
/* process POST data - set value of $ok to true if everything is OK! */
/*
this is where you determine the rules for success or failure
*/
/* Determine where the use goes next */
if( $ok ){
exit( header('Location: login.php') );
} else {
exit( header('Location: register.php') );
}
}
?>
<?php
/* register.php */
session_start();
?>
<html>
<head>
<title>register.php</title>
</head>
<body>
<!--
the form fields should initially be blank, but if the user is redirected
back to the page the fields should show the values stored in the
session variable.
-->
<form name='register' method='post' action='success.php'>
<!-- various form fields - example -->
<input type='text' name='email' value='<?php echo getvalue('register','email'); ?>' />
<input type='text' name='username' value='<?php echo getvalue('register','username'); ?>' />
<!-- more fields -->
<input type='submit' />
</form>
</body>
</html>
<?php
session_start();
$_SESSION['namefeild_name'] = $_POST['namefeild_name'];
$_SESSION['mob'] = $_POST['mob'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['city'] = $_POST['city'];
if(isset($_POST['reg']))
{
$con=mysql_connect("localhost","root","");
if(!$con) { die('Could Not Connect: '.mysql_error()); }
mysql_select_db("database", $con);
if(!isset($_POST['namefeild_name']) ||
!isset($_POST['mob']) ||
!isset($_POST['pass']) ||
!isset($_POST['pas']) ||
!isset($_POST['email']) ||
!isset($_POST['city']))
{
die("<script type='text/javascript'>alert('We are sorry, but there appears to be a problem with the form you submitted.')</script>");
}
$uid = $_POST['namefeild_name']; // required
$name = $_POST['namefeild_name']; // required
$uname=$_POST['mob']; //required
$pass=$_POST['pass']; //required
$pas=$_POST['pas']; //required
$email = $_POST['email']; // required
$city = $_POST['city']; // not required
$type = 'BAL'; // not required
$id=md5($uname);
$error_message = "";
$string_exp = "/\b([A-Za-z]{1,30}[- ]{0,1}|[A-Za-z]{1,30}[- \']{1}
[A-Za-z]{1,30}[- ]{0,1}|[A-Za-z]{1,2}[ -\']{1}[A-Za-z]{1,30}){2,5}/";
if(!preg_match($string_exp,$name)) {
$error_message .= "<script type='text/javascript'>alert('Name does not appear to be valid.')</script>";
header('location:register.php?errorname');
}
$string_exp = "/^[7-9][0-9]{9}$/";
if(!preg_match($string_exp,$uname)) {
$error_message .= "<script type='text/javascript'>alert('Mobile Number does not appear to be valid.')</script>";
header('location:register.php?errormob');
}
$string_exp = "/\b([A-Za-z]{1,30}[- ]{0,1}){1}/";
if(!preg_match($string_exp,$pas)) {
$error_message .= "<script type='text/javascript'>alert('The password you entered does not appear to be valid.<br />Contain Atleast one Uppercase Letter<br />Contain atleast one lower case letter<br />contain atleast one number')</script>";
header('location:register.php?errorpass');
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$city)) {
$error_message .= "<script type='text/javascript'>alert('City does not appear to be valid.')</script>";
header('location:register.php?errorcity');
}
if(strlen($city) < 2) {
$error_message .= "<script type='text/javascript'>alert('City does not appear to be valid.')</script>";
header('location:register.php?errorcity');
}
if(strlen($error_message) > 0) {
die($error_message);
}
else
{
$query=mysql_query("select * from customer where uname='".$uname."'") or die(mysql_error());
$res=mysql_fetch_row($query);
if($res)
{
header("location: register.php?useralreadyexits");
session_destroy();
}
elseif(!$res)
{
$datetime=Date("Y/m/d H:i:s");
$result=mysql_query("INSERT INTO customer VALUES('$id','$uname','$name','$pas','$email','$city','$datetime');");
$result2=mysql_query("INSERT INTO payment VALUES('$id','$uname','25','$datetime','$type');");
if($result && $result2)
{
header("location: login.php?success");
session_destroy();
}
else
{
$_SESSION['name']=$uname;
header('location:register.php?notregistered');
}
}
}
mysql_close($con);
}
?>

Register form Error Correction in PHP - Best solution?

I'm looking for as simple approach to correcting errors such as non-matching passwords and people inserting blank data into a form in HTML.
I want to use PHP to throw me back an error when this happens, I was considering using if statements but realised it would not show more than one error if it happens.
Here is an example of what I was doing, keeping in mind $firstname's input is from POST:
if ($firstname == "")
{
$_SESSION['nofirstname'] = 1;
header('Location: register.php');
}
In register.php it picks up this, and warns the user that he has entered no first name. This is cool but won't display additional errors if there are any. I'm guessing switches and arrays are the way forward but I don't really understand how to add a entry to an array.
Anyone able to help?
session_start();
....
$_SESSION['flag']=false;
if ($firstname == "")
{
$_SESSION['nofirstname'] = 1;$_SESSION['flag']=true;
}
if ($lastnamee == "")
{
$_SESSION['nolastname'] = 1;$_SESSION['flag']=true;
}
...
header('Location: register.php');
in register.php
session_start();
...
if ($_SESSION['flag']==true){
if ($_SESSION['nofirstname']==1) {///message}
if ($_SESSION['nolastname']==1) {///message}
...
}
Use a nested if, e.g;
<?php
if($firstcond){
if($secondcond){
}else{
$_SESSION['error'] = 'Second Condition not met!';
header('Location: register.php');
//error
}
}else{
$_SESSION['error'] = 'First Condition not met!';
header('Location: register.php');
//error
}
?>
This means that in order for $secondcond to be validated, $firstcond must pass whatever checks you perform on it first :)
session_start();
ob_start()
if ($firstname == "")
{
$_SESSION['nofirstname'] = "Enter your name";
header('Location: register.php');
}
Redirect the page and display
echo isset($_SESSION['nofirstname'])?$_SESSION['nofirstname']:'';
Try this.
Try this:
session_start();
$errors = array();
if ($firstname == "")
{
$errors['nofirstname'] = 1;
}
if ($lastname == "")
{
$errors['nolastname'] = 1;
}
$run = 1;
foreach ($errors AS $key => $value)
{
$_SESSION[$key] = $value;
$run = 0;
}
if (!$run)
header('Location: register.php');

want to place part of php code somewhere else on page

I'm very new to php. I found some CMS like code for east text editing here on SO and now I'm trying to implement it on our micro site.
My problem is, that I want login error report to show on exact position on the page - just under the login button.
Can someone tell me how can I put that error report text whereever I want? I don't want to override it with CSS positioning.
In basic, I want to put that p class="error":
<?php
if (empty($_POST) && isset($_GET['action'])) {
$action = $_GET['action'];
switch ($action) {
case 'logout':
session_unset();
session_destroy();
break;
}
}
if (!isset($_SESSION['user'])) {
$user = '';
$pass = '';
if (isset($_POST['login'])) {
$user = strtolower(trim($_POST['user']));
$pass = $_POST['pass'];
$errors = array();
if ($user == '' || $user != '1') {
$errors['user'] = '';
}
if ($pass == '' || $pass != '1') {
$errors['pass'] = '';
}
if (empty($errors)) {
$_SESSION['user'] = $user;
} else {
echo '<p class="error">Insert correct ';
if (isset($errors['user']))
echo 'name';
if (count($errors) == 2)
echo ' a ';
if (isset($errors['pass']))
echo 'password';
echo '.</p>', "\n";
}
}
}
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
?>
somewhere else in the whole code of my page. Do I need to cut out something from that php code, or do I need to write new part of code for that?
Thank you for you help, Matej
Instead of just doing 'echo' all over the place, which means you get output at the place where the PHP code is embedded in the page, set some flags/message variables to output later.
e.g.
<?php
$errors = false;
$msgs = '';
if (....) {
$errors = true;
$msgs = "something dun gone wrong";
}
?>
... various bits of your html go here ...
<?php if ($errors) { echo $msgs; } ?>
... more html here ...

Multiple Submit Buttons On Form Difficulties

I wonder whether someone may be able to help me please.
I've put together this form which, if you scroll to the bottom of the page, has multiple submission buttons. i.e 'Submit', 'Deleted selected image' and 'View Selected Image'.
I posted a query on this site yesterday here, about about how to go about dealing with multiple 'submission' buttons and received some great advice.
I've tried to implement the advice I was given, but I just can't seem to get this to work. As the guidance suggested, I've added a name to each button and tried to call that through the PHP script, but all that happens is the page refreshes as if submitting the whole page, rather, than for example, being able to view the selected file.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Please find my PHP code & Form script below
<?php
$db_host = 'host';
$db_user = 'username';
$db_pwd = 'password';
$database = 'databasename';
$table = 'images';
// use the same name as SQL table
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
return mysql_real_escape_string($s);
}
// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!isset($_POST["action"]))
{
// cleaning title field
$title = trim(sql_safe($_POST['title']));
if ($title == '') // if title is not set
$title = '(No Title Provided)';// use (empty title) string
//print_r($_FILES);exit;
if($_FILES["photo"]["error"] >= 4) {
$msg = '<b>Error!</b> - You <b> must </b> select a file before clicking the <b> "Upload This Image" </b> button. Please try again.';
}
else
if (isset($_FILES['photo']))
{
list($width, $height, $imtype, $attr) = getimagesize($_FILES['photo']['tmp_name']);
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = '<b> Error! </b> - The image that you attempted to upload is not in the correct format. The file format <b> must </b> be one of the following: <b> "gif", "jpeg" </b> or <b> "png" </b>. Please try again.';
if($_FILES["photo"]["size"]/1150000 >= 1) {
$msg = '<b> Error! </b> - The file that you are attempting to upload is greater than the prescribed <b> 1MB </b> limit. Please try again.';
}
if (!isset($msg)) // If there was no error
{
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO {$table}
SET ext='$ext', title='$title',
data='$data'");
$msg = '<b> Success! </b> - Your image has been uploaded';
}
}
elseif (isset($_GET['title'])) // isset(..title) needed
$msg = 'Error: file not loaded';// to make sure we've using
// upload form, not form
// for deletion
if (isset($_POST['deleteimage'])) // If used selected some photo to delete
{ // in 'uploaded images form';
$imageid = intval($_POST['del']);
mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
$msg = 'The image which you selected has now been deleted!';
}
if (isset($_POST['viewimage'])) // If used selected some photo to delete
{ // in 'uploaded images form';
$imageid = intval($_POST['view']);
mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid");
if(mysql_num_rows($result) == 1)
{
$image = $row['myimage'];
header("Content-type: image/gif"); // or whatever
print $image;
exit;
}
}
}
else
{
$imageid = intval($_POST['del']);
if ($_POST["action"] == "view")
{
$result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
FROM {$table}
WHERE imageid=$imageid LIMIT 1");
if (mysql_num_rows($result) == 0)
die('no image');
list($ext, $imagetime, $data) = mysql_fetch_row($result);
$send_304 = false;
if (php_sapi_name() == 'apache') {
// if our web server is apache
// we get check HTTP
// If-Modified-Since header
// and do not send image
// if there is a cached version
$ar = apache_request_headers();
if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
($ar['If-Modified-Since'] != '') && // not empty
(strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
$send_304 = true; // imagetime
}
if ($send_304)
{
// Sending 304 response to browser
// "Browser, your cached version of image is OK
// we're not sending anything new to you"
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);
exit(); // bye-bye
}
// outputing HTTP headers
header('Content-Length: '.strlen($data));
header("Content-type: image/{$ext}");
// outputing image
echo $data;
exit();
}
else if ($_POST["action"] == "delete")
{
$imageid = intval($_POST['del']);
mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
$msg = 'The image which you selected has now been deleted!';
}
}
}
?>
<form action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data">
<div align="left">
<!-- This form is used for image deletion -->
<?php
$result = mysql_query("SELECT imageid, imagetime, title FROM {$table} ORDER BY imageid DESC");
if (mysql_num_rows($result) == 0) // table is empty
echo '<ul><li>You have no images loaded</li></ul>';
else
{
echo '<ul>';
while(list($imageid, $imagetime, $title) = mysql_fetch_row($result))
{
// outputing list
echo "<li><input type='radio' name='del' title, value='{$imageid}' />";
echo " <small>{$title}</small> &nbsp";
echo "<small>{$imagetime}</small></li>";
}
echo '</ul>';
echo '<input type="submit" value="Delete Selected Image" onclick="document.getElementById(\'action\').value=\'delete\'" />';
echo '<input type="submit" value="View Selected Image" onclick="document.getElementById(\'action\').value=\'view\'" />';
}
?>
<input type="hidden" name="action" id="action" />
</div>
</form>
Many thanks and kind regards
Where you're checking the $_POST action, you need to do this:
if ($_POST["viewimage"] == "View Selected Image") { // Do stuff }
if ($_POST["deleteimage"] == "Delete Selected Image") { // Do stuff }
Basically, you need to check $_POST['name'] == 'value'

Using 'IF.. ELSE' to change variable and use it in 'form action...'

I've created a test form that uses IF.. ELSE to validate data in a simple form. This works ok and any validation messages or errors are posted to the same page (userform.php) to inform the user of success or otherwise.
What I want to do now is take the user to a different page on successful completion of the form. Here's my code so far:
<?php
if (isset($_POST['email'], $_POST['password'])) {
$errors = array ();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST ['email'];
$password = $_POST ['password'];
if (empty ($firstname) || empty ($lastname) || empty ($email) || empty ($password)) {
$errors [] = "Please complete the form";
}
if (empty($email)) {
$errors [] = "You must enter an email address";
}
if (empty($password)) {
$errors [] = "You must enter a password";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
$errors[] = "Please enter a valid email address";
}
}
if (!empty ($errors)) {
foreach ($errors as $error) {
echo '<strong>', $error ,'</strong><br />';
$result = "userform.php";
}
} else {
$result = "confirm.php";
}
?>
<form action="<?php echo $result ?>" method="post">
The idea is that the users success or otherwise in completing the form changes the $result variable which is used in the form action. The above code doesn't work, so how would I do it?
Is it even possible?
instead of "form action=" at the bottom:
<?php
include($result);
?>
As I understand it you want it to work like so:
User fills form
User submits form
Form submission goes to userform.php
If all values validate, continue to confirm.php
If not, return to userform.php
If that's the case, I don't think you want to change the form action: that would require that the user re-submit the form. Instead, use a HTTP redirect to send them to confirm.php:
header("Location: confirm.php");
... or if you wanna be really by-the-book about it:
header("Status: 303 See Other");
header("Location: http://exampel.com/confirm.php"); // according to the protocol,
// `Location` headers should be full URLs
<?php
/* ... */
if (!empty ($errors)) {
foreach ($errors as $error) {
echo '<strong>', $error ,'</strong><br />';
}
?>
<form action="userform.php" method="post">
<?php
} else {
header("Location: confirm.php");
// if you need to pass additional information to confirm.php, use a query string:
// header("Location: confirm.php?var1=".$var1);
}
?>
The way you're doing it now, will redirect the user to confirm.php if they submit the form for a second time. You could change your code to this:
} else {
// $result = "confirm.php";
header("Location: confirm.php");
exit();
}
That way, if everything has been entered, the user will be redirected to confirm.php. But what do you do with the variables if everything is allright? They won't be taken to the new page.
} else {
$result = confirm.php;
foreach($_POST as $key => $val){
$input.="<input type='hidden' name='$key' value='$val' />";
}
$form = "<form method='post' name='confirm' action='confirm.php'>".$input."</form>";
$script = "<script type='text/javascript'>document.confirm.submit();</script>";
echo $form.$script;
}
empty ($errors)
will ALWAYS return empty. That's why you always get:
$result = 'confirm.php';
Check return values here
Also, I don't think you can do this easily. Instead, why don't you just create a check.php or whatever to check the variables/check for errors, etc. Then do whatever you want (redirect back to the form-filling page or proceeding to confirm.php page.
The whole idea is wrong. You have to fix 2 issues in your code.
1. A major one. Learn to properly indent nested code blocks!
It's impossible to read such an ugly mass with no indents.
2. A minor one.
I see no use of confirmation page here. What are you gonna do on that page? And from where you're going to get form values?
It seems you have to either use just simple Javascript code to show a confirmation or store entered data into session
And, I have to say, that show a confirmation page for simply a feedback form is quite uncommon practice.
So, I think you really need only one form action and only thing to ccare is properly filled form
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST ['email'];
$password = $_POST ['password'];
$errors = array();
if (empty ($firstname) || empty ($lastname) || empty ($email) || empty ($password)) {
$errors [] = "Please complete the form. All fields required.";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
$errors[] = "Please enter a valid email address";
}
if (!$errors) {
// do whatever you wish to this data
// and then redirect to whatever address again
// the current one is a default
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['fiestname'] = $form['lasttname'] = $form['email'] = $form['password'] = '';
}
include 'form.tpl.php';
?>
while in the form.tpl.php file you have your form fields, entered values and conditional output of error messages
<? if ($errors): ?>
<? foreach($errors as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form method="POST">
<input type="text" name="firstname" value=<?=$form['firstname']>
... and so on

Categories