In PHP I want to use a script held in a separate file to process a form and validate it. If there are errors I want the form to display the errors and original values for the user to change.
At the moment the validation script is on the same page as the form and all works ok. However I would like this away from the form and send the form variables to the script using the 'action' in the form.
If I do this though, how can I then go back to the form with error messages and original values — do I simply use $_POST in the script and a header location? or is there a better method.
If the form validates okay I'll then go to a separate page (using a header).
Can anyone help me understand the process/logic I should be trying to achieve and the function s to past variables between the pages ($_GET?)
If you want to track variables across multiple pages, it might be feasible to investigate sessions. You can assign variables from $_GET or $_POST to the session, and they will be accessible across pages.
I think what you are looking for is a framework called Model-View-Controller (MVC). In your case, your form is the "view" and script to process data is "controller" then the controller has the option what to show to the user (view) which is your form with error message or some other page with success message. But MVC is a bit more complex than that. If you want to study MVC, read some articles and choose MVC framework to use like CakePHP, CodeIgniter, Zend framework et cetera.
If you are studying basics of PHP, you might not want to start using a framework, in that case, you can do something like this (login sample):
login.php
<?php
$error = "";
$username = "";
$password = "";
//POST method used. The user is trying to login
if(isset($_POST))
{
$username = $_POST["username"];
$password = $_POST["password"];
//process login here
//check database
if($success == true)
{
header( 'Location: home.php' ) ;
}
else
{
include "login-view.php";
$error = "Either username or password is incorrect.";
}
}
else //GET method used. The user visits the login page
{
include "login-view.php";
}
?>
login-view.php
<p><?php echo $error; ?></p>
<form method="post" action="login.php">
<input type="text" name="username" value="<?php echo $username ?>" />
<input type="password" name="password" />
<input type="submit" value="send" />
</form>
The code above goes like this:
1) The user visit the login page. login.php will detect that the method used is GET -- cliocking a link, opening a bookmark or typing URL to address bar. login.php then will include login-view which contains the form.
2) The user type his username and password and click submit button. login.php will detect that the request is POST, then validate username and password, provide error message if necessary. If valid, then redirect to home page, if not, include login-view.php (form), this time with error message and previously typed username.
Related
I am trying to redirect a user to a 'success' page if the registration was successful. However, by this point, headers have already been sent so I can't just call header() directly.
What I did instead was put an included file (call it redirect.php) above the Doctype on the page:
// handle requested redirects
if (isset($_POST['redirect_to']))
{
$new_page = $_POST['redirect_to'];
header("Location: http://localhost/$new_page");
}
So if $_POST['redirect_to'] is set, then header() can redirect to that page. Now the problem with this approach is that this $_POST[''] variable is inside a function tasked with processing the user's registration, so of course, the form has already been submitted before the post variable is set, and therefore, redirect.php never gets to see the post variable.
Is there an easy way around this or am I making this harder than it needs to be?
Since you havent mentioned AJAX my guess is that you are just having a wrong concept of registration process.
Common registration process and structure:
<?php
if( !empty($_POST['registerme']) ){
// do the registration process and possible errors STORE IN THE VARIABLE
// lets say $errors, it could be an array of strings or anything you want
// if registration process was succesfull,
// set $reg_suc to true otherwise to false
if( $reg_suc ){
header('Location: success.php');
exit();
}
}
?>
<?php
if( !empty($errors) ){
//there were some errors
foreach( $errors as $error ) echo $error."<br>\n";
}
?>
<form action="#" method="POST">
<input type="hidden" name="registerme" value="registerme">
<input type="text" name="validateName" placeholder="name">
<?php if( !empty($errors['validateName']) ) echo "Please correct this value"; ?>
<!--
//some more input fields
-->
<input type="submit" value="Register">
</form>
EDIT: This is of course common only for very simple applications with registration/login functionality, in MVC(P) architecture and similar achitectures this is usually created by a view using template file providing HTML template and a model/controller or model/presenter (in e.g. PHP) that are handling the registration/login process and possible error log and that are outputting results, errors and other data through the view back to user...
I learned this back in college a few years ago, and now I actually have to do something like this for work. I'm sifting through my old homework assignments and man I wish I was neater.
I'm creating a registration page.
User submits POST to self -> php validates on the same page
if it's good
I direct to a thankYou.php page and clear any variables.
if it's no good, I redirect to myself and populate the form with my bad answers.
Do i need to start a session and store all my variables in a session or something?
I omitted some of the code. to make it quicker to read
<?php
//connect to database.....
//Extracting the data
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$pageValid = true;
$fName = $_POST['fName'];
$lName = $_POST['lName'];
};
//validate $fname $lname etc $pageValid = true if it's all good
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if ($pageValid == true){
//insert into sql
header('Location: thankyou.php');
exit;
} else {
//if page is not valid redirect come back here
header('Location: register.php');
exit;
};
} //<!--End of ($_SERVER['REQUEST_METHOD'] == 'POST')
?>
<!DOCTYPE html>
<html lang="en">
<head>header...</head>
<body>
<div id="form" class="col-md-12">
<form id="form1" name="form1" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<table class="table"><tr>
<td width="200"><label for="firstName">First Name:</label></td>
<td>
<input name="fName" type="text" id="register"
value="<?php
//$fName I want to add the value of $fName here after it gets redirected
?>" size="25" maxlength="50" /> *
<?php print $fNameError;?>
</td>
</tr>
</table>
</body>
</html>
fName can be populated with $_REQUEST['fName']
You could always retrieve the value of every post inputs using $_POST (or $_GET for forms with the GET method)
In both cases, you can retrieve your input values accessing the array $_REQUEST. Find here the documentation
Using a session is a really really bad idea: it would cause you tons of headache when your user will start accessing your web app from multiple tabs. It is also a problem since it will require you to clear the session after having processed the form, or unexpected results may happen the next time the user will use the form (like, for example, input fields automatically and unexplainably filled with no user input).
Update
Storing forms inputs in the session is discouraged for at least two reasons:
sessions are shared between all the pages concurrently opened by the same user. Imagine you open the form in a tab and you submit it with some errors; the web app will re-open the form, filling the forms with the data it has in session. Now, open a second tab with the same form: the session is still the same, so the form will be filled with the data in the first form. Submit it with some errors: you will have changed the data for both the forms
$_REQUEST items are populated during a POST, and they are automatically cleaned up the next request; sessions are not, they are persisted for the whole session. This means that your code will need to clear them up explicitely, or you will risk to find form inputs with the old values even without a form submit
Yes, storing data in $_SESSION variable is a good idea.
e.g.$_SESSION["lname"] = $_POST["lname"];. Obvioulsy you need to start a session, check for input validity, etc....
Basically you check for the existence of a POST variable:
<?php
if( isset( $_POST['fName'] ) )
{
// the form has been submitted, do something
}
?>
You don't have to use session variables if your form data is displayed on the page that receives the POST data.
Edit
If you want to populate some $_SESSION variables then you could stuff all the POST data into a session array
<?php
if( isset( $_POST['fName'] ) )
{
$_SESSION['posted'] = $_POST;
}
?>
Or, if you validate POST data and want to populate the session with only valid input:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$_SESSION['formData'] = array();
$_SESSION['formData']['pageValid'] = true;
$_SESSION['formData']['fName'] = $_POST['fName'];
$_SESSION['formData']['lName'] = $_POST['lName'];
};
?>
You don't need to redirect back to the form on an error... The form is built within the same script so just let it render the rest of the script. You only need a redirect on valid registration data.
Basically, get rid of the "else" portion of you PHP.
echo "Hello : ".$_SESSION['doc_username'];
//username sent from a different page by post method
$username = $_POST['username'];
echo "<p><strong>Showing Health Information for : </strong>";echo $username; "</p>";
if($_POST['submit'])
{
$height = mysql_real_escape_string($_POST['height']);
$weight = mysql_real_escape_string($_POST['weight']);
if($height && $weight)
{
require "dbc.php";
$query = mysql_query("UPDATE patient_info SET
height='$height',weight='$weight' WHERE username='$username'");
echo "Patient Data Saved!";
}
else
{
echo "All fields are required!";
}
The problem with this code is not in the mysql query. I have already checked it for syntax errors using phpcodechecker and there was none. There were more variables to be inserted into the database but height and weight will do for example. My problem is I am getting the username from a different page by POST method and I cannot save it in a way that it could be used by the "submit" value in this form to enable updating of that particular username. Because the username from the other form which $username cannot be referred to within the $_POST in this page, thus the username variable is blank when I click the submit button. How can I get a username sent from another page to this page by POST to be used in this form in the UPDATE query. The form does send the username to this page successfully which is proven when I can echo the username out. But it cannot be used by the form in this page. Please help as I am very new to PHP codes and I'm trying the best that I can.
On the initial page, add a hidden form element named "username" with the value you want to carry over into the form submission.
<input type="hidden" name="username" id="username" value="the.user.name">
You may store user name in session on request when it passed, or add to getparam of request or in hidden element of form:
<form action="procces.php?username={real_user_name}">
OR
<form>
<input type="hidden" name="username" id="username" value="{real_user_name}"/>
...
</form>
<input type="text" name="username" value="<?php echo $_POST['username']; ?>" />
The username in first page was transferred to another paged where you can edit it
As second page also contains a form so we also need to add username field int as when it will be posted the username will also be sent.
This had to be inserted into the 2nd form to retain the data sent from the previous in the previous page so that it can be used for the query in mysql.
First of all replace the line:
From:
if($_POST['submit'])
to:
if (isset($_POST['submit']))
If you are using a combobox then check that you have provided the name parameter in its markup like:
<select name="submit">
...
</select>
[EDIT]
After analyzing the code it is found that the HTML markup
was written after form element. I think this is the issue. Rest
appears to be Ok.
Hope this will solve the issue.
You may the user name in the session (supposed you have one, if not, you seriously should anyway):
Populating a form field like #tslocum suggested also needs to get the user name from somewhere. This is a quite common solution, but where does the user name come from?
There might be some time between submitting the name and rendering the current page, so as this is stateless but you need a state (State "we have a given username already") within that page during rendering and processing, take a look at $_SESSION global variable.
my approach:
Post 1:
....
$_SESSION['currentUser'] = $_POST['username'];
// you need some checks over here, don't use
// that as typed here, left out just for clearness.
... some time
Post 2:
...
$username = $_SESSION['currentUser'];
// again some checks over here!
read about $_SESSION in the php manuals.
I'm quite new in this PHP programming and already tried looking my issue at this forum but no success.
I have build a simple webform using PHP and stuck when trying to edit form. My form consist of below
register html form - basicallly user fill in the form and hit submit. the form will then go to register.php
Register.php - all the field store at database and I also display the form using the SESSION (not call from database) in this page.
Here is my problem start. At the dispay(register.php) I want allow user to edit his/her information and submit again(which i think use update query base on ID). But I truly don't know how to do this.
Can someone advice me or give some simple code for this so that I can have clearer view?
you also must strip slashes for avoiding Sql injection
In previous pages you must store the username from textbox of login
Something like this:
session_start();
$_SESSION['username']=$_POST['input of login txtbox'];
you can just get the condition with user cause you have just one unique user 2 users mustn't have the same user name then just store the username of them in $_SESSION
$connection=Mysql_connect('server','user','pass');
if(array_key_exists('sub2',$_POST))
{
if(!$connection)
{
echo 'connection is invalid';
}
else
{
Mysql_select_db('Your DB',$connection);
$pas=$_POST['pass1'];
$username=$_POST['username'];
$pas=mysql_escape_string($pas);
$username=mysql_escape_string($username);
$query="update user set user='$username'and pass=password('$pas') where username='".$_SESSION['username'].";
//some code
}
in your form:
<p><b>User Name:</b><input type="text" name="username" />
<p><b>Password:</b><input type="password" name="pass1" />
<input type="submit" name="sub2" value="update"/>
use this site for secure your code
I am sending login status = fail, back to my login page.Here is my code-
header("location:index.php?login=fail");
but that is sending through URL like-
http://localhost/303/index.php?login=fail
is there any way to pass value without showing in URL? And how to get this value on the second page?
You are passing that value via a GET request, which is why it appears in the URL. In order to pass a value without showing it in the URL, you want to pass it via a POST request.
In order to do this you aren't going to want to "return" the value to your login page. Instead, whatever php form is handling the process of logging in the user after they click the "login" button, will decide what to show the user.
In PHP post variables can be accessed by the global $_POST object -
$_POST['username'];
Would get the value with the name "username" that you passed via POST:
<form method="post" action="checkLogin.php">
Username:
<input type="text" name="username" maxlength="25" />
Password:
</td><td><input type="password" name="password" />
<input type="submit" name="submit" value="Login">
</form>
In order to dynamically save and show errors to the user, you can store them in the session, for example have a file called "errors.php"
<?php
if (isset($_SESSION['errors']))
{
echo $_SESSION['errors'];
}
unset($_SESSION['errors'])
?>
And in your php that checks the login, do:
session_start();
$_SESSION['errors'] = "Invalid username or password.";
Then redirect to your login page (don't pass any variables) and on your form always have this field:
<?php include("errors.php"); ?>
If you didn't have any errors, it won't show anything and the login page will look normal.
Note: In any php form that you use a session_start(), it HAS TO BE THE FIRST THING in the form.
Other ways are to use session or hidden fields but you what you are doing is fine for the purpose. You can later retrieve the value like this:
if ($_GET['login'] === 'fail')
{
// failed.......
}
there are several ways to accomplish your task
Modern AJAX way. Form being sent using AJAX. No page reload until password is correct. Errors shown in place. Requres javascript.
Post/Redirect/Get pattern. Form being sent using regular POST. No redirect on errors, shown in place.
sessions, when we store an error in the session