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);
}
?>
Related
If anyone would be able to point me in the right direction it would make my day!
I'm trying to create a forum by following this tutorial: "https://code.tutsplus.com/tutorials/how-to-create-a-phpmysql-powered-forum-from-scratch--net-10188".
I've created the pages with some modifications but the problem I'm getting is at the sign-in, first of all when I add the connect.php page to the sign-in page, the code doesn't echo the form, it's blank. Also when I don't use the connect page, the error messages get printed out at the start when I would like them to come after hitting submit.
I have managed to get a connection to my database and get out data with other code, but I can't seem to get this working.
<?php
session_start();
//signin.php
include 'forumHeader.php';
include 'connect.php';
echo '<h3>Sign in</h3>';
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can sign out if you want.</br></br>';
echo 'Welcome, ' . $_SESSION['user_name'] . '. Proceed to the forum overview.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo '<form method="post" action="">
Username: <input type="text" name="user_name" />
Password: <input type="password" name="user_pass"/>
<input type="submit" value="Sign in" />
</form>';
}
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Varify if the data is correct and return the correct response
*/
$errors = array(); /* declare the array for later use */
if(!isset($_POST['user_name'])) //NOT + FALSE + POST FROM INPUT //ISSET RETURNS FALSE WHEN CHECKING THAT HAS BEEN ASSIGNED TO NULL
{
$errors[] = 'The username field must not be empty.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'The password field must not be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/ //Detta betyder, om ERRORS INTE är TOM
{
echo 'Uh-oh.. a couple of fields are not filled in correctly..';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul>';
}
else
{
//the form has been posted without errors, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "SELECT
user_id,
user_name,
user_level
FROM
forum_Users
WHERE
user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
AND
user_pass = '" . sha1($_POST['user_pass']) . "'";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysql_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysql_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
echo 'Welcome, ' . $_SESSION['user_name'] . '. Proceed to the forum overview.';
}
}
}
}
include 'forumFooter.php';
?>
This is pretty much the code I use for the sign-in page. The code I have at the connect.php page is:
<?php
//connect.php
$server = 'server';
$username = 'user';
$password = 'pass';
$database = 'database';
if(!mysql_connect($server, $username, $password))
{
exit('Error: could not establish database connection');
}
if(!mysql_select_db($database)
{
exit('Error: could not select the database');
}
?>
Where you are echoing out the form you should be elseing into the form being processed if there is $_POST, atm you are going to it whether there is $_POST or not and trying to process empty $_POSTs will throw errors.
Side note: set your error reporting to all using this method error_reporting(E_ALL), that will let you know whats going wrong in future, it is normally set where you set session_start()
A user enters two dates periods on a text-box and a SQL select statement picks mobile numbers from a database entered in between the period. I want to pick and display them on a page. On the same display page, I have a text area where a user can type a message and on submit, it should be sent to these selected numbers and displayed mobile numbers. I am having a challenge on passing the $mobilenumber to the function sendbulk that is to send the message to the mobile numbers displayed by $mobilenumber variable. Everything else is okay apart from passing the $mobilenumber. I think this is because after the page loads to display the contacts selected, on the second load as you submit the $message to bulk function the value of $mobilenumber is already lost. How can I save it.
Check sample code below and please advice. How do I save the $mobilenumber so that by the second load it is still there to be passed to the function sendbulk()? Anyone?
<?php
//Define variable and set to empty values
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$message = test_input($_POST['message']);
echo "$message";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$time1 = isset($_POST['t1']) ? $_POST['t1'] : 'default something missing';
$time2 = isset($_POST['t2']) ? $_POST['t2'] : 'default something missing';
//connection
$sql = "SELECT DISTINCT msisdn FROM customer WHERE DATE_FORMAT(time_paid, '%Y-%c-%e') BETWEEN ADDDATE('$time1',INTERVAL 0 HOUR) AND ADDDATE('$time2',INTERVAL '23:59' HOUR_MINUTE)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo " Recipients: "; echo "$result->num_rows <br> <br>";
// output data of each row
while($row = $result->fetch_assoc()) {
$mobilenumber = $row['msisdn'];
echo "Mobile : " . "$mobilenumber" . "<br>";
}
} else {
echo "No Contacts to Display";
}
$conn->close();
sendbulk($mobilenumber,$message);
?>
<center></center> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<textarea name='message' rows="6" cols="60" placeholder="Please Type Your Message Here"></textarea>
<br><br>
<input type="submit" name="submit" value="Send Message">
</form></center>
<?php
function sendbulk($mobilenumber,$message) {
echo "$mobilenumber";
echo "$message";
$serviceArguments = array(
"mobilenumber" => $mobilenumber,
"message" => $message_sent
);
$client = new SoapClient("http://*******");
$result = $client->process($serviceArguments);
return $result;
}
You use sessions.
Here is a sample code:
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count'] += 1;
}
echo $_SESSION['count'];
?>
Keep reloading this file via your web server. You should see the variable incrementing.
As an alternative, you can also use $_COOKIE. The only difference is that $_SESSION is saved on the server side and not accessible on the client. To identify the client it does store a cookie for that session on the client.
$_COOKIE on the other hand is completely stored on the client and passed by the browsers to the server on every request.
Also note a caveat, don't overload your session variables or cookies as it will hit your response times.
Also note that session_start() is required in every PHP file where you want to access the session.
So i have a login script and not too sure why it won't work. In my User table I have these fields:
Table: User
Field 1) ID
Field 2) Password (it is stored with crypt)
Field 3) Status (ranges from 0-2)
index.php
<?php
session_start();
unset($_SESSION['Status']);
?>
<head>
<title>Login Form</title>
<link rel="stylesheet" type="text/css" href="login.css">
<img src="logo1.jpg" style="float:left; width:490px; height:130px; margin-top: -70px;">
<!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
</head>
<body>
<section class="container">
<div class="login">
<h1>Login</h1>
<form action="process_login.php" method="POST"/>
<div class="help-tip">
<p>Enter the User ID and Password that you were given, in order to login. If you have forgotten your ID or Password, contact Admin</p>
</div>
<p><input type="number" name="ID" value="" placeholder="ID*" required autofocus></p>
<p><input type="password" name="Password" value="" placeholder="Password*" required></p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
</div>
process_login.php
<?php
session_start();
?>
<?php
//Connect to host site and databse
include("functions.php");
// Fetching variables
$id = $_POST['ID'];
$pw = crypt($_POST['Password']);
//Find user details from User table using the username entered and comparing the entered password with the one retrieved form the user table
$UserValidate = mysqli_query ("SELECT * FROM User WHERE ID = '$id'") or die (mysqli_error());
$row = mysqli_fetch_array($UserValidate);
$CorrectId = $row['ID'];
$CorrectPw = $row['Password'];
$UserType = $row['Status'];
//check if ID in database
if ($id == $CorrectId) {
//check if password is assigned to that username and is correct
if ($pw == $CorrectPw) {
//check if user is standard user
if ($UserType == 0) {
$_SESSION['CadetUser'] = $id;
header('http://****/calendar.php:'.$url);die();
if ($UserType == 1) {
$_SESSION['StaffUser'] = $id;
header('http://****/calendar_staff.php:'.$url);die();
if ($UserType == 2) {
$_SESSION['AdminUser'] = $id;
header('http://****/calendar_admin.php:'.$url);die();
}
}
else {
echo "Either your ID or Password is wrong";
header('http://******/index.php:'.$url);die();
}
}
}
}
?>
UPDATE
My problem is that i am getting a blank screen when I log in with the correct details. It just stops at process_login.php
Also i changed the redirect to "header.........." like suggested
For redirect you could try
header('location:'.$url);die();
Note : remove all echo or print before header and make sure you don't have white spaces before your php opening tags
As an aside, your SQL statement is vulnerable to SQL injection because you put the $id straight into the statement. It would be far safer to use parameters and mysqli
This is your code - indented, as entered in your post:
//check if ID in database
if ($id == $CorrectId) {
//check if password is assigned to that username and is correct
if ($pw == $CorrectPw) {
//check if user is standard user
if ($UserType == 0) {
$_SESSION['CadetUser'] = $id;
header('http://****/calendar.php:'.$url);
die();
if ($UserType == 1) {
$_SESSION['StaffUser'] = $id;
header('http://****/calendar_staff.php:'.$url);
die();
// <----- missing a closing brace
if ($UserType == 2) {
$_SESSION['AdminUser'] = $id;
header('http://****/calendar_admin.php:'.$url);
die();
}
}
else {
echo "Either your ID or Password is wrong"; // you need to remove this; outputting HTML prior to sending headers will result in a PHP error
header('http://******/index.php:'.$url);
die();
}
}
}
} // <----- remove this
As you can see the only condition that stands a chance is if ($UserType == 0). Not to mention there's an erroneous } in there which could cause a syntax error.
You're also missing Location in your header, eg. header('Location: url/goes/here.php');
I've reformatted your code below, and fixed the syntax errors:
//check if ID in database
if ($id == $CorrectId && $pw == $CorrectPw) {
//check if user is standard user
if ($UserType == 0) {
$_SESSION['CadetUser'] = $id;
header('Location: http://****/calendar.php:'.$url);
die();
}
elseif ($UserType == 1) {
$_SESSION['StaffUser'] = $id;
header('Location: http://****/calendar_staff.php:'.$url);
die();
}
elseif ($UserType == 2) {
$_SESSION['AdminUser'] = $id;
header('Location: http://****/calendar_admin.php:'.$url);
die();
}
else {
header('Location: http://******/index.php:'.$url);
die();
}
}
And since if ($id == $CorrectId) and if ($pw == $CorrectPw) are required conditions that must be met in order to proceed, it makes sense to just include them in a single condition.. for readability. You should avoid nesting conditions too deep whenever possible. Makes things messy, and code hard to read/follow. You can see I've added them into a single condition.
Change header function
header('http://****/calendar.php:'.$url);
To
header('location : http://****/calendar.php:');
Add location in header as shown above
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.
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