PHP Session won't keep array variables - php

I have an Index page with login form, a verification page called Login and content.
Index is fairly simple: if logged in, redirect to Content, otherwise display login form and POST to Login page
index.php:
<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd'])){
header('Location: content.php');
} else {
?>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> PHP Login </title>
</head>
<body>
<center>
<form method="POST" action="login.php">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="usr"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pswd"></td>
</tr>
<tr>
<td><input type="submit" name="login" value="Login"></td>
<td><input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
<?php } ?>
Then we have Login verification: compare the POST vars with coded variables, if all is good, set Session variables and redirect to content.
login.php:
<?php
session_start();
if($_POST['usr']=='user' && $_POST['pswd']=='password'){
$_SESSION['usr'] = 'user';
$_SESSION['pswd'] = 'password';
header('Location: content.php');
} else {
echo "post: ";
print_r ($_POST);
//header('Location: index.php');
}
?>
Then we have the Content page, check that the Session is set and display content, otherwise PRINT_R
content.php:
<?php
session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
} else {
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>
The process works, up to the Content page. I keep getting a blank SESSION array, and when I try going to Index, it pretends I never logged in. what am I missing?!
Edit: in The code above, content.php is trying to check if the session is set. If it is NOT set it will show me a blank array (for debugging purposes, but normally I want it to go back to index, since the user is not properly connected),
if it IS set, it will echo "you are logged in". It is also including a page called 'logoff.html' as that page has a button to destroy the session.
Even without the IF statement, simply running a print_r ($_SESSION); returns a blank array. This means there is no problem in the IF statement, but something that happens before it.
Solution: I didn't know about this before, but some hosting sites require some PHP set up, before they can store PHP sessions. I went to the knowledge base of my hosting service and searched for "session", and found an explanation on how to set up the php.ini file to save my sessions in the correct path.

Make sure sessions are configured properly. For example, is the session save handler set correctly? If using files, does it have permission to access the specified folder? If memcache, is that set up properly?
This would be the main reason for session variables to not be saved.

change this
<?php
session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
} else {
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>
i think in your code when session not set then it will print so change it with
<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd']))
{
// session is set
// header('Location: index.php');
echo "session: ";
print_r ($_SESSION);
}
else
{
/// session is not set
include 'logoff.html';
?>
You are logged in!!!
<?php } ?>

Related

Login implementation in PHP

Suppose, I have two pages login.php and index.php. In index.php I have two buttons Login and register.After clicking the buttons ,the user is directed to login.php.
If I want to implement a login functionality using PHP, something related to facebook such that the if a user has logged in before, then it bypasses the index page once the username and password are set and directly lands into the login page. Is $_SESSION a proper way of doing it.
For example:
<?php
session_start();
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ayu</title>
</head>
<body>
<?php if (isset($_SESSION["user"])) { ?>
<h1>Hi <?php echo $_SESSION["user"]; ?></h1>
Logout
<?php } else { ?>
<h1>Login</h1>
<?php echo (isset($_GET["error"])) ? '<p>You idiot!</p>' : ""; ?>
<form action="new-user.php" method="post">
<div>
<label>
<strong>Username</strong>
<input type="text" name="username" />
</label>
</div>
<div>
<label>
<strong>Password</strong>
<input type="password" name="password" />
</label>
</div>
<input type="submit" value="Log In" />
</form>
<?php } ?>
</body>
</html>
In the login functionality, I am setting the $_SESSION values
<?php
session_start();
if (count($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
unset($_SESSION["user"]);
header("Location: ./?error");
}
?>
Yes using and creating ($_SESSION) session is the correct way to check logged in users.
$_SESSION is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a script.
There is no need to do global $variable; to access it within functions
or methods.
Check for session on very top of a page, if found redirect to index else to login page.
if(!isset($_SESSION['login_user'])){
header("location:login.php");
}
Refer this simple login example using my sql in php Here
EDIT
As requested by OP - if you want to hide a particular section in index.php page based on session value or say if a user is logged in or not that can be done like:
<?php
if(isset($_SESSION['login_user'])){
?>
<form>
<input type="submit" name="whatever" />
<!-- Other Fields -->
</form>
<?php
}
?>
Html Form in the above code will only be shown if a user is logged in else it will be hidden.
Yes, Session is best way to implement the same. You can use the below php code to solve your problem
<?php
session_start();
if (!empty($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
if($_SESSION["user"]!=''){
unset($_SESSION["user"]);
}
header("Location: ./?error");
}else{
/* Write code for form */
}
?>

Checking the session value that is available or not

I wrote the following login.php file.
<?php
session_start();
//Check everything and if everything is correct and the username and password is correct and available
echo "Successfully";
$_SESSION['login_user'] = $username;
// and etc
?>
Now if the username is session as the the result $_SESSION['login_user'] value is session also.
and then I create check-session.html file and it is as follows:
<html>
<body>
<form method = "POST" action = "check.php">
<input type = "submit" value = "check-session">
</form>
</body>
</html>
And then the check.php file is as follows:
<?php
if(isset($_SESSION['login_user'])) {
echo "session is available";}
else { echo "session is not available"; }
?>
But the problem is when the login operation is successfully and now I want to know that the session is created really or not, after clicking the check-session button in the check-session.html page, I see the result from server as the follows:
session is not available
Also for more information I use wamp server.
Put session_start(); in the start of every page that's using sessions or is related to them in any way.
In the start of your check.php file
<?php
session_start();
if(isset($_SESSION['login_user'])) {
echo "session is available";}
else { echo "session is not available"; }
?>
You can solve this problem by making a separate file for setting session and include that file on the starting of each logged in page.
this is c.php for checking session...
<?php
include 'b.php';
if(isset($_POST['check_session']))
{
if(isset($_SESSION['login_user']))
echo "session is available";
else
echo "session is not available";
}
?>
<form method = "POST" action = "c.php">
<input type = "submit" name="check_session" value = "check-session">
</form>
a.php for login
<?php
if(isset($_POST['login']))
{
header("Location: c.php");
}
?>
<html>
<body>
<form method = "POST" action = "a.php">
<input type="submit" name="login" value="Login">
</form>
</body>
</html>
and also make b.php simply for setting session using session_start()

How to prevent user from bypassing php authentication

We call it html1 for simplicity.
When a user goes to html1, there's a login2.php login page to enable access to client.php which is the hidden page.
It then goes to checklogin.php...if the password and user name matches...it then goes to the hidden client.php page...if not..it goes back to homepage.
The user has to login to be able to view the contents of hidden client.php page.
However the user can access client.php by typing in ..../client.php on the address bar...therefore bypassing the auth page and rendering it useless. I can just type servername/client.php...and it still shows me the contents of client.php...but I want client.php...to be private!
How do I prevent this from happening?
thanks.
first login page...
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<table>
<form method="post" action="checklogin2.php">
<div id="name">User Id: <input type="text" name="****"></div>
<div id="password">Password: <input type="password" name="*******"></div>
<div class="button"><input type="submit" value="Login"></div>
</form>
</table>
</body>
</html>
then it goes to....
checklogin2.php
<?php
$*** = $_POST['****'];
$***** = $_POST['***'];
if($uid == '****' and $***** == '*****')
{
session_start();
$_SESSION['sid']=session_id();
header("location:securepage.php");
}
else
{
header("location:index.html");
}
?>
Then it goes to...
securepage.php
<?php
session_start();
if($_SESSION['sid']==session_id())
{
header("location:client.php");
echo "<a href='logout.php'>Logout</a>";
}
else
{
header("location:login.php");
}
?>
In the beginning of your every page you have to check if user is authorized.
On checklogin.php if user entered correct login and password, just set something like
$_SESSION['authorized'] = TRUE;
...and on other pages just check if user is authorized:
if (isset($_SESSION['authorized']) && $_SESSION['authorized'] === TRUE) {
// Alright, let's show all the hidden functionality!
echo "Psst! Hey! Wanna buy some weed?";
} else {
// User is not authorized!
header('Location: login.php');
exit();
}
Note that you don't have to mess with cookies, session IDs etc. - just add session_start() before everything and freely use $_SESSION var.
This is the main pro of sessions (and $_SESSION variable in particular): you can remember some data among different pages on same website.
All pages has to check if the user is authed. I would recommend using objects, and always inherit a class that checks this for you. It's not fun to have the same code everywhere, doing the same thing.
if($_SERVER["PHP_SELF"] == '/yourpagefolder/yourpage.php' && !isset($_SESSION['login_user'])){
header('location: login.php');
}

Redirect user who already logged in PHP

I want to redirect logged in users to home page(member-index.php), I have used the following code to accomplish this, but this doesn't work.
<?php
function redirect() {
header('location:member-index.php');
}
?>
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
if(isset($_SESSION['SESS_FIRST_NAME'])){
redirect();
}
?>
<form id="loginForm" name="loginForm" method="post" action="login-exec.php">
<input name="email" type="text" class="textfield" id="login" placeholder="username" />
<input name="password" type="password" class="textfield" id="password" placeholder="password"/>
<input type="submit" name="Submit" value="LOGIN" />
</form>
</body>
</html>
session variables at (login-exec.php)
$qry="SELECT * FROM members WHERE email='$login' AND passwd='".md5($_POST['password'])."'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) == 1) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
$_SESSION['SESS_FIRST_NAME'] = $member['fullname'];
The other pages with sessions, works perfectly fine, I could get and print the logged in user on another page, But couldn't get session work in login-form page..
Any help would be appreciated!
I'm surprised error reporting error_reporting(E_ALL); ini_set('display_errors', 1); didn't throw you a warning about outputting before header.
I.e.:
Warning: session_start(): Cannot send session cache limiter - headers already sent...
Move your <?php session_start(); ?> at the top of your code.
<?php session_start(); ?>
<?php
function redirect() {
header('location:member-index.php');
exit;
}
?>
and add exit; after your header to avoid further execution.
Also make sure all your files do not contain a byte order mark (BOM) and that there is no output before header. A space, HTML, nothing, not even a cookie, or anything else that would account as output.
All files should be saved in your code editor, as UTF-8 WITHOUT BOM.
I added this code at top of my login form, and it worked!
<?php
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
header("location: member-index.php");
exit();
}
?>
Do this at the top of your file instead
<?php
session_start();
if(isset($_SESSION['SESS_FIRST_NAME'])){
header("location: member-index.php");
}
?>
<html>....the rest of your html
You can look at the php docs for header to see why you are having an issue. The paragraph that starts with 'Remember' specifically

php redirect loop

I'm following a php video tutorial (it's not online sorry) from Lynda.com and used the following code, but I got the following error
Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.
could this be a problem with my code. i.e. the fact that the code has two redirect_to in the first 10 or 15 lines, or is it talking about something else?
<?php require_once("../../includes/initialize.php"); ?>
<? if(!$session->is_logged_in()){
redirect_to("login.php"); } ?>
<?php
$logfile = SITE_ROOT.DS.'logs'.DS.'log.txt';
if($_GET['clear'] == 'true') {
file_put_contents($logfile, '');
//add the first log entry
log_action('Logs Cleared', "by User ID {$session->user_id}");
//redirect to this same page so that the URL won't
//have "clear=true" anymore
redirect_to('logfile.php');
}
?>
<?php include_layout_templates('admin_header.php');?>
« Back<br/>
<br/>
<h2>Log File</h2>
<p>Clear log file</p>
<?php
if (file_exists($logfile) && is_readable($logfile) &&
$handle = fopen($logfile, 'r')) {//read
echo "<ul class=\"logentries\">";
while(!feof($handle)) {
$entry = fgets($handle);
if(trim($entry) != "") {
echo "<li>{$entry}</li>";
}
}
echo "</ul>";
fclose($handle);
} else {
echo "Could not read from {$logfile}.";
}
?>
//Remember to give your form's submit tag a name="submit" attribute
if (isset($_POST['submit'])) {//Form has been submitted.
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//Check database to see if username/password exist
$found_user = User::authenticate($username, $password);
if ($found_user) {
$session->login($found_user);
log_action('Login', "{$found_user->username} loggined in.");
redirect_to("index.php");
} else {
//username/password combo was not found in the database
$message = "Username/password combination incorrect.";
}
} else {//Form has not been submitted.
$username = "";
$password = "";
}
?>
<?php include_layout_template('admin_header.php'); ?>
<h2>Staff Login</h2>
<?php echo output_message($message); ?>
<form action="login.php" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input type="text" name="username" maxlength="30" value="<?php
echo htmlentities($username); ?>" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" maxlength="30" value="<?php
echo htmlentities($password); ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="login" />
</td>
</tr>
</table>
</form>
<?php include_layout_template('admin_footer.php'); ?>
You have an endless loop of redirecting.
"login.php" redirects to "login.php" if you're not logged in. "login.php" redirects to "login.php" if you're not logged in. "login.php" redirects to "login.php" if you're not logged in. "login.php" redirects to "login.php" if you're not logged in. etc.
You should probably make the redirect happen only when the current page is not "login.php"; i.e. remove that logic from this page.
<? if(!$session->is_logged_in()){
redirect_to("login.php"); } ?>
Therein lies your problem I think. You're checking on your login page, to see if someone is logged in or not. If they're not, you'll redirect to your login page, starting a new request, and it'll perform the check again.
Login page asks, is the user logged in? No! Redirect them to the login page
Login page asks, Is the user logged in? No! Redirect them to the login page
Login page asks, Is the user logged in? No! Redirect them to the login page
ad-infinitum
People shouldn't have to be logged in to use the login page, so remove the check to see if someone's logged in before they use said page.
Check if your login page redirects if you're not logged in.
Make sure there is no output before you redirect
Make sure you exit after you have done the redirect. In your code example you will end up with some whitespace before you call the redirect function as a result of that empty line between your require and if check. If I was you, I wouldn't jump in and out of php as much as you do when there is no need to. All the way down to your first link, I see only php, but yet you have 3 <?php and one <? (which is also a bad idea. I'd stick with using only <?php).

Categories