undefined variable related to session/cookie - php

I have a log in form that allows persistent login and regular session. Long story made short, when users are in their account, they can change password, email and stuff. But for that, I need to get their username from their session or cookie first (so I can do the proper SQL query).
I try to do so with this code:
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
}
else
if(isset($_COOKIE['username']))
{
$username = $_COOKIE['username'];
}
But if I try to echo $username, I keep getting "undefined variable". Why is that?
I noticed that if I put a session_start(); at the top. I get the proper username for session but not for cookie of course. How can I solve that?
The weird part (for me) is that I got the exact same code (well that part) in another page and username isn't undefined.
PS: If something isn't clear or more information is needed, please tell me.
EDIT
I tried this:
function accountValidation()
{
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
}
else if(isset($_COOKIE['username']))
{
$cookie = $_COOKIE['username'];
$explode = explode(' - ', $cookie);
$username = $explode['0'];
}
echo $username;
}
accountValidation();
And it worked ... So if I put it into a function and then call it, it works?! What is the diference? Why does it need to be into a function for it to work???

If you set certain cookie, it would be available to you from next reload. As $_COOKIE is set when a page head is called. You wont be able to retrieve the cookie from the same page which has set the cookie. I hope you got what i meant. If not let me know I would give an better example.
EDIT:
Example
<?php
session_start();
$_SESSION['test'] = 'test1success';
echo $_SESSION['test'];// would display test1success
if (!isset($_COOKIE['test2']))
{
setcookie("test2", "test2success", time()+3600);
}
echo $_COOKIE['test2'];
// wont display test2success when you load the page for first time
// reload it & it would display test2success
?>
Explanation:
The first thing you need to understand is that the cookie is stored on your PC(browser) when the page is loaded. The client (i.e. browser) sends cookie headers to the server & does the page execution. The values set by set_cookie during page execution are set on the client pc, and the server doesn't know about the new values just set - unless you reload the page & the cookie header is sent back.

Related

Get ID from URL and store it in variable

I need to get the data from URL, example domain.com/?id=username
Username will vary from one user to another... Once they visit the website with link like that, they can move around the website and then at some point fill out the form. Since they moved around the website, the url will not have ?id=username in the path, so I need to store that data in the variable to be able to send it with the form.
I assume I need to set and store the cookie per session (so that cookie will refresh after session / browser exit)
I use ob_start() since I have to implement this code in the body, when the headers are already sent.
ob_start();
session_start();
$affid = $_GET['id'];
setcookie('affid',$affid, 0, "/");
$finalaffID = $_COOKIE['affid'];
ob_end_clean();
echo '<span class="testoutput">'.$finalaffID.'</span>';
After some attempts, I got this code, but it doesnt store the value after I move around couple pages, it only shows the on initial page visit.
Any ideas please?
You could use session variables.
$_SESSION["id"] = $_GET["id"];
this session var will be accessible anywhere the session is open. Just call it with $_SESSION["id"].
index.php
Url: www.domain.com/?id=user
<?php
session_start();
if (isset($_GET["id"])) {
$_SESSION["id"] = $_GET["id"];
}
?>
otherpage.php
Url: www.domain.com/otherpage.php
<?php
session_start();
if (isset($_SESSION["id"])){
echo $_SESSION["id"];
}
?>
Jose is right about saving IDs in sessions. There's a good post about it that deals SPECIFICALLY with IDs here: Cookie vs Session for Storing IDs
But, if you want to store it as a cookie, this code stores the ID.
$id = $_GET['id']);
setcookie('id', $id);
And this code allows you to retrieve the ID!
echo $_COOKIE['id'];

Whats the best way to keep a user signed in after their session ends?

I'm working on a simple login page for a class and was planning on using cookies to keep users logged in (if they choose) after closing their browser. I used a checkbox input button as a case to set a cookie. After a user goes to the login page and signs in I send them to a script to check for valid username and passwords where I also check if the button was used
#QotD.php
if(isset($_GET['signed_in'])) #check box value
if($_GET['signed_in']=="on"){
if(isset($_GET['username']))
$username = $_GET['username'];
setcookie('username',$username,time()+10000);#cookie set with username
}
What I thought to do was to have a conditional statement at the beginning of the login page file checking whether a cookie is set and if it is go directly to the main page.
#QotD_homepage.php
if(isset($_COOKIE['username'])){
header("Location: main_page.php");
exit();
}
The problem is that it seems to keep the user signed in whether they check the box off or not. I tried adding a button to unset the cookie but it didn't work. Is there a more efficient way to handle cookies in this manner?
Firstly, for signing in a user, you are going to want to use the POST action method as it hides the information from the url. The GET method contains the information in the url and can be easy copied and hacked.
Secondly, you if statements should look like this
if(isset($_GET['username']))
{
$username = $_GET['username'];
# do something with username...
if(isset($_GET['signed_in']) && $_GET['signed_in']=="on")
setcookie('username',$username,time()+10000);
}
}
To solve your question regarding why user is being logged in every time, even when you don't set the cookie, the reason is probably because you have not unset the cookie. This is usualy done via a logout page.
Create a logout page with the code:
setcookie('username', null, 1);
Then run this page every time you wish to unset the cookie to test the login without ticking the checkbox.
Hope it helps :)
If conditional statement is wrong.Fix it by ending it with end if or using {} brackets. Use the code below
<?php
if(isset($_GET['signed_in'])) { #check box value
if($_GET['signed_in']=="on"){
if(isset($_GET['username']))
$username = $_GET['username'];
setcookie('username',$username,time()+10000);#cookie set with username
}
}
?>
OR
<?php
if(isset($_GET['signed_in'])) : #check box value
if($_GET['signed_in']=="on"){
if(isset($_GET['username']))
$username = $_GET['username'];
setcookie('username',$username,time()+10000);#cookie set with username
}
endif;
?>
Hope this helps you

php cookie does not work at the first time reading

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.

PHP Sessions: Explanation please?

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.

PHP Login, Store Session Variables

Yo. I'm trying to make a simple login system in PHP and my problem is this: I don't really understand sessions.
Now, when I log a user in, I run session_register("user"); but I don't really understand what I'm up to. Does that session variable contain any identifiable information, so that I for example can get it out via $_SESSION["user"] or will I have to store the username in a separate variable? Thanks.
Let me bring you up to speed.
Call the function session_start(); in the beginning of your script (so it's executed every page call).
This makes sessions active/work for that page automagicly.
From that point on you can simply use the $_SESSION array to set values.
e.g.
$_SESSION['hello'] = 'world';
The next time the page loads (other request), this wil work/happen:
echo $_SESSION['hello']; //Echo's 'world'
To simply destroy one variable, unset that one:
unset($_SESSION['hello']);
To destroy the whole session (and alle the variables in it):
session_destroy();
This is all there is about the sessions basics.
The session is able to store any information you might find useful, so putting information in is up to you.
To try some things out, try the following and see for yourself:
<?php
session_start();
if(isset($_SESSION['foo']))
{
echo 'I found something in the session: ' . $_SESSION['foo'];
}
else
{
echo 'I found nothing, but I will store it now.';
$_SESSION['foo'] = 'This was a triumph.';
}
?>
Calling this site the first time should store the information, storing it the second time will print it out.
So yeah, you can basically put anything you like in the session, for instance a username.
Keep in mind, however, that the session dies as soon as the user closes his browser.
$_SESSION['user'] must be set to your user's name/id so that when you try to read it the next time, you'd be able to identify that user. For example:
login:
$_SESSION['user'] = some_user_id;
user area:
$user = $_SESSION['user'];
// extract the user from database, based on the $user variable
// do something

Categories