On my secure site (https), I set a PHP $_SESSION variable. I then use header("location: http://...page.php") to send the user to a php page on my http site, which is on the same server. The session variable is lost, because of the http:// URL (I assume) in the header statement. I can't get the header("location: ...") to work without using the full URL. Thus I tried the following tip from stackoverflow - php session lost when switching, which several other posts reference, but I ended up with numerous error_log warning entries and once I clicked to another page that required $_SESSION['loginUser'], the session was gone.
PHP Warning: session_start(): The session id is too long or contains illegal characters
Sample session ID passed: dlouenopfi3edoep3dlvne8bn1
Code that creates the session on https php page (note for this post header location is not real)
session_start();
$currentSessionID = session_id();
$_SESSION['loginUser'] = $username;
header("location: http://www.test.com/path/to/page/off-campus/cat_index.php?session=$currentSessionID");
Code that receives the session on http php pages
// Retrieve the session ID as passed via the GET method.
$currentSessionID = $_GET['session'];
echo "sid: " . $currentSessionID;//a session id like above is displayed
// Set a cookie for the session ID.
session_id($currentSessionID);
session_start();
if(isset($_SESSION['loginUser'])){
$username = $_SESSION['loginUser'];
echo "Welcome: $username<br />";
} else {
require_once($_SERVER["DOCUMENT_ROOT"] . "/_includes/CASwrap.php");
}
I've exhausted my searching. Any help will be appreciated. Thanks.
I solved my two questions.
To prevent the numerous error_log warning entries all I needed was an "exit" statement after the "header" statement.
To maintain the current session, I used an if statement to test for a current session id stored in the variable $currentSessionID. If yes then set the session_id with the value of $currentSessionID. If no, then don't set the session_id with the $currentSessionID variable, since it has no value.
Related
I am trying to set the PHPSESSID from a value I received from a CURL POST. However, it is not setting when I assign it to the session_id(). The first echo statement is the correct PHPSESSID from the curl post. However, the second echo returns empty. Any thoughts?
PHP
//set current session id
session_id($sessID[1]);
echo "current SessID: " . session_id();
//start session
session_start();
echo "PHPSESSID: " . $_COOKIE['PHPSESSID'];
PHP's superglobals are populated with data when the script starts up, and then they are NOT touched again by PHP for the life of the script. Your new session ID will only show up on the NEXT request, after the new session cookie's had a chance to round-trip through the client's browser.
You cannot echo anything before doing session_start(). Per the docs:
Note: To use cookie-based sessions, session_start() must be called
before outputing anything to the browser.
http://us3.php.net//manual/en/function.session-start.php
The way you have it now is messing up the cookie. And you don't want to be messing up the cookies. :) The end result is the client never recognizes a session id cookie.
I have an application that needs to create a new session id at specific times. Right now, this is causing the user to log out because $_SESSION ends up being empty.
It is my understanding that regenerate_session_id() should preserve the session information and just change the session id (meaning that $_SESSION['someVar'] would be available on subsequent requests.
What I'm finding is that $_SESSION is empty on subsequent requests.
I've tried copying the data:
$session = $_SESSION;
session_regenerate_id();
$_SESSION = $session;
but that didn't help. If I comment out session_regenerate_id(); subsequent pages load properly (the $_SESSION array is populated and the user stays logged in).
I have a dev environment that I just set up recently running a newer version of PHP (5.5) and this code is functioning as I would expect it to. I'm not aware of any other differences.
What am I missing? Thanks in advance.
session_start();
$_SESSION['name'] = "mike";
session_regenerate_id();
echo $_SESSION['name'];
outputs 'mike'
I did a little test on my server and it seems to be working fine.
<?php
session_start();
$old = session_id();
$_SESSION['name'] = "mike";
session_regenerate_id();
$new = session_id();
echo $_SESSION['name']."<br/>\n";
echo $old ."<br/>". $new
?>
Here is a sample of the output:
mike
d9oog3vo55936m3088o25qqe27
m6qq99pp1c80mit8e66ho3hfn3
As you can see, it is changing the session id and keeping the session variables in place, as it is supposed to. Perhaps your hosting provider has some funky settings in the php.ini? You might want to look into that.
Alternatively, and it is a bit of a hassle, couldn't you create a cookie with a key that will log them back in immediately after it logs them out, then delete the cookie?
After a good nights rest, it occurred to me that you probably have some header issues. Sessions are only valid within the same domain they are set in, so for example, if you set the session variable in www.example.com, then use a header redirect to header("location:example.com");, your session variables will be blank, as they aren't set for that domain, they are set for www.example.com. I would check through your code and see if that is the issue, as you say, it is working fine in your sandbox.
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 this query in mysql in a php page:
mysql_query("INSERT INTO tz_todo SET text='".$text."',
position = ".$position.",
user_id=".$_SESSION['user_id'].",
view_stat=0");
I tried to echo the query and the result is this:
INSERT INTO tz_todo SET text='trial text', position = 21, user_id=, view_stat=0
it seems that it can't get the session value of user_id.
And $_SESSION['user_id'] is not working in social engine. How to correct this? I also made a localhost version in my xampp and everything is fine but when I converted it into social engine, session is not working.
In any page where you are using session objects, place this code at the beginning of the file:
if(!isset($_SESSION)){session_start();}
This way if the session is not already started, it starts it; otherwise it ignores the session start if the sesion is already started.
This is important because calling session_start() if session is started already can sometimes cause errors.
That's how I get my user id through session
session_start();
$userID = $viewer->getIdentity();
$_SESSION['user_id'] = $userID;
echo $_SESSION['user_id'];
Using session to store the user_id is totally wrong. To gain a user_id try
$viewer_id = Engine_Api::_()->user()->getViewer()->getIdentity(); (or $user->getIdentity if you have another user's object).
If you still need to use session for storing this data, use Zend-approach.
session_start();
$_SESSION["test"] = "hello world";
session_start();
echo $_SESSION["test"];
does above code work ? if not, check your session.save_path in the php.ini
NOTE: to retain this variable remember to call session_start() on each php script/page before calling for the variable from the session.
Yoy might be forget to start your session at the top of the page
<?php if(!isset($_SESSION)){ session_start(); } ?>
$_SESSION['user_id'] might not stored a value. check your login page (Basically after login session variables will set) or after register weather you assigned a value to that session variable..
setting a value to a session variable :
$_SESSION['user_id'] = "1234567";
I am a beginner for PHP and studying to use cookie for login. Would any body please check my code to see what is my problem, or let me how to fix this problem.
When I open the page at the first time, the cookie will not work. It will work when I repeated to open that link. However, I still could not make it work after I use function include and header One of codes is :
One code cookie.php is :
<?php
setcookie("cookiename",$_REQUEST['name']);
if(isset($_COOKIE['cookiename'])){
$cookieSet = ' The Cookie is ' . $_COOKIE['cookiename'];
} else {
$cookieset = ' No Cookie has been set';
}
setcookie("cookiepwd",$_REQUEST['pwd']);
print_r($_COOKIE);
?>
When I run this code first time, it will does not show any thing. I can see cookie data at second time. From some website it is said that cookie would not be read at the same page.
So I moved print_r($_COOKIE) to second php file as well as added function include() or header() to above file, but both neither works.
Cookie2.php:
<?php
setcookie("cookiename",$_REQUEST['name']);
if(isset($_COOKIE['cookiename'])){
$cookieSet = ' The Cookie is ' . $_COOKIE['cookiename'];
} else {
$cookieset = ' No Cookie has been set';
}
setcookie("cookiepwd",$_REQUEST['pwd']);
include(‘printcookie.php’);
//or header("Location: printcookie.php")
?>
printcookie.php:
<?php
print_r($_COOKIE);
?>
Thank you very much for answering in advance!
Michelle
setcookie only sets up the header, that is being sent to the client. It doesn't change the $_COOKIE superglobal.
In other hand - $_COOKIE is filled up with the cookies sent from the client
So at first step - you set the cookie with setcookie and have nothing in $_COOKIE because client hasn't sent it yet, and will only on the next request.
And there is no way of doing what you want, rather than modifying $_COOKIE manually
PS: it is a bad idea to put user's password in the cookie
Give zerkms the answer, but I just want to reiterate:
Cookies are not bad for storing bits of info like the user's theme preferences or preferred start page, etc. They get their bad rep from being used for identity and authentication handling. There are cookies out there that basically have "isAdmin=0" in order to control user access. It is very easy to change that to isAdmin=1 and have a field day. Since you are new to PHP, take the time to learn about sessions now while it's all new to you.
When you set a cookie using setcookie, you are sending an HTTP header to the browser with the cookie info. The browser will then pass back that cookie in any future requests to the server. The $_COOKIE global variable holds the cookie info passed in from the browser to the server.
Since you are using $_REQUEST to get the cookie name, you don't need to check the cookie (otherwise you wouldn't have the data to set it right?). So consider going this route:
if(!isset($_COOKIE['cookiename'])) {
$name = $_POST['name']);
setcookie("cookiename",$name);
} else {
$name = $_COOKIE['cookiename']);
}
echo "Welcome back $name!";
This will also help out if they clear cookies, etc.
But really, the safer route is:
session_start();
if(!isset($_SESSION['name'])){
$_SESSION['name'] = $_POST['name']);
}
if(!isset($_SESSION['pwd'])){
$_SESSION['pwd'] = $_POST['pwd']);
}
$name = $_SESSION['name'];
$pwd = $_SESSION['pwd'];
And even this would be frowned upon for serious web security, where you should simply check the password against a stored hash and then delete it, using other global variables to confirm session integrity. But there's now a whole StackExchange for that.
As a workaround you could use location() after checking the cookie to have access to the stored data.
But be aware that location() fails, if anything (including breaks and blanks in your script) already sent to the browser.