Transfer variables between PHP pages - php

I want to get user input in one page, store that in a php variable and use it in another php page. I have tried using 'sessions' but it doesn't seem to be working. Is there another safe alternative? This information is likely to be usernames and passwords.

Try changing your session code as this is the best way to do this.
For example:
index.php
<?php
session_start();
if (isset($_POST['username'], $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
echo 'Click to continue.';
} else {
// form
}
?>
nextpage.php
<?php
session_start();
if (isset($_SESSION['username'])) {
echo $_SESSION['username'];
} else {
header('Location: index.php');
}
?>
However I'd probably store something safer like a userid in a session rather than the user's login credentials.

I Agree with carson, sessions should work for this. Make sure you are calling session_start() before anything else on any page you want to use the session variables.
Also, I would not store password info directly, rather use some kind of authentication token mechanism. IMHO, it is not intrinsically unsafe to store password data in a session, but if there is no need to do so, you should probably try to avoid it.

There are several ways:
use sessions (but don't forget to call session_start() on every page you'll use the session data store ($_SESSION))
append your data to the query string of the "next" page ($_GET)
post your data to the "next" page ($_POST)
The session-way is the only way on which the data does not "leave" the server as it's stored on the server itself. For all other ways mentioned above you have to take care of sanitizing and validating the data on the receiving page.
The most simple way would be
//page1.php
session_start();
$_SESSION['user']='user';
$_SESSION['password']='password';
//page2.php
session_start();
echo $_SESSION['user'] . ' ' . $_SESSION['password'];

You can try using POST and GET methods for transferring user inputs within PHP scripts.
PHP GET
PHP POST

I agree too, sessions are the best solution. See this chapter from Web Database Applications with PHP & MySQL for some examples.

Related

Understanding PHP files and AJAX calls

I'm slowly learning PHP ;-) I'm having difficulties understanding how separate PHP-files work together.
I make AJAX calls to different php files that all need to be connected to the backend (Parse). Such as:
sign_up.php
login.php
verify_email.php
get_something_out_of_the_database.php
What is the standard way to stay logged in over the different php files? (or what is the google search term for it..?)
Update:
Thanks for all your answers about 'sessions'. I doesn't work very well yet, so i made a new question.
Thanks!
Remzo
You should use PHP sessions. These are a way to store information on visitor browser between multiple pages...
To start a session, you first need to add session_start(); in every PHP file you intend to use it. Usually it's added in a header.php
Then, you can use sessions already.
To store a result:
$_SESSION['some_data'] = $var;
To retrieve a result in another page, for example:
echo $_SESSION['some_data']; // will echo $var
More info can be found here:
http://www.w3schools.com/php/php_sessions.asp
You can do this for example by storing the login-data in a session-variable and checking it at the start of every new page.
Example:
You check if login-data is valid. Then
session_start();
$_SESSION["login"] = $loginname;
At the start of another page:
session_start();
if(!isset($_SESSION["login"]) || $_SESSION["login"] != "check_somehow")
{
header("Location: logout.php");
exit;
}
For logging out you can use
session_start();
session_destroy();
On the start of your user logged in, you can do something like
session_start();
$_SESSION['USER'] = <some user info>;
In your other pages you can see if
if(isset($_SESSION['USER'])){
// do something
}
at last on logout
session_destroy();
will kill the session

Putting variable in header = PHP

So I'm trying to make the posts.php page look like this >> 'posts.php?user='.$username << for each individual user.
Here is the code on my index.php page (which after a user logs in/signs up turns into >> 'index.php?user='.$username :
<?php
include('header.php');
session_start();
if(!isset($_SESSION['username'])) {
//do nothing
} else {
$_SESSION['username'] = $_GET['user'];
$username = $_GET['user'];
$_SESSION['username'] = $username;
}
Here is the code so far on my posts.php page :
<?php
include('header.php');
session_start();
if(!isset($_SESSION['username'])) {
header('location: must_login.php');
} else {
//idk what to put here
}
?>
I'm trying to get my posts.php page header to look like this >> 'posts.php?user='.$username
I understand you are on day 1 of PHP learning. You are getting a lot of negative responses because your question isn't very specific. You aren't very clear about what is "not working." You should say what you expect to happen, and what is happening.
Here's my answer based on what I think you're asking.
Since the username would usually be gotten from a sign-in form, and sign-in forms usually use POST, you should probably do that. Use POST instead of GET.
included files have access to all the global variables in the file from which they are included.
File#1:
// index.php
$username = $_POST['user'];
include('header.php');
File#2:
// header.php
<div id="header">
<p>You are logged in as user "<?= $username ?>"</p>
</div>
The variable you set in index.php $username is available for use in header.php.
Ok so there's a fair few things you need to consider here, but we all had to learn once so I'll try and cover most of them.
Firstly (as #TrentonMaki has said): DO NOT USE USERNAMES IN URLs. If this site is going live, it is probably the most dangerous thing you can do, aside from printing out your passwords onto the screen.
You must read about authorisation and authentication before you continue.
Secondly, in the interests of learning: the $_SESSION super-global is not the right one to use for URL variables. We call URL variables "GET" variables and therefore they are accessible like this:
$user = mb_convert_encoding($_GET['myVar'], ‘UTF-8′, ‘UTF-8′);
$user = htmlentities($user, ENT_QUOTES, ‘UTF-8′);
These functions 'escape' the data in the variables to make them safe from XSS and SQL Injection attacks (there are alot of other precautions you need to take as well - but they are outside of the scope of this question).
In terms of Sessions, these are variables that are stored in the server memory and persist between pages. there are several considerations when using Sessions (security vulnerabilties like "Session Hijacking") and things you can do to make Sessions safer, but here is how they basically work.
//start the session to retrieve or set variables
session_start();
//you should regenerate session_id here - you need to look up how to do this and other Session santisation.
//set a session var
$_SESSION['myVar'] = "myString";
Now when a new page is loaded you can get the value of a $_SESSION var:
//start the session to retrieve or set variables
session_start();
//you should regenerate session_id here - you need to look up how to do this and other Session santisation.
//get a session var
$myVar = $_SESSION['myVar'];
Some other topics you should definitely learn before you go any further:
mysqli extension - do not use the mysql functions - this is by far the most common mistake new PHP developers make
Prepared statements - these are a MUST for live data security. You should learn them so you never use anything else.
Note :
1.Passing Variable above included file will passing variable to all included script
2.session_start(); must ONLY ONTOP of script and call only session_start(); to avoid session already started error.
<?php
session_start();
$username = $_POST['user'];
include('header.php');
?>

PHP: Sending a constant through a form and auto-sending it

For a website, I need to route users to their own page. I have a login form, which sends data to a PHP file to check if the user's information is correct, and if so, forwarding the user to their page. The only problem is that I need to validate the user on arrival, to check if they logged in or just typed out the URL. I plan to use this with a POST, but how can I auto-send the constant (i.e. "logged-in")? Is there a way to do that through an HTML form (outputted from an echo) and sending it when the page loads? Thanks in advance!
EDIT 1: I understand that I must use Sessions, but whenever the page redirects it clears the session. The whole reason I was asking this was because I needed a way to keep the session active. How do I redirect in a way that doesn't clear the session?
In the PHP file that validates their credentials, start a "session". You can then apply session variables that can be called at any time while the session is valid. You can do this with POST, which is sounds like you're using, or by querying a database upon validation.
For example, upon validation:
session_start();
$_SESSION['username'] = $_POST['username'];
$security_check = mysql_query("SELECT * FROM userList WHERE username = '$username'");
$row = mysql_fetch_assoc($security_check);
$_SESSION['userId'] = $row['userId'];
$_SESSION['userFullName'] = $row['userFullName'];
On subsequent pages, you can put the following code at the top to check if the user logged in. If not, it will kick them back to the index page; otherwise the $_SESSION variables will be maintained.
<?php
session_start();
if (!isset($_SESSION['userId'])) {
echo "<script> window.location.replace('index.php?login=no') </script>";
}
?>
As suggested in the comments, I would recommend doing some further research on sessions to get a full understanding of how they work.

PHP Sessions: Explanation please?

I have been learning PHP for a little bit now, and it has been going really easy for the most part. The only thing I'm hung up on is getting sessions to work. Google has been unforgiving in this endeavor.
It could be one of two reasons; syntax or my software. I'm currently building a local website using EasyPHP 5.3.5.0 on a machine that isn't connected to the internet. Connecting it to the internet is not an option.
What I currently know of sessions is that a lot of syntax related to it has be deprecated, replaced by the superglobal $_SESSION array, which is a lot easier to use. start_session(); must be before any syntax relating to sessions. However, my login script isn't establishing a session, as a quick !isset ($_SESSION['username']) always returns true.
My script is set up like this:
PHP include to login.php, which is a form. check_login.php is what validates it, and if a query returns one row, it'll redirect to login_success.php which establishes the session, gives a welcome message then redirects (Using JavaScript) to the homepage.
Any ideas?
EDIT to include more information:
Here is a synopsis of my code:
index.php:
include 'main_login.php';
main_login.php:
if(!isset ($_SESSION['username'])){
...
Login form, action="cehcklogin.php" method="post"
...
}else{
var_dump ($_SESSION): // Just to see if it works
}
checklogin.php:
Connect to SQL
$username = $_POST['username'];
$password = $_POST['password'];
$username / $password stripslashes / mysql_real_escape_string
Query to find the username & password
$count = mysql_num_rows($result);
if($count = 1){
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
header("location:login_success.php");
}else{
echo "Wrong Username or Password."
}
login_success.php:
The login process goes to all of the way here, redirects home and that's where the problem is.
session_start();
var_dump($_SESSION); //This works
if(!isset ($_SESSION['username'])){
header("location:index.php");
}
Javascript redirect, and a welcome message appears.
It all works until you get to the homepage, which $_SESSION['username'] should be set, and it should not display the form, but it does.
It looks like you're not using session_start() in your main_login.php like etranger alluded to. You need to call that function at the start of each new request to begin using sessions.
Otherwise, if you are calling session_start() and you just neglected to show it in the code sample, then maybe the session ID is being lost during the redirect. Are you using cookie-based sessions or passing session ID as a URL parameter? Try printing session_id() or SID at the top of each page. This will let you know when the session is lost (the session ID will change or be "").
If you're using cookie-based sessions, then maybe the cookie is getting lost for some reason. If you're using URL parameter to pass session ID, then maybe transparent session ID support isn't working right.
You have to call session_start() as early as possible, and definitely before using $_SESSION, which would otherwise be empty.

PHP Login, Store Session Variables

Yo. I'm trying to make a simple login system in PHP and my problem is this: I don't really understand sessions.
Now, when I log a user in, I run session_register("user"); but I don't really understand what I'm up to. Does that session variable contain any identifiable information, so that I for example can get it out via $_SESSION["user"] or will I have to store the username in a separate variable? Thanks.
Let me bring you up to speed.
Call the function session_start(); in the beginning of your script (so it's executed every page call).
This makes sessions active/work for that page automagicly.
From that point on you can simply use the $_SESSION array to set values.
e.g.
$_SESSION['hello'] = 'world';
The next time the page loads (other request), this wil work/happen:
echo $_SESSION['hello']; //Echo's 'world'
To simply destroy one variable, unset that one:
unset($_SESSION['hello']);
To destroy the whole session (and alle the variables in it):
session_destroy();
This is all there is about the sessions basics.
The session is able to store any information you might find useful, so putting information in is up to you.
To try some things out, try the following and see for yourself:
<?php
session_start();
if(isset($_SESSION['foo']))
{
echo 'I found something in the session: ' . $_SESSION['foo'];
}
else
{
echo 'I found nothing, but I will store it now.';
$_SESSION['foo'] = 'This was a triumph.';
}
?>
Calling this site the first time should store the information, storing it the second time will print it out.
So yeah, you can basically put anything you like in the session, for instance a username.
Keep in mind, however, that the session dies as soon as the user closes his browser.
$_SESSION['user'] must be set to your user's name/id so that when you try to read it the next time, you'd be able to identify that user. For example:
login:
$_SESSION['user'] = some_user_id;
user area:
$user = $_SESSION['user'];
// extract the user from database, based on the $user variable
// do something

Categories