How do I pass information between PHP pages?
For example, I have a PHP script to process login input from a form, and then a separate PHP script to process further input for the user. However, I want the second PHP file to receive the input from the login form. In essence, I do not want the same script being run twice for the login.
You are looking for POST and GET variables, it's done in the method parameter of your HTML form:
login.php
<form name="myform" action="secondpage.php" method="post">
<div>Username: <input type="text" name="username" value="" /></div>
<div>Password: <input type="password" name="password" value="" /></div>
</form>
Then in this other page:
secondpage.php
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
if ($username != '') {
// do your validations here
}
Explanation
When you use the GET method, the parameters are visible in the URL, so let's say we change the method="GET" in login.php, you'll end up with something like secondpage.php?username=jsmith&password=1234. And then you could get the values using $_GET['username'].
Using POST makes it possible to send larger quantity of data (there is a vague limit to the size of a URL) and it's not visible in the URL. You should note though that it's still sent in clear text, so it does not means it's secure.
POST and GET were made for different purposes. GET should be use to extract information that you could want to extract again in the future, information that is not special to this very instant. It's useful to have mypage.php?product=123 because you'll potentially want to send this URL to a friend. A POST should be used when you'll modify the state of data: updating a product, creating a new user, deleting an article and so on. It's something you want to happen once.
Structure
In conclusion, I just want to add that normally you wouldn't necessarily want to use another PHP script just to avoid some code to run or not. So without knowing the specifics of your project, I can nevertheless say that you would probably want to do something like that to benefit from the same code (such as the form's HTML).
Please note it's simplified code.
login.php
<?php
$error = false;
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
// if, and only if something was posted... so not on first display
if ($username != '') {
// do your validations here
if ($properlyLogged) {
session_start();
$_SESSION['loggedAt'] = time();
header('Location: http://localhost/secondpage.php');
exit();
} else {
$error = true;
}
}
?>
<?php if($error): ?>Login failed. Please try again.<?php endif; ?>
<form name="myform" action="login.php" method="post">
<div>Username: <input type="text" name="username" value="<?php echo($username) ?>" /></div>
<div>Password: <input type="password" name="password" value="" /></div>
</form>
secondpage.php
<?php
session_start();
if (!isset($_SESSION['loggedAt'])) {
// if not properly logged in, return user to login
header('Location: http://localhost/login.php');
exit();
}
?>
You are now logged in!
Hope that's what you were looking for!
You can pass information between pages using GET or POST methods. GET would append the information you wish to pass as a querystring on the url such as:
loginprocess.php?id=JSmith&pword=HelloThere (this isn't exactly recommended for private information)
The other method is to send the information via POST so that it is hidden from the querystring.
More examples can be seen here: http://www.tizag.com/phpT/postget.php
If the data isn't that large you could redirect the user to the 2nd page with the data passed via the URL (GET variables). Otherwise, just run the seconds method in the same page, and use a function to do the final parsing of the data which can be included as the above user suggests.
Just a small extra to what was written before: the limit on the GET (parametrize URL) is a full URL, which means 1024 characters. If you need more than that, you have to use post.
You can take advantage of PHP sessions to share data amongst your PHP scripts. Basic example below, read more here.
login.php:
<?php
// initializes the session //
session_start();
// save user name and password to session //
$_SESSION["username"] = 'someuser';
$_SESSION["password"] = 'somepassword';
$_sESSION["valid"] = true;
?>
secondpage.php:
<?php
// start session handler //
session_start();
// check for a valid session //
if (!isset($_SESSION["valid"])) header("Location: login.php\n\n");
// continue page code here //
?>
Related
I have a form, which redirects the user to "page1.php" after the form is submitted. What I want to do is to redirect the user to "page2.php" after the form is submitted, but I need to make sure that the POST request was sent. Example:
<form action="page1.php" method="POST">
<input type="text" name="username" />
<input type="text" name="age" />
<input type="submit" value="" />
</form>
When the user clicks on Submit, it redirects him to page1.php. I want to redirect him to page2.php, but I need to make sure that the data is sent to the server. I can't use AJAX. Is there any way to do it with cURL or something like that? Any examples?
Thanks!
I guess this works !!
In page1.php
<?php
//do establish session
//and check for the input fields obtained via $_POST
if(isset($_POST['name_of_your_field']) && !empty($_POST['name_of_your_field'])){
if(!mail($to,$subject,$message)){
header('location:form.php?msg=error');
}else{
header('location:page2.php?msg=succes');
}
}
?>
You can check if the POST request was sent with something like:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// do something...
}
You can create a hidden input in your form and send additional info about the form that is submitted, e.g. action.
Inside you will do your magic and redirect user with:
header('Location: page2.php');
exit();
In your 'page1.php' processor, add a 'header' redirect to 'page2.php'.
header("Location: page2.php");
exit;
you could do a check if query is complete
example
<?php
$query=mysqli_query(".......your query statement")or trigger_error(mysqli_error());
if($query){
header("Location:page2.php");
}
else{
die('error');
}
?>
In your situation, you can just simple check for the posted data. Like
$username = $_POST['username'];
$age = $_POST['age'];
if($username&&$age){ /* This is to check if the variables are not empty */
// redirect to page2
}
It is logical that if those are not empty, meaning they are posted. Even if they are empty, as long as you get there, that means it was posted. There is no need to check if posted or not, what needs to be checked was, if posted data was there.
I hope I made it clear. ^_^ but making sure is not bad at all. Happy coding friend.
I've been trying to do form validation without using the url. So I thought that I would create a hidden field in my form and send it over to my validation php script. What I was hoping I would be able to do is set what ever errors there are in the form to this hidden field and return it. However once I get out of the scope it destroys whatever I set. I thought $_POST had global scope? Maybe I declared I set the hidden field wrong? I have placed the code below.
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/databaseConnect.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/functions.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/users.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/userDetails.php';
//get the refering url to be used to redirect
$refUrl = $_SERVER['HTTP_REFERER'];
if(isset($_POST['register'])){
//declare a temp error array
$tempError;
//check if the form is empty
if(empty($_POST['Email'])&&empty($_POST['Email Confirmation'])&&empty($_POST['Password'])&&empty($_POST['Password Confirmation'])
&&empty($_POST['Stage Name'])&&empty($_POST['Main Club'])){
$tempError = 'Please fill in the form.';
}else{
//set variables
}
if(!empty($tempError)){
//start a session to declare session errors
$_POST['errors'] = $tempError;
//redirect back to referring url
header('Location:'.$refUrl);
exit();
}else{
//log user in and redirect to member home page
}
}
Basic form (I excluded the input field as it would be really long)
<div class="col-md-6 well">
<span class="jsError"></span><?php if(isset($_POST['errors'])){ $errors = $_POST['errors']; } if(!empty($errors)){ echo '<p class="alert alert-danger text-center">'.$errors.'</p>'; } ?>
<form class="form-horizontal" role="form" method="post" action="controllers/registrationController.php" id="registration">
<input type="hidden" name="errors" value="<?php if(isset($_POST['errors'])){echo $_POST['errors']; } ?>">
</form>
I looked into using the $_SESSION variable method too but the stuff I found was either a bit complicated or it involved me starting a whole bunch of sessions everywhere (would make my code messy in my opinion).
$_POST is populated from the contents of the data passed by the browser to the server. When you send a Location header it causes the browser to load a new page, but since it will have no form data, nothing will be passed.
If you need to pass data from page to page then $_SESSION is the way to go. All that is required is a session_start() at the top of the pages that need access, and you can store your $_POST data like this:
$_SESSION['postdata'] = $_POST;
Retrieving it becomes
$email = $_SESSION['post']['Email'];
The alternative is to echo the data as a hidden <input> in a new form, but that will require a new form to be submitted and I get the feeling you want something seamless.
Note also that $_SERVER['HTTP_REFERER'] is not guaranteed to be accurate, or even present. You shouldn't rely on this for production code. It might work for you with your browser in your test set-up, but that's no guarantee it'll work for other browsers. Find another way.
You can achieve this by using javascript instead of a redirect, but the only way to pass data through a redirect is via the URL, the session, or cookies.
$_POST['errors'] = $tempError;
//redirect back to referring url
?>
<html><head><title></title></head><body>
<form id="temp_form">
<?php
foreach($_POST as $k=>$v) {
?><input type="hidden" name="<?php echo htmlentities($k); ?>" value="<?php echo htmlentities($v); ?>" /><?php
}
?>
</form>
<script type="text/javascript">
setTimeout(function() { document.getElementById('temp_form').submit(); },100);
</script>
</body>
</html>
<?php
die();
I wish some help .
I need a php script using session id to redirect a specific username and password log in
to a specific html form as no one except that user can reach links without logging in by this username and password (i.e no one can copy the link after logging in at another browser and proceed) . Something like admin area or something.
(note : i'll specify name and password by myself not by retrieving it from database ,So no SQL scripts needed)
I searched too much in that and couldn't find something helps .
appreciate ur effort in advance .
On special_form.php and/or other similar pages put something like this:
check_login();
Where check_login() is something like this:
function check_login() {
if ($_SESSION['login'] == true AND !empty($_SESSION['user_id')) {
if ($_SESSION['username'] != 'MyUser' OR $_SESSION['password'] != 'MyPass') {
header('Location: http://www.domain.com/login.php');
}
} else {
header('Location: http://www.domain.com/login.php');
}
}
Now, on login-process.php write something like this:
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
if ($_SESSION['username'] == 'MyUser' AND $_SESSION['password'] == 'MyPass') {
header('Location: http://www.domain.com/special_form.php');
}
// normal login process code
I just hope that I've understood your problem correctly. Give me some hints if I'm wrong somewhere. :)
Put this on top of all pages to check if logged in:
if(!isset($_SESSION['loggedin'] ||
!$_SESSION['loggedin']==1) header('Location: http://website.com/login.php');
Html form on login.php
<?php
//And just check post variables from form:
if(isset($_POST['submit'])) {
if(strcmp($_POST['username'], 'Your username') == 0 &&
(strcmp($_POST['password'], 'Your password') == 0) {
$_SESSION['loggedin'] = 1;
header('Location: http://website.com/youareloggedin.php');
}
}
?>
<form action="" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
Some tips:
do not write anything to page before calling header function, it will break it.
A blank action on form will send data to itself, make sure php is on top (it is generally easier to keep all php on top and use inline php when needed e.g. <?=functionorvariable()?>
strcmp compares two strings, if they are equal it will give you zero as a return value.
always use isset to check if form was actually submitted on page instead of checking values.
you should add in error checking for checking post values, to see if they are empty or whatever, it is good practice.
learn by doing, please study the structure of this program and see how it is clearly written, it's intentions are clear. Always follow the clarity route when coding.
Good luck
I have faced a problem in all of my php projects is that since i used OOP is that if there is a user submitting a form
when it goes to processing it and if it has an error i save a message in the session and redirect them to the same page
this is a sample and of course when it redirects it wipes all the fields that was there
like let's say i have a register form that had
<?php if(!empty($message)) { echo $message } ?>
<form action ="forms/register.php">
first name: <input type="text" name="first_name" />
username:<input type="text" name="username" />
<input type="submit" value = "submit" />
</form>
and this is what the code in forms/register.php
if(isset($_POST['submit'])) {
$first_name = $_POST['first_name'];
$username = $_POST['username'];
if(empty($first_name) || empty($username) {
$session -> message("please fill in all the fields");
redirect("../register.php");
} else {
// do something else like insert query
}
}
my problem is if first_name or user_name is empty and it redirects to register.php
and it echos the error message no problem in that
but the fields are empty the first_name and the user_name are empty
so the user has to fill it all again
so one of my friends suggested to save it in the session or something
so i would like to know if that is possible then how and what i mean by how so nobody would get it wrong, i mean the way not the code to just copy it and paste it
Thanks in advance
and sorry for being long and annoying
You can store whatever values you want to keep persisted in the form after the page redirects in session variables, then retrieve those values on the form page and echo them in the value attribute of the form elements.
session_start(); $_SESSION['nick'] = $_GET['nick'];
more / better examples:
http://php.net/manual/en/function.session-start.php
Not sure what issue you exactly are facing (also what $session is inside your workflow?).
However, i recommend using PHP inbuild session support.
http://php.net/manual/en/features.sessions.php
From the above link itself:
<?php
session_start();
if(isset($_SESSION['views']))
{
$_SESSION['views']=$_SESSION['views']+1;
}
else
{
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
}
?>
Above code simply keeps track of page views. $_SESSION variable persists between page loads and you should be using the same for all your session requirements.
I am having problems figuring out how to retain users data when the validation fails. I am somewhat new to PHP so I might be making some huge mistakes in my logic.
Currently if the validation fails all the fields are wiped clean and $_Post data is also gone.
Here is some code assuming the user enters an invalid email I want the Name field to be retained. This code is not working.
<?php
if($_POST['doSubmit'] == 'Submit') {
$usr_name = $data['Name'];
$usr_email = $data['Email'];
if (isEmail($usr_email)==FALSE){
$err = "Email is invalid.");
header("Location: index.php?msg=$err");
exit();
}
//do whatever with data
}
if (isset($_GET['msg'])) {
$msg = mysql_real_escape_string($_GET['msg']);
echo "<div class=\"msg\">$msg</div><hr />";
}
if (isset ($_POST['Name'])){
$reusername = $_POST['Name'];}
else{$reusername = "NOTHING";}//to test
?>
<form action="index.php" method="post" >
<input name="UserName" type="text" size="30" value="<?echo $reusername;?>">
<input name="Email" type="text" size="30">
<input name="doSubmit" type="submit" value="submit">
</form>
}
You can use AJAX to submit your form data to your PHP script and have it return JSON data that specifies whether the validation was successful or not. That way, your fields won't be wiped clean.
Another way is to send back the recorded parameters to the posting page, and in the posting page, populate the fields using PHP.
However, I think the first solution is better.
UPDATE
The edit makes your code clearer and so I noticed something. Your input field is called UserName in the HTML, but you are referring to Name in PHP. That's probably why it's not working. Is your field always being filled with the value NOTHING? Make sure the name of the input field and the subscript you are using in $_POST are the same.
Also, there's no need to redirect to another page (using header) if you have an error. Maintain an $errors array or variable to print error messages in the same page. But like I mentioned before, it's probably better to use the JSON approach since then you can separate your view layer (the html) from the PHP (controller layer). So you'd put your HTML in one file, and your PHP in another file.
EDIT:
Vivin had commented that my assumption regarding the header was incorrect and he was right in that. Further more it looks like what the OP is doing is essentially what i layed out below albeit in a less structured fashion. Further Vivin - caught what is likely the actual problem here - the html name and the array key $_POST do not match.
Its wiped clean because you are using header to redirect to another page. Typicaly you would have a single page that validates the data and if ok does something with it and returns a success view of some sort, or that returns an error view directly showing the form again. By using header youre actually redirecting the browser to another page (ie. starting up an entirely new request).
For example:
// myform.php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'get')
{
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
elseif(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
$form = santize($_POST); // clean up the input... htmlentities, date format filters, etc..
if($data = is_valid($form))
{
process_data($data); // this would insert it in the db, or email it, etc..
}
else
{
$errors = get_errors(); // this would get our error messages associated with each form field indexed by the same key as $form
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
}
so this assumes that your form.inc.php always has the output of error messages coded into it - it just doesnt display them. So in this file you might see something like:
<fieldset>
<label for="item_1">
<?php echo isset($error['item_1']) ? $error['item_1'] : null; ?>
Item 1: <input id="item_1" value="<?php echo $form['item_1'] ?>" />
</label>
</fieldset>
Could do something similar to if failed then value=$_POST['value']
But vivin's answer is best. I don't know much about AJAX and wouldn't be able to manage that.
Ok, firstly header("Location: index.php?msg=$err"); is not really required. It's best practice not to redirect like this on error, but display errors on the same page. Also, redirecting like this means you lose all of the post data in the form so you can never print it back into the inputs.
What you need to do is this:
<input name="Email" type="text" size="30" value="<?php print (!$err && $usr_email ? htmlentities($usr_email, ENT_QUOTES) : '') ?>">
Here I'm checking whether any errors exist, then whether the $usr_email variable is set. If both these conditions are matched the post data is printed in the value attribute of the field.
The reason I'm using the function htmlentities() is because otherwise a user can inject malicious code into the page.
You appear to be processing the post on the same page as your form. This is an OK way to do things and it means you're nearly there. All you have to do is redirect if your validation is successful but not if it fails. Like this
<?php
if( isset( $_POST['number'] ) ) {
$number = $_POST['number'];
// validate
if( $number < 10 ) {
// process it and then;
header('Location: success_page.php');
} else {
$err = 'Your number is too big';
}
} else {
$number = '';
$err = '';
}
?>
<form method="POST">
Enter a number less than 10<br/>
<?php echo $err ?><br/>
<input name="number" value="<?php echo $number ?>"><br/>
<input type="submit">
</form>