How can I pass variables to other files in PHP - php

I'm building a simple website with few pages such as index.php, about.php etc. I've included navigation file and I want it to automatically choose current page and use different styling. It can be done with one variable. The easiest way is to use GET method but I want to have shorter URL. So is there any other way? Because as far as I know POST refers only to forms. Maybe I should use cookies?

Use a session. It will keep a set of values stored in the $_SESSION superglobal as long as the client's session cookie is still set.
Example:
page1.php
<?php
session_start();
$_SESSION['test'] = "Hello, session!";
?>
page2.php
<?php
session_start();
echo $_SESSION['test'];
?>
If you visit page2.php first, you'll get no output. Once you visit page1.php, it will set the 'test' session variable. When you view page2.php again, it will show the result. This session is server-side, and is accessed by the session ID stored in a cookie by the browser. Session cookies are usually deleted when the browsing session ends (i.e. the user closes the browser) or when the session cookie timeout expires. Most sites use this as a mechanism to handle logins, by setting session variables relating to the logged in user (e.g. user id) when a login completes successfully.
See the PHP sessions reference: http://www.php.net/manual/en/book.session.php

Related

Php session not opening correctly on all pages

So I created this little login system for my php site, I have a login form where I first create the session with a few session variables like UserId and such.
I also do session_destroy() before i create the session so that any existing session will be destroyed.
Then I have this php file that I include on the top of every page on my site which opens that session with session_start() and starts the mysql connection and such.
Problem is, on some pages the session does open correctly and on other pages seems to create a new session. In fact if I go to another page and return to the page where the correct session isn't opening it's the same incorrect session, so I actually have two sessions opened it seems...
When I echo the session ID on page where it works and the one where it doesnt, they have different session ID's so I'm confused.
First of all don't use session_destroy() as it will delete the session on the next page request. Instead use:
unset( $_SESSION ); //this will delete the session immediately
To try and test the problem use the session_id() function:
<?php
$a = session_id();
if(empty($a)) session_start();
echo "SID: ".SID."<br>session_id(): ".session_id()."<br>COOKIE: ".$_COOKIE["PHPSESSID"];
?>
IF you are getting duplicate cookies (as is in this case), check the domain and path of each cookie. Make sure the cookie path are domain are always set to the same domain and path is always the root of your website (assuming you want the cookies site-global).
Each cookie is visible to the set path and domain, all paths starting with the path set, and may be set to match all subdomains of the domain.
Based on the comments to the question.

how to use session in php?

I am creating a login module in php. I am using session variables for that.
On the top of the file, I write
session_start();
Then when my login password is authenticated, I write
$_SESSION["username"] = $_POST["userid"]
now do I need to do something else as well to ensure that the session that got started sustains?? because as soon as it logs in, it logs out automatically? does it mean the session expires as soon as I log in?? In that case what should I do to make the session sustain??
Put session_start(); at the top of page where you will use the session variables.
And be sure you don't unset session in you login script.
No, session is meant to stay between the requests. If you read $_SESSION['username'] on next request, it will contain the data you saved in previous request. Obviously, you need to put session_start(); at the beginning of every page you want to interact with it.
session_start() doesn't start the session, it starts the session engine. It must be run on every page you want to have access to the session on.
You need session_start(); at the top of all files you are going to access Session data in
At the top, put session_start(); also on each page you want to use session, you need this function.
The session sustains as long as you didn't remove the session or close the browser, not sure whether it will expire sometime.
To check whether you are still logged in, you can access the session using $username = $_SESSION['username'];, or the function isset($_SESSION['username']) also helps.

Write session start on 1 page or all pages?

All the tutorials say to put session start. They don't say if that should be in all pages on the website, or some, or only 1.
And if it's only 1 page, does it have to be the main page? Or a page with a form that I am making that puts the session ID in the database? If the visitor never visits a page with a session id but they are on the site, do they still have a session id?
You need to put this in each page that need to access the session data before accessing (or creating) any session data.
See: http://php.net/manual/en/function.session-start.php
Just for a matter of completeness you can choose to write session_start(); in all pages, in just one or in none of them. Let me explain this.
You need to start session in every script where you need access to $_SESSION variable but instead of putting session_start(); in every single script you can create a file headers.php and put there all your repetitive code including session_start();
If everything in your application needs access to $_SESSION you can forget the use of session_start(); simply setting session.auto_start = 1 in your php.ini file. You will be able to access $_SESSION without writing session_start(); before.
More here
Anything that is going to access Session variables needs to start the session.
So unless you have a php page that is non-dependent on the session than every page needs it.
You need to declare session_start(); in every page if you want to get data from $_SESSION or store data into $_SESSION in those particular page. If you do not need to interact with $_SESSION then you don't have to declare session_start().#hmwhat

What is PHP session_start()

Does it start a current session based on cookies? Got that from the PHP website. How does PHP control the session? If I start a session when a user opens up my login page, what do I even use that session for? Can I use the current session to get info about the logged in user?
The PHP session system lets you store securely data in the $_SESSION global array. A typical example is to store the user's identifier in the session when they type in their password:
if ($user = try_login($login, $password))
$_SESSION['user'] = $user;
Then, you can access that information on all other pages:
if (isset($_SESSION['user']))
// logged in !
echo user_name($_SESSION['user']);
The data is stored on the server, so there is no risk of tampering (on the other hand, mind your disk usage).
Starting the session lets the current request use $_SESSION. If this is the user's first visit, the array will be empty and a new session cookie will be sent for you.
Closing the session merely prevents the current request from using $_SESSION, but the data stays around for the next requests.
Destroying the session throws away all the data, forever. The sessions are destroyed a certain duration after the last visit (usually around 30 minutes).
I assume you want to know what a PHP session means for you, the programmer.
When you do session_start() you are telling PHP that you want to use the session. This is made available to you as an array called $_SESSION. You can use that like any other array with the difference that the stuff you put in there stays there from one page to another (provided you use session_start() at the beginning of each page).
The actual mechanism may vary depending on configuration (php.ini), but a typical installation can use cookies for the session. Let's assume that your webserver is on linux and you're using cookies. You do the following
session_start();
$_SESSION['name']='Bob';
When PHP sees this it creates a text file with a semi-random name (for example sess_a3tfkd5558kf5rlm44i538fj07), sticks the $_SESSION contents in there as plain text and then sends a cookie to the user with the session id, which can be used to find the session file (for example a3tfkd5558kf5rlm44i538fj07).
The next time the user comes back he hands in the session id in his cookie, PHP goes to the relevant file and loads its contents in $_SESSION.
You'll note that the actual information is kept on the server while the user is only given an id. Kinda like handing in your coat in a club and getting a ticket with a number on it.
PHP's session_start starts OR resumes an HTTP session, which is explained fairly well in this article:
http://en.wikipedia.org/wiki/Session_(computer_science)
The concept of an HTTP "session" isn't specific to PHP, it's used in many (all?) server side HTTP frameworks as one way to allow for some state to be stored/associated across different request/responses (since HTTP is stateless). A unique token (which is often, but not always, stored in a cookie) identifies a particular client, and the server can associate the "session."
Here's some more info about sessions and PHP in particular that may help: http://www.php.net/manual/en/book.session.php
Like it says in the Manual
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
If you start a new session at your login page, the session is initially empty. You can store in it whatever you want, for instance, store the user id once the user has logged in. The session data is destroyed when you close the session.
You might want to read all chapters in the Session Extension Manual Pages and also see
what is session and cookies in php and where it stored
You can compare PHP session with the cookie, but session is the much more secure way of storing information. Cookie store data on user's computer, but session store on the server in a temporary file securely.
I have discussed session and how to use it on one of my blog post - How to start a PHP session, store and accessing Session data?
Below is an example code of storing data in PHP session:
<?php
session_start();
$_SESSION["name"] = "John";
?>
Below is the example of retriving the session data:
<?php
session_start();
echo $_SESSION["name"];
?>
The above code will display the name "John".
Source: How to start a PHP session, store and accessing Session data?

PHP login user logic

I've scrapped all the tutorials that have never worked for one reason or another, and decided to roll out my own registration/login feature on my own, and to my surprise it actually works!
But what I don't get is how the logic behind keeping somebody logged in works! Like, once they've logged in, do I just $_POST their data to whatever other page they visit and once they're on the new page $_REQUEST that post data from the URL and display a message like: "yeah, you're still logged in"?
I'm a bit confused atm, so I hope this question doesn't confuse you too.
Let us have we have pages like login.php after_login_page1.php after_login_page2.php
You can follow these simple steps
Set $_SESSION['id'] = $userid //userid from db in login.php
always have session_start() in the successive pages like after_login_page1.php, after_login_page2.php
Check if(! isset($_SESSION['id'])){
header("Location: login.php");
}
at the logout.php page give $_SESSION['id']=''; and do a session_destroy()
The easiest imo is to use a session.
Basically this is PHP automatically setting a cookie (or adding a piece to the url, depending your configuration) on the user system and automatically loading it on each pageview. You can then add data to the session and as long as the cookie didn't expire (or was deleted) and/or you don't destroy the session, you will have that data at your disposal on each pageview the user does.
Take a look here for a small intro to sessions: http://www.htmlgoodies.com/beyond/php/article.php/3472581/PHP-Tutorial-Sessions.htm
Once they have logged in you generally have two options. Store their details or an authentication token (something that will help the PHP on the server know who is who) in a session or store it in a cookie. Both have their perks, but you will need to choose the one that works for you.
If you store data in a session, the user cannot access what you have stored, only your code can. This is helpful if you want to store say, their id or username. You can trust that it would always be their id and username, because they cannot modify it.
With cookies, the user can access and modify them because they are stored on their local machines. Because of this, you need to be a bit more sneaky and hash the users details, then verify who it is with some server-side logic. It's a little more complex.
A session implementation might look like this:
session_start(); //Make sure you call this at the top of EVERY page
if($passwordsMatch){
$_SESSION['user'] = $_POST['username'];
}
//Now we have access to $_SESSION['user'] on every page.
On another unrelated page:
session_start();
print "Welcome, ".$_SESSION['user'];
Easiest way is to "keep users logged in" is to use PHP sessions. When you run session_start();, PHP sets cookie with SESSION_ID in users browser so it can identify this user. After that, you can set any data in $_SESSION array which will be saved in session between page requests.

Categories