php script don't refreshes in browser - php

I have the following php code:
<?php session_start();
....
$result=$db->query($query);
$row=$result->fetch_assoc();
$_SESSION['id']=$row['id'];
header('Location: http://www.blabla.com/successLoginPage.php');
php code on: successLoginPage.php
<?php session_start();
echo $_SESSION['id'];
Here is problem. When i do all things, i see nothing in successLoginPage.php, after approximately 10 minutes i refresh the page and see correct variable. I tried to clear the cache, ctrl+f5, shutdown the browser and computer, but nothing changes - still need to wait 10 minutes. This problem is exists in chrome and ie8.
How can i solve this problem?
Thanks in advance.
*Edit 1:
I add logout.php page with the following code: session_start();session_destroy();unset($_SESSION); When i log in successfully and receive the proper echo, i push logout link and then log in using another account - all great.
1st question - can i log in via 1st account for the 1st time and via 2nd account for the 2nd time? Is this ok?
2nd question - when i failed to log in, there again i see freeze. If i try to log in with proper account after this, i will see old information about fail login. What i need to do?

It may be somewhat obvious but... is $row['id'] actually a number/string, not NULL? :p You could try
var_dump($_SESSION['id']);
instead of
echo $_SESSION['id'];

Have you tried
session_write_close();
after setting your session variable?

First of all, you are not showing the entire code and in this case it is very important.
<?php session_start();
....
$result=$db->query($query);
$row=$result->fetch_assoc();
$_SESSION['id']=$row['id'];
header('Location: http://www.blabla.com/successLoginPage.php');
// Mystery ???
When you are calling header('Location: xxx'), it doesn't stop the script, so everything after your header is executed.
You could add the function die to prevent any other code to execute after the redirection.
<?php session_start();
....
$result=$db->query($query);
$row=$result->fetch_assoc();
$_SESSION['id']=$row['id'];
header('Location: http://www.blabla.com/successLoginPage.php');
die(); // No more code executed after this //

Solved the problem.
I deleted all login files and rewrite it from scratch and all seems to work now. Don't know where bug was.

Related

Session is set, but not working after going to another page just at first time [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a login.php and a few pages for userarea. After login, it works and it goes to user.php and I use some $_SESSION variables to show the name and username. It works, also my $_SESSION variables are set at first time too and it will stay on the user.php.
But when I go to another page of userarea, it returned me to login.php, but if I login again, then it is OK and no problem and I can go to different pages without problem. Why?
I tried these things:
I changed $_SESSION['log_in'] from boolean to string or use another session like $_SESSION['username'] for !isset($_SESSION['username']) (top of each pages). This username session will be show in the user.php but after that I go to another page doesn't work.
I have session_start() top of every page.
<?php
session_start();
if(!isset($_SESSION['log_in'])){
header("Location: login.php");
}
// I have this code top of every page.
?>
This is login.php:
<?php
session_start();
if(isset($_SESSION['log_in'])){
header("Location:user.php");
}
if( password_verify($_POST['password'],$user['password'])) {
$_SESSION['name'] = $user['name'];
$_SESSION['email'] = $user['email'];
$_SESSION['username'] = $user['username'];
//to know is user login or not
$_SESSION['log_in'] = TRUE;
echo "<meta http-equiv=Refresh content=2;url=user.php>";
//if I user header("Location: user.php") it doesn't go to user, but with meta it goes to user.php
?>
This is user.php:
<?php
session_start();
if(!isset($_SESSION['log_in'])){
header("Location: login.php");
}
// this is top of my user.php and top of another pages too.
?>
This is logout:
<?php
session_start();
if(isset($_SESSION['log_in'])) {
session_unset();
session_destroy();
header('location: login.php');
} else {
session_unset();
session_destroy();
header('location: http://www.mywebsite.com');
}
// this is my logout.php
?>
I don't get any error, and I have another session part too for admins, but I wrote totally different session, for example $_SESSION['admin_log_in'] it has just one page and it works good.
(Posted on behalf of the question author).
I should open my website "www.".
I just spotted the problem - this is an enormously tricky issue to debug.
This is one of your code snippets, with an extra line of code - the exit:
<?php
session_start();
if(!isset($_SESSION['log_in'])){
header("Location: login.php");
exit();
}
// this is top of my user.php and top of another pages too.
?>
So, what is happening here?
The header() call queues up an HTTP header to be sent to the browser - it may be sent immediately or it may be sent once HTML input is emitted by your program (since you are not explicitly flushing this information, we don't know exactly when it will be sent).
The important thing to note is that when you call header(), your PHP script carries on executing. You have not told it to stop. So, it will do a bunch of things you did not expect.
At some point, the browser will receive the Location header, and will terminate the connection, and in most web server configurations, PHP will stop executing, since your web server is in control of the PHP interpreter. Thus, you have a race condition between the browser terminating the connection and your script getting to the end; what gets executed in the script will probably vary from one run to another. This will depend partly on network latency - a slower network connection will allow the script to get further before it is terminated.
Ensuring that you stop the script immediately after the header call, or at least exiting deliberately and gracefully, will resolve this.

Session not working for first time, from second time it works

I don't know what is the problem. When I do login for first time after deleting all history and cookies and cache, it doesn't set session to redirected page. But when I do login for second time, session is set to redirected page. Here id the code of First & second page.
First Page
<?php
session_start();
include('includes/connection.php');
$email=$_POST['email'];
$password=$_POST['password'];
$data=mysqli_query($GLOBALS["___mysqli_ston"], "select * from user_registration where email='$email' and password='$password' ");
$data1=mysqli_num_rows($data);
$val=mysqli_fetch_array($data);
if($data1>0)
{
$_SESSION['user_id']=$val['user_id'];
echo "<script>window.location.href='index.php'</script>";
}
else
{
echo "<script>window.location.href='login.php'</script>";
}
?>
Second Page
<?php
session_start();
$val=$_SESSION['user_id'];
echo $val;
?>
session_start(); should be at the very top of both scripts!
Session variables are saved on server and assigned a unique code that are passed to browser in cookies.
Because the cookies are set by the headers they need to be sent before anything else!
Even a whitespace at the top of your script may cause session cookie to be not properly set on browser side.
So always start the both scripts like this:
<?php
session_start();
// Rest of the code....
It looks like they are on top on your question but I think you edited question later to put there.
That's the only reason sessions are not working the first time and they are working on second time.
instead of the echo use
header("Location: index.php");
EDIT
alsosession_start should be declared at the top of the first page because you cant set a session that doesn't exist in the context if you were running it in a console environment you would receive the following error
"$_SESSION['user_id'] does not exist in the current context"
same happening here. is php 5.6 is super strange problem. on some pages work normaly and on one dont. First request is like dont get recognized.. :)
for example: set
#when page load set:
$_SESSION['a']=0;
#then with JS requests increase $_SESSION['a']+=1; and this start working on third request...

PHP logout system not working. (session_destroy on MAMP)

I recently transferred my website from XAMPP to MAMP. The problem is that my logout system is no longer working. The logout widget:
Log Out
My logout page itself:
<?php
session_start()
session_destroy()
header('Location:login.php');
?>
The weird thing is that when I change something to logout.php, such as making it a simple echo statement:
<?php
echo 'test';
//session_start()
//session_destroy()
//header('Location:login.php');
?>
I still do not see 'test' in my browser; I just stay at index.php even though I have commented out the header in the page. I am 100% the link path is fine.
Wether or not I alter the logout.php file or not, I can see that the server has NOT deleted the session file in tmp/php. This is weird because I have allowed in MAC OS X everyone acces to read and write to this tmp/php folder.
OS: MAC OS X
SERVER: Apache within MAMP
PHP:5.4.4
BROWSERS: Problem occurs in both Google Chrome & Safari
(This is my maiden voyage with posting a question on stackoverflow, if you tips to improve my questioning, please let me know)
Try using this instead:
<?
session_start();
$_SESSION = array();
header("Location: index.php");
?>
I just clear $_SESSION, and it always works for me
If calling logout.php when it containts the code below does not print test then there is something else wrong and it has nothing to do with the sessions.
<?php
echo 'test';
//session_start()
//session_destroy()
//header('Location:login.php');
?>
You mention that it still shows the index.php, which makes me thing you have a rewrite rule in your .htaccess file which redirects the call from logout.php to the index. Check your htaccess file for any rules.
You can find information about htaccess on MAMP here
These are the essential parts of a logout, assuming that your scripts are using PHP sessions. Note that your logout script causes a parse error because it is missing semicolons at the end of statements. Maybe just a typo.
<?php // RAY_EE_logout.php
session_start();
// CLEAR THE INFORMATION FROM THE $_SESSION ARRAY
$_SESSION = array();
// IF THE SESSION IS KEPT IN COOKIE, FORCE SESSION COOKIE TO EXPIRE
if (isset($_COOKIE[session_name()]))
{
$cookie_expires = time() - date('Z') - 3600;
setcookie(session_name(), '', $cookie_expires, '/');
}
// TELL PHP TO ELIMINATE THE SESSION
session_destroy();
// REDIRECT TO THE HOME PAGE
header("Location: /");
exit;
HTH, ~Ray
Try using output buffer.
<?php
ob_start();
session_start();
session_destroy();
header('Location:login.php');
?>
In my case it had to do with the php code block not being defined correctly. I had <? ?> instead of <?php ?>
Hope this helps someone.
#tom.e.degroot: Last time I checked, "it didnt work" was not an error message. You'll need to describe the symptoms a little more. Please follow the guidance here: http://SSCCE.org and give us something we can install and test on our own servers. Thanks, ~Ray

Login-protected page is not requiring login to access

I have written this script to prevent users that haven't logged in from viewing certain pages. I have tried to get it working but no joy. I would be very grateful if someone could tell me what wrong.
<?php
session_start();
require_once ("ConnectToMySql.php");
if (!isset($_SESSION['username']))
{
header("location:../Login/LoginForm.php");
}
?>
First of all, let's test if the user is authenticated:
<?php
session_start();
var_dump($_SESSION); // print all the session to see if $_SESSION['username'] is set
exit;
...
If the user is logged, restart the browser to end the session. (You must restart the browser, it is not enough to close that tab)
If the $_SESSION is empty, the user is not logged in, remove the first test lines and let's see if the execution goes to the header function:
if (!isset($_SESSION['username']))
{
echo "User will be redirected";
exit;
header("location:../Login/LoginForm.php");
}
If it goes ok so far, it means that the redirection is not working.
Please note that if there was any output sent, the headers can no longer be sent to the browser. If that is the case you need to check your files (also files included like ConnectToMySql.php) for any output. A frequent mistake is adding a blank space after closing the php tag ?> in a configuration file and that is very hard to find and debug. A simple practice to avoid that is never put the php end tag ?> in files containing only PHP.
Depending on these tests, you could at least find out what is not working.

$_SESSION values not holding!

I'm writing a user login system, and I (like so many others) am having a problem with my sessions.
Here's the pointer from the login script when the inputs are validated:
session_start();
$_SESSION['id']=$id;
header('location: memberhome.php');
Here's the first thing on memberhome.php:
<?php
session_start();
$id=$_SESSION['id'];
?>
And later in memberhome.php:
You are logged in as: <?php echo $id; ?>
The problem is $_SESSION['id'] is apparently empty so the echo $id prints nothing.
An alternate that also does NOT work:
//removed session_start and $_SESSION bit from the top
You are logged in as: <?php session_start(); echo $_SESSION['id']; ?>
NOW, here's the weird part. This method DOES work:
You are logged in as: <?php echo session_start();$_SESSION['id']; ?>
You can see the session_start() is moved AFTER the echo. This works when the page loads from the login script. However, upon refresh, it does NOT work once again.
I've tried a bunch of alternatives and spent a few hours searching for answers in previous questions. I also looked at my phpinfo() for something fishy and found nothing. This is entirely what my progress is hinging on. Thanks!
First of all, please enable debugging:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Second, session_start() needs to be at the top of the page. So the line you wrote;
You are logged in as: <?php echo session_start();$_SESSION['id']; ?>
will never work.
The following line needs to be on top of the page, before any HTML etc.
<?php
session_start();
$id=$_SESSION['id'];
?>
Have you tried:
print_r($_SESSION);
to examine the contents of the session?
Make sure you're calling session_start() before you output anything on the page. The standard cookie-based sessions require some header information to be exchanged, which must be done before you send any content.
You're most likely running into output buffering, which is why it sometimes works and other times it does not. Generally speaking, stick to starting the session before any output is generated, you'll find your code works better.
use
ob_start(); #session_start();
on the top of the both page

Categories