file1.php
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['pass'];
$_SESSION["email"] = $email;
$_SESSION["pass"] = $password;
//echo $_SESSION["email"];
header("location:file2.php");
?>
file2.php
<?php
session_start();
$email = $_SESSION["email"];
echo $_SESSION["email"];
?>
I want to display the email the user logged in with. The error says "Undefined index email" at the second line in file2.php. Everywhere I've looked says to put session_start() at the top of every file, and to create the session in file1.php, then access it via line 2 of file2.php.
The only thing I can think that is making this not work is that this is not using HTML. I have an android app where the user enters their email and password. My app hands off the credentials to file1.php. I know it hands off correctly because if I uncomment line 6 of file1.php, the echo response works correctly. It for some reason, will not echo in file2.php.
The reason I need this to work is because I want to be able to use the email session variable in any php file (for logging out, display info, etc), and if I can't get it working in this simple example I will have no where to go.
There are several similar questions on the site (e.g. this). They suggest to use the isset method to ensure your session variable is available.
In your case, it could be added before the header call in file1.php, so
if (isset($_SESSION['email'])) {
header("location:file2.php");
}
The sessions in PHP by default are cookie based, your APP don't use cookies, you need to implement another method session like a self generate token against a database, maybe use a REST framework.
Another solution can be emulate the cookies with headers but I don't know if that is possible in Android
Session works by cookie support, does your android app's request class supports this ?
It seems your client sends request to file1.php then server responses with session id in cookie, then your application redirects to file2.php. In normal way browsers sends previous session id to tell server which session belongs itself. Please check that you are sending this cookie while requesting file2.php
Related
I am beginner in web development and i am creating my first project. I am using XAMPP, for my php files. I have basically created app.php, sigin.php. So in order to prevent user from directly access my app.php i am using session variables in php. Hence i added the following PHP code just before my app.php.
<?php
session_start();
if(!isset($_SESSION['loginstatus'])) {
header('location:./login.php');
die();
}
?>
And i am setting my session variables in my signin.php like the following:
if($user['username'] == $username && $user['password'] == $password) {
$_SESSION['username'] = $username;
$_SESSION['loginstatus'] = 'success';
echo "success!";
header('location:../app.php');
}
Now i tried accessing my app.php without login, i am still able to access app.php. To check where is the issue i cleared my browser history and cookies, then i tried accessing app.php, then surprisingly it worked i was actually redirected to login page, but as soon as i do first succesfull login, and logout and again try to access app.php without login, i was again able to access app.php without login.
Now for some reason i feel that my browser is saving session variables too, So to check that i wrote a small piece of code and pasted in my app.php:
<?php
var_dump($_SESSION['loginstatus']);
?>
after first successful login my $_SESSION['loginstatus'] is always set to successful. Now as i said i am a beginner, what i learnt is session are stored in server side. So i am totally confused regarding this.
There is a cookie in your webbrowser "phpsessid" wich stores the id of the Session on the server.
In normal cases you destroy the Session, at logout.
session_unset(); to unset all session variables
session_destroy(); destroys the session
The Session will timeout after time X. You can change it, described here -> Link
So if you have a cookie in your Browser with a valid id of a not-timeouted Session you will always be able to log in.
So basically, going to browser setting > privacy and security > more > pre-load pages for faster browsing and searching
I just disabled this default setting from chrome, and it started working as expected.
i'm having a bit of a problem. I'm trying to set up a simple webpage with only three .php pages. I want a session variable $_SESSION['userID'] to be set when a user is logged in and I want the index page to show extra info if someone is logged in.
On index.php I want to show some info, if a user is logged in I want to show some extra info.
login.php - simple log in form.
login_exe.php - takes care of database connection and verification.
So this was my idea:
On index.php, check if session is started, if not: start.
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
later on, check if $_SESSION['userID'] contains a value, if so: print a string
if($_SESSION['userID'] != null){
echo "User logged in";
}
On login_exe.php i've almost the same code:
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
in verification function:
$_SESSION['userID'] = $data['userID'];
header("Location: index.php");
The problem is that a new session is started on every page. How can I fix this and only start the session once? Thanks in advance
You should just put session_start() on top of documents that using sessions. Say, if you have 5 .php files that using sessions, then put 5 times the session_start() on top of them.
This is because session_start() sends headers and headers must be sent before any output (for example, any echo or whitespace).
Then, you should use something like isset($_SESSION["foo"]) and not just the entire $_SESSION array, where foo is something you set previously.
If you dont want sessions at all or need to reset the entire array, just call session_destroy() which effectively destroy the current session. Use unset($_SESSION["foo"]) when you want to get rid of a key.
Finally, you might get weird cases where you cannot read session key you write at. In these cases check what is the path of sessions and if they're writeable, or change their path:
$path = session_save_path(); // what is the path
is_writable($path); // can i write to it?
session_save_path("my/new/path"); // change the darn path;
// put -even- before session_start()!
:)
glad i help
I think the PHP manuals are really good compared to ...ahm, so just read about session_start(). It says:
session_start() creates a session or resumes the current one (...)
so all you need is session_start() very early in your code. This must be executed on every request (maybe as include).
Your code checking the userId looks fine, one important hint here: you should know exactly what isset(), empty() and the like mean in PHP, so always have the comparision of comparison at hand.
You should not ask new answers (edit: questions) in comments. Be as systematic here as you are in coding.
How to end a session:
This gives room for discussion, because there is the session cookie, which is client side, and the session data, which is server side.
I recommend:
$_SESSION = null;
Reason: this will clear all login and other associated data immediately. It leaves the cookie intact, which is normally of no concern, since all associated data is gone.
i have this code:
$username = $_POST["username"];
$password = $_POST["password"];
if(mysql_num_rows($result80)>0)
{
$row80 = mysql_fetch_assoc($result80);
$_SESSION["loginmng"] = 1;
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
$fname = $row80["fname"];
$lname = $row80["lname"];
$userid = $row80["id"];
}
and every thing is ok because i tryed to echo the session and its work in the same page (index.php)
now i have this check:
if(($_SESSION["loginmng"]!=1)||(!isset($_SESSION["username"]))||(!isset($_SESSION["password"])))
{
header("Location: index.php");
}
when i put this into new folder:
newfolder/index.php
the check is not working right,when i have logged in , and the session is set....when i am tring to echo $_SESSION["loginmng"] and the other sessions,,its values is empty like no session setted and the header is got run ...and go to index...i have put session_start(); in the first php line too
i tryed too:
if($_SESSION["loginmng"]!=1)
{
header("Location: ../index.php");
}
and the same thing...like no session set, what may be the problem
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag.
Maybe you forgot to add session_start(); on top of the file.
To make session start on each page you need to start the session on each page.
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.
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.
I am fairly new to PHP. What is the best way to control access to a class throughout a PHP application and where is the best place to store these classes that will need to be accessed throughout the entire application? Example; I have a user class that is created on during the login process, but each time the page post it appears that the object is reinitialized.
I have tried to set property IsLoggedIn and then check that variable each time before creating the object as new again, but this doesn't seem work. I have also tried to use the isSet function in PHP to see if the class variable already exists
You're right, the state of your application is not carried over from request to request.
Contrarily to desktop applications, web applications won't stay initialized because to the server, every time it can be a another visitor, wanting something completely different. You know who's using the desktop application, but you don't necessarily know who's requesting the page. Imagine 10 users doing different thing simultaneously on your web application? You wouldn't keep the whole application running necessarily for each of those visitors. Imagine with 10,000 visitors...
There are ways to keep some data from request to request though. The application will be reinitialized each time, yes, but you can then reload the state of what you were doing. It always revolve around around the same general methods:
Cookies; Cookies are a small file that is kept on the client side and which content will be available on each request to you. In PHP, this is available using $_COOKIE variable. In all cases, you could serialize your classes instances and reload them afterwards. The problem is, you wouldn't want to put sensitive data there as any(malicious)body can see and modify it.
POST or GET; In each request, you pass a state in the $_GET request (the URL such as http://localhost/myscript.php?iamatstep=4. Or via a $_POST such as using a hidden input field in a form. This data could be encrypted and make sense only to you, but still, you are putting sensitive data back to the client and anybody could fiddle with it.
Database, Disk; Or anything else on the server. Again, you serialize your data in a file for example at the end of a request ready to be used again for the next request. The main advantage is that it stays on your server. The downside is that at this point, you don't know which data to extract back for which request as there might be multiple users on your application at the same time...
And this is where the notion of $_SESSION comes into play. It's just a packaged way of using all of this at the same time. It's not magical as often it's perceived by beginners. When you use a session, the data put into the $_SESSION is stored somewhere on the server (normally a file in a temporary directory although it can be changed to something else like a database) and a unique ID is attributed to this session and passed in a cookie that will follow the visitor from request to request. So the only thing on the client's side is a big number in the cookie. On the next request, the browser tells PHP on the server that it's session number 12345, loads the corresponding file if it exists and then the data is available to you again. If cookies are not enabled, it could be passed in a GET or POST, although it's often better not to go there (see session.use_trans_sid's note).
It often looks like that on each of your pages you need authentication.
<?php
// verify if we have a current session
if (isset($_SESSION['login'])) {
// get data in current session
$username = $_SESSION['login']['username'];
$isLoggedIn = $_SESSION['login']['isLoggedIn'];
} else {
$username = '';
$isLoggedIn = false;
}
// take care of the unauthorized users
if (!$isLoggedIn) {
// maybe a redirection here...
}
// do the things a logged in users has the permission to do
And to set the session, it'll probably look like that:
<?php
// handle the form post of your login page for example
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// verify the username and password against a database
if ($everythingIsOkay) {
// we can consider this user logged in and create a session
$_SESSION['login']['username'] = $username;
$_SESSION['login']['isLoggedIn'] = true;
// and now maybe redirect the user to the correct page
}
}
// raise an error about an invalid login
And finally, maybe a logout.php page that would do something like that:
<?php
unset($_SESSION['login']);
// redirect the user to the login page
This kind of data is going to have to be stored in a session, the only thing that is carried from page to page is Session data (sessions/cookies/...) so your class initialization is not carried over.
You can add information like the users username to the session with:
$username //username from db
$name //name from db
$_SESSION['username'] = $username;
$_SESSION['name'] = $name;
or if you just want to have easy access to all the information about the user you can do:
$_SESSION['user'] = mysql_fetch_assoc($result); //where $result is the response from the db to your login query
after you do this $_SESSION['user'] will be an array with all the details you selected from the database.