session variable sets on one page and find empty on another page - php

Hello Friends I am new at forum
I have create a simple login page name as index.php with following code:
// I have already starts session by session_start()
$qry="select empCode from relaxo_employee_info where empCode='".$username."' and empPassword='".$password."' and empPost='Executive'";
$result=mysql_query($qry);
if($row=mysql_fetch_array($result))
{
$_SESSION['UID']=$username;
echo $_SESSION['UID']; //prints session data successfully so think session set correctly.
?>
<script>self.location.href='executive/order_place.php';</script>
<?php
}
then at starting of order_place.php I continue the session by session_start() and the following code in it to check valid session
<?php
session_start();
if(isset($_SESSION['UID'])==NULL) // at this point $_SESSION['UID'] find automatically empty. somehow Its blank completely.
{
?>
<script>self.location.href='index.php';</script> //because of session finds empty it redirects to index.php
<?php
}
?>
and strange things are happens I just share with u which helps you understand my problem
1) the same code is run on localhost successfully and does not work on my domain
2) sometimes session works successfully but sometimes not with same code without any changes
So guys please solve my problem and help me to come out from this issue

if(isset($_SESSION['UID'])==NULL)
is kind of a weird approach if you want to compare the $_SESSION variable with NULL. Instead, try
if(is_null($_SESSION['UID']))
and see if the problem still occurs.

Try like this...
<?php
session_start();
if(isset($_SESSION['UID'])) // check whether session is set or not.
{
if($_SESSION['UID'] == NULL) // check session is NULL
{
header('location:index.php'); // redirect to index.php page
}
}
?>

if(isset($_SESSION['UID'])==NULL) is where your problem is. If true == null or false == null it's never going to work.

isset($_SESSION['UID']) tests to see if your variable is set.
in order for you to test it's value try something:
if( isset($_SESSION['UID']) && trim($_SESSION['UID'])!='' )
{
// execute code here
}

Related

Php login script won't wrap around php

I am trying to verify that a user has logged in before showing them the page, using the method below, while the if/else method works when wrapped around plain html, it is failing when there is php involved. I am a novice by the way. What happens is the page simply loads as if the two tags below weren't there...which would be fine had I previously logged in, but I hadn't.
<?php
session_start();
if(isset($_SESSION['user'])) {
?>
HTML/PHP Page goes here.
<?php
} else {
header("Location: cms/admin/loginreadmode.php");
}
?>
Thanks in advance,
You can debug just below your session_start(); by printing your session:
echo '<pre>';
print_r($_SESSION);
die();
If $_SESSION['user'] isn't showing up in your array it isn't be set.
You can do this like this:
session_start();
$_SESSION['user'] = true;
Are you sure that you have add session support in every page?
if (!isset($_SESSION)) {
session_start();
}
This code should be working, so mistake is probably somwhere else I suggest checking if you set $_session["user] after login.
You should also replace your not-working code part with simple
echo "hello";
to chek it.
1) That is not a great method of checking whether a user is logged in, purely checking whether a user sessions exists can end up causing a lot of problems. Storing the ID in the sessions and then checking whether the ID is valid may be a better way,
2) When I copy the code above into a test document it goes straight to the redirect page in the else statement. This is down to the user session not being set, as soon as I set the user session before the code is executed it works fine. I see 'HTML/PHP Page goes here.'.
Setting the user session:
$_SESSION['user'] = 'TestUser';
You can change the code at the top of the page to be
<?php
session_start();
if(!isset($_SESSION['user'])) {
header("Location: cms/admin/loginreadmode.php");
die();
}
?>

Session variable clears itself (PHP)

As a part of a very simple login script, I create a session variable (or at least that is what I think it's called) with the username, and use that as a check of whether or not a user is logged in. The variable is set in the login script, using the following code:
if($count==1) {
session_start();
$_SESSION['ed_user'] = $ed_user;
header("location:main.php");
} else {
echo "Incorrect user or password, please try again.";
}
I know that the first part of this if-statement is run, since I am not presented with the error message. On the page it directs to (main.php) the first lines of code should check if $_SESSION['ed_user'] is set, and return to index.php, if this is not the case. This is done with the code:
if(!$_SESSION['ed_user']){
header("location:index.php");
}
However, it seems to always return me to index.php after login. I have tried to check if the variable exists, using the following line:
<p><?php echo"Current user: ".$_SESSION['ed_user'];?></p>
Which indicates that the variable is empty. What am I doing wrong here?
You need to call
session_start();
On every page.
On your main.php file...
session_start();
if(!isset($_SESSION['ed_user'])){
header("location:index.php");
}
You need to call session_start() to access session variables.

validation user using $_SESSION in PHP

I have a php page that should only be accessed by admin. I am using a php $_SESSION to validate the user. I have this code segment on top of my page which should only be accessed by the admin
if (!isset($_SESSION["uname"])) {
header("Location:../error.html");
exit;
}
if ($_SESSION["uname"] != "admin") {
header("Location:../error.html");
exit;
}
uname variable is getting pass to the page correctly, I am sure about that. But my validating process does not work as I expected. any user can access the page.
Is there anything wrong I have done here.
Did you output anything before doing these checks, even a single empty line is enough to prevent redirecting the page using
hearder()
As others stated I'd make sure you do
session_start();
But I have to assume you have the correct session values as you put
"uname variable is getting pass to the page correctly, I am sure about
that. But my validating process does not work as I expected. any user
can access the page. Is there anything wrong I have done here."
So that leads me to the header error, one way to tell is adding.
ini_set('display_errors', 1);
above your "validation checks" this should show any errors like "unable to send headers output already sent" etc.
Did you call session_start() function at beginning.
It would not work unless we call session_start before using any SESSION data.
http://www.php.net/manual/en/function.session-start.php
You probably forgot to call session_start() at the very beginning of the restricted page as well as the page where $_SESSION['uname'] is being set. Also make sure that $_SESSION['uname'] does not contains the value of 'admin' for other logged in users.
Note: You can debug values of super globals like $_SESSION using the print_r() or var_dump() functions.
See the example given below;
Start your session in your index or the desire page
sesstion_start();
Create this function to validate and redirect automatically
function isValidate($value, $autoRedirect = true){
if(empty($_SESSION['uname']) || $_SESSION['uname'] != $value){
if($autoRedirect){
header("Location:../error.html");
exit;
}else {
return false;
}
}
else {
return true;
}
}
Now simply call this method to validate the session by name. For example;
isValidate("admin");
isValidate("user");

Using isset php function to determine is a key is set in the super global Session array

I have a page called login.php. Login.php processes user information. If the passed user information is found in the database a new session is started. The name and password are then added to the super global sessions array
if(correct_password($name, $password, $users, $users_size)) {
session_start();
$_SESSION["name"] = $name;
$_SESSION["password"] = $password;
header("Location: account.php");
After the validation the user is redirected to account.php. I want to ensure that the user is logged in i.e the "name" index is set before they can access account.php. In order to do this I have the following code
if(!isset($_SESSION["name"])) {
header("Location: index.php");
die;
}
This code is suppose to check to see if the "name" index is set. If it is not set it means the user is not logged in and should therefore be directed back to index.php. However it seems that even if the user logs in the if always is true. I even tested
echo isset($_SESSION["name"]);
die;
to simplify things. When this is done nothing appears on the screen meaning that isset evaluated to false. If I try to print the global sessions array in account.php it works. The data prints and it shows that the name field is populated with the data submited from login.php.
What am I misunderstanding about isset? Or did I mess up somewhere else.
Thanks in advance.
You also need to have session_start(); on top of the page where you check for that value, not only where you set it.
session_start();
if(!isset($_SESSION["name"])) {
header("Location: index.php");
die;
}
This can also work for you:
if( false == isset( $_SESSION ) && false == isset( $_SESSION['name'] )
header("Location: index.php");
die;
}
Storing username and password either in cookie and session is not a good idea
try this will help you out
if (isset($_SESSION['name']) && null != $_SESSION['name']){
//name is exist don't forgot validate username against database
}
Hey to everyone who answered this question thank you. All your answers worked. The reason I thought they were not working is because I forgot to destroy the session after the user logged in. So even after log out the name index was still set.

PHP Session not Saving

I have this written at the very first line on every page of my website.
include("restd.php");
and restd.php contains the following lines :
#session_start();
if(isset($_SESSION['id']))
{
}
else
{
header("location:index.php");
}
The problem i'm facing is that when ever i click or do something on my website. it logs me out and takes me to index.php.
im sure its something to do with the session. ive tried every single thing to avoid this problem but i ahve used restd.php because i dont want anyone to copy the url of someone and paste and get into the website.
anyone who is logged in only can view other's pages. if they arent logged in then they'll be redirected to index.php
EDIT : and guys a confusing thing is that all this is working fine on my testing server which is easyPHP-5.3.8.0 but this problem is coming up when i upload all the files to my server.
Your session directory (probably /tmp/) is not writable.
Check with session_save_path() if it is writable.
if (!is_writable(session_save_path())) {
echo 'Session path "'.session_save_path().'" is not writable for PHP!';
}
Do you actually set $_SESSION['id'] on a page...
What you are trying to do here is:
Start a session and load the $_SESSION from the session handler
Check if $_SESSION contains key 'id'
Redirect to index.php if $_SESSION['id'] is not set
Do you actually do this in index.php?
session_start();
$_SESSION['id'] = something;
you need declare $_SESSION['id'] :
file1.php
session_start();
$_SESSION['id'] = '123'
file2.php
include 'file1.php'
if(isset($_SESSION['id']))
{
}
else
{
header("location:index.php");
}
In my case I forgot that I had the PHP flag session.cookie_secure set to on, while the development environment was not TLS-secured.
More information about Session/Cookie parameters.
I know this is an old thread, but the following helped me with the same problem after hours of despair. Found on: http://php.net/manual/de/function.session-save-path.php
I made a folder next to the public html folder and placed these lines at the very first point in index.php
Location of session folder:
/domains/account/session
location of index.php
/domains/account/public_html/index.php
What I placed in index.php at line 0:
<?php
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
?>
Hopefully this will save you time.
Check maybe your session path does not exist
so you can save PHP session path using:
ini_set(' session.save_path','SOME WRITABLE PATH');
Couple things:
your include file doesn't have the <?php ?> tags, so the content will not be evaluated as PHP
Session_start must be called before you start outputting anything. Is that the case?
You still don't even answer where you SET $_SESSION['id']. $pid = $_SESSION['id'] does not set the session variable. session_start() comes before ANYTHING session related, it's not shown before your include.
I had the same problem and found a work-around for it. If anybody can explain why the session is not read even when the cookie is there, please let me know.
<?php
// logged.php
// The PHP session system will figure out whether to use cookies or URLs to pass the SID
if(!isset($_COOKIE['PHPSESSID']) && !isset($_GET['PHPSESSID']) && authenticationRoutine(/* Returns true if succesfully authenticated */) ) {
session_id(uniqid("User--"));
session_start();
$_SESSION['id']=session_id();
}
?>
<?php
// Insecure restd.php (The user can forge a stolen SID cookie or URL GET request, but that is inherent with PHP sessions)
if(!isset($_COOKIE['PHPSESSID']) && !isset($_GET['PHPSESSID']) {header('Location: index.php')}
?>
.
[EDIT]
Even though the cookie was there and I prevented starting a new session, the session had not been read and started, so no session variables were available. In this case I check if the session has been started first (not using session_status() because it doesn't exist in PHP 3.5, which for some reason is the most widespread among hosts). If no session has been started within PHP, I check if it had been started before by testing the cookies and GET variables. If a session ID was found, the script resumes the session with that ID. If no ID is available, the user gets redirected to the index.
<?php
// restd.php
if(empty(session_id())) {
if(isset($_COOKIE['PHPSESSID']) && !empty($_COOKIE['PHPSESSID'])) {session_id($_COOKIE['PHPSESSID']);}
elseif(isset($_GET['PHPSESSID']) && !empty($_GET['PHPSESSID'])) {session_id($_GET['PHPSESSID']);}
else {header('Location: index.php'); exit(0);}
session_start();
}

Categories