I'm currenting busy coding a registration page. The page has three steps and every step has its own cookie value. What I'd like to do is checking for the cookies value and transfer the user to the correct page upon visiting the website
Example:
if the value of $_COOKIE['step'] is 'step_two' it should redirect to: www.domain.com/register.php?step=your_details. If the cookie's not set, it should not redirect and stay on the register.php page.
The redirecting is working 'fine', but it gets into an infinite loop. I really cant think clear anymore as I've been awake for almost 24h now. Therefor I would appreciate it if anyone could push me into the right directions.
Piece of code:
$cookie_value = 'step_2';
setcookie("step",$cookie_value, time()+3600*24);
$cookie_not_set = true;
$cookie_step_two = false;
if (isset($_COOKIE['step'])) {
if ($_COOKIE['step'] == 'step_2') {
$cookie_not_set = false;
$cookie_step_two = true;
header('Location: ?step=your_details');
exit();
}
} else {
$cookie_not_set = true;
}
Thank you.
Nowhere are you actually setting your cookie value, so it won't change. That's why you have an infinite loop.
$_GET and $_COOKIE have nothing to do with each other. It looks like you want:
if ($_GET['step'] === 'your_details')`
...which would be better than using a cookie anyway.
You are going to constantly enter your if condition as there is no other manipulations going on to your cookie data.
if your cookie is set to "step_2" you will enter the loop. No changes are in place, so on the refresh to the page. You will re-enter the step_2 condition and be into a redirect.
I'm also assuming that you understand that your $_GET & $_COOKIE requests are completely different. If not, see #Brads answer
A solution to stop this infinite loop would be:
if (isset($_COOKIE['step'])) {
if ($_COOKIE['step'] == 'step_2') {
$cookie_not_set = false;
$cookie_step_two = true;
$_COOKIE['step'] = 'step_3';
header('Location: ?step=your_details');
exit();
}
But also take note, your true/false validations/changes are local changes and will not be absolute on page refresh
I believe your issue is the redirect is not changing your cookie, so you need to look at the GET var you a re passing if the cookie is set to step_2 thus;
$cookie_not_set = true;
$cookie_step_two = false;
if (isset($_COOKIE['step'])) {
if ($_COOKIE['step'] == 'step_2') {
if( !empty($_GET['step']) && $_GET['step'] == 'your_details' )
{
... you have redirected and now can continue ...
}
else
{
// redirect and set the get var to signal to this script.
$cookie_not_set = false;
$cookie_step_two = true;
header('Location: ?step=your_details');
exit();
}
}
} else {
$cookie_not_set = true;
}
Related
I have a problem with cookies. In my login script i have the following line of code:
if($_GET['keep'] == "true"){
setcookie('id',$id,time()+3153600);
}
The problem I'm facing is that the cookies are not saving at all ( not even if i don't quit the browser). I'm quite a beginer in this respect and I think I'm not doing it right.
EDIT:
If i print_r all the Cookies it only gives me PHPSESSID after the cookie is set. I printed on index.php and i set the cookie on login.php
SOLUTION: Cookies are saved by default with the path of the file they were created in. To change the path there is another atribute. So by setcookie('id',$id,time()+3153600,'/'); you make the cookie available for the entire domain.
There is no issue in your code
if($_GET['keep'] = "true"){
setcookie('id',$id,time()+3153600);
}
This will may cause to
No data passing to $_GET['keep']
Or if data passing $_GET['keep'] value in not Matched ("true").
Both Works then $id is empty in setcookie method
Improve your code
if(isset($_GET['keep']){
if($_GET['keep'] == "true"){
if(isset($id))
{
#all perpect
$cokkie_id = 'id';
setcookie('id',$id,time()+3153600);
echo "I'm Set. And My value is ".$cokkie_id;
}
else
{
echo "Opzz My ID is also empty";
}
}
else
{
echo 'Get method is Set. But Value is not "true". Actual value is '. $_GET['keep'];
}
}
else
{
echo 'I cant reach Get method Buddy';
}
I think you miss "=" sign
if ($_GET['keep'] == "true") {
if (!isset($_COOKIE['id'])) {
setcookie('id',$id,time()+3153600);
}
}
use isset or ==
if (isset($_GET['keep']) && $_GET['keep'] == "true") {
setcookie('id', $id,time()+3153600);
}else{
echo 'keep is empty';
}
I want to check if a cookie exist and if not look into the header if it is send with the link and if that is FALSE go back to the page where i create the cookie in the header. When i input this code into my code (on top)
if(empty($_COOKIE['location'])){
if(isset($_GET['location'])){
$_COOKIE['location'] = filter_input(INPUT_GET, 'loc', FILTER_SANITIZE_NUMBER_INT);
setcookie('location', $_COOKIE['location'], time()+3600 * 8);
}
else {
header('Location: location-select');
}
It keeps falling back to the else part header('Location: location-select'); no matter what i try. If i remove this block of code it works fine but there is no check on my cookie. Anyone has an idea why this is happening?
I think this is what you're trying to do.
It checks if $_COOKIE['location'] is empty and isn't set.
If that's the case then it creates a cookie with the data you supplied.
If it /is/ set it navigates to location-select.
if(empty($_COOKIE['location'])){
if( ! isset($_GET['location'])){
$data = filter_input(INPUT_GET, 'loc', FILTER_SANITIZE_NUMBER_INT);
setcookie('location', $data, time()+3600 * 8);
}
else {
header('Location: location-select');
}
}
I am trying to detect if a user on my page has cookies enabled or not. The following code performs the check, but, I have no idea on how to redirect the user to the page they came from.
The script starts a session and checks if it has already checked for cookies. If not, it redirects the user to a test page, and since I had called session_start() in the first page, I should see the PHPSESSID cookie if the user agent has cookies enabled.
The problem is, ths script might be called from any page of my site, and I will have to redirect them back to their selected page, say index.php?page=news&postid=4.
session_start();
// Check if client accepts cookies //
if (!isset($_SESSION['cookies_ok'])) {
if (isset($_GET['cookie_test'])) {
if (!isset($_COOKIE['PHPSESSID'])) {
die('Cookies are disabled');
} else {
$_SESSION['cookies_ok'] = true;
header(-------- - ? ? ? ? ? -------- -);
exit();
}
}
if (!isset($_COOKIE['PHPSESSID'])) {
header('Location: index.php?cookie_test=1');
exit();
}
}
I think its better to make one file set cookie and redirect to another file. Then the next file can check the value and determine if cookie is enabled. See the example.
Create two files, cookiechecker.php and stat.php
// cookiechecker.php
// save the referrer in session. if cookie works we can get back to it later.
session_start();
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// setting cookie to test
setcookie('foo', 'bar', time()+3600);
header("location: stat.php");
and
stat.php
<?php if(isset($_COOKIE['foo']) && $_COOKIE['foo']=='bar'):
// cookie is working
session_start();
// get back to our old page
header("location: {$_SESSION['page']}");
else: // show the message ?>
cookie is not working
<? endif; ?>
Load cookiechecker.php in browser it'll tell cookie is working. Call it with command line like curl. It'll say, cookie is not working
Update
Here is a single file solution.
session_start();
if (isset($_GET['check']) && $_GET['check'] == true) {
if (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
// cookie is working
// get back to our old page
header("location: {$_SESSION['page']}");
} else {
// show the message "cookie is not working"
}
} else {
// save the referrer in session. if cookie works we can get back to it later.
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// set a cookie to test
setcookie('foo', 'bar', time() + 3600);
// redirecting to the same page to check
header("location: {$_SERVER['PHP_SELF']}?check=true");
}
HTTP_REFERER did not work for me, seems like REQUEST_URI is what I need.
Here is the code I finally used:
session_start();
// ------------------------------- //
// Check if client accepts cookies //
// ------------------------------- //
if( !isset( $_SESSION['cookies_ok'] ) ) {
if( isset( $_GET['cookie_test'] ) ) {
if( !isset( $_COOKIE['PHPSESSID'] ) ) {
die('Cookies are disabled');
}
else {
$_SESSION['cookies_ok'] = true;
$go_to = $_SESSION['cookie_test_caller'];
unset( $_SESSION['cookie_test_caller'] );
header("Location: $go_to");
exit();
}
}
if( !isset( $_COOKIE['PHPSESSID'] ) ){
$_SESSION['cookie_test_caller'] = $_SERVER['REQUEST_URI'];
header('Location: index.php?cookie_test=1');
exit();
}
}
// ------------------------------- //
There's no need to save the original URL and redirect to it afterwards. You can perform a transparent redirect via AJAX which doesn't trigger a page reload. It's very simple to implement. You can check my post here: https://stackoverflow.com/a/18832817/2784322
I think this is easiest solution. Doesn't require separate files and allows you to proceed with script if cookies are enabled:
$cookiesEnabled = true;
if (!isset($_COOKIE['mycookie'])) {
$cookiesEnabled = false;
if (!isset($_GET['cookie_test'])) {
setcookie('mycookie', 1, 0, '/');
#ob_end_clean();
$_SESSION['original_url'] = $_SERVER['REQUEST_URI'];
$uri = $_SERVER['REQUEST_URI'];
$uri = explode('?', $uri);
$q = (isset($uri[1]) && $uri[1])?explode('&', $uri[1]):array();
$q[] = 'cookie_test=1';
$uri[1] = implode('&', $q);
$uri = implode('?', $uri);
header('Location: '.$uri);
die;
}
} else if (isset($_GET['cookie_test'])) {
#ob_end_clean();
$uri = $_SESSION['original_url'];
unset($_SESSION['original_url']);
header('Location: '.$uri);
die;
}
// if (!$cookiesEnabled) ... do what you want if cookies are disabled
I have this code that makes sure your are logged in, and then making sure you are on the right page by checking a cookie set at login. This code works on a page in a directory underneath the login in script, however in a page in a directory below that it always takes you to accessdenied. Any ideas?
<?php
session_start();
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
header("location: http://mywebsite.com/member/accessdenied.html");
exit();
}
$_COOKIE["verify"] = $verify;
if( $verify != file_get_contents("name.txt")) {
header("location: http://mywebsite.com/member/accessdenied.html");
} else { }
?>
And it seems like just the bottom part, the part that checks the cookie, isn't working. Again, any ideas?
I think you have your cookie assignment backwards:
$_COOKIE["verify"] = $verify;
Should be
$verify = $_COOKIE["verify"];
And that should be:
$verify = isset($_COOKIE["verify"])?$_COOKIE["verify"]:false;
As if the cookie was not previously set, well it would give a notice error.
<?php
$verify = $_COOKIE["verify"];
if( $verify == file_get_contents("name.txt")) {
echo $verify . 'is equal to the content of name.txt'
} else {
echo $verify . 'is NOT equal to the content of name.txt'
}
?>
Try debugging the code with this. See if the content of your variable is what you want. But I find it unusual that a variable would be a file.
are you sure you always get the content from file_get_contents? I could imagine it's found in one directory but not in the other!
antoher idea: cookies can be set to be relevant for a particular directory only. I just realize, what we're missing here, is the part where you set the cookie in the first place.
Kind of a weird issue, ok here is my setup...
domain.com calls reads from an Iframe on sub.domain.com
sub.domain.com makes an ajax call to sub.domain.com/call.php
sub.domain.com returns ajax call to domain.com
AKA long-polling
Now, everything works perfectly when there is no session data (I close the browser and restart the page). However, once I reload the page and their is session data, call.php does a start_session() and hangs there.
I have tried almost everything and can't figure this out. I've tried destroying the session, unsetting all the session variables, modifying some ini settings, and nothing has worked.
Here is the code of call.php where the session data is...
session_start();
$sql = ("SELECT userid FROM status WHERE typing = '".mysql_real_escape_string($userid)."'");
$result = mysql_query($sql);
if ($result && mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$typing_id = $row['userid'];
if (!empty($typing_id)) {
if (isset($_SESSION['typing2'])) {
unset($_SESSION['typing2']);
}
} else {
$typing_id = "-1";
}
} else {
$typing_id = "-1";
if (isset($_SESSION['typing'])) {
unset($_SESSION['typing']);
}
}
if ($_SESSION['typing'] != $typing_id && !isset($_SESSION['typing2']) || $initialize == "1") {
$typing = array('typing_id' => $typing_id);
}
if ($typing_id == "-1") {
$_SESSION['typing2'] = "-1";
} else {
$_SESSION['typing'] = $typing_id;
}
Does anyone have any ideas? I was thinking it might have to do with the domain but I'm not sure.
Thanks!
I actually found out (after hours and hours of debugging and research) that the problem is being caused because the PHP session locks up. Then, when the new page loads, it won't work until the old session times out. A session_write_close() will fix it.
default session storage in php is cookie based. if you are using that you must set domain for your session cookie in php.ini
http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-domain