if statement keeps falling back to the else part - php

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');
}
}

Related

Infinite loop php redirect based on cookie

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;
}

Check url for information with php

I am wanting to check the url of one of my pages if the user has landed correctly
for example if a user visits www.example.com/page.php?data=something
The user will beable to view the page
but if the user visits www.example.com/page.php he gets redirected
This is my current code
$checkurl = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($check, "?data=")!==false){
}
else {
header("Location: index.php");;
}
I thought this would work and been at this for a while cant seem to see a problem but i am still learning...
You need to use $_GET
For example
if (!isset($_GET["data"])) {
header("Location: index.php");
}
PHP Manual $_GET
Have you tried
if(isset($_GET['data']))
{
}
else
{
header("Location: index.php");
}
This way you just check if there is a "data" on your URL
You can just use this since you are looking for a query string aka a $_GET request:
if ($_GET['data'] != 'something') {
header('Location: http://test.com');
exit();
}
Also, if you just want to check if they included ?data=:
if (!isset($_GET['data'])) {
header('Location: http://test.com');
exit();
}

Detect if cookies are enabled in PHP

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

why is my header("Location: $_SERVER['HTTP_REFERER']"); PHP function not working?

It works when I input
header("Location: http://www.google.com");
but it doesn't work when I have
header("Location: $_SERVER['HTTP_REFERER']");
I want to redirect the page to whatever page it came from.
Try it: :)
if (!empty($_SERVER['HTTP_REFERER']))
header("Location: ".$_SERVER['HTTP_REFERER']);
else
echo "No referrer.";
However, for determining which page user came from, I'd rather use session variable, which gets reset at every page:
session_start();
echo "Previous page:", $_SESSION['loc'];
$_SESSION['loc']=$_SERVER['PHP_SELF'];
ps: This only works for local pages, you cannot track other websites.
You might try:
header("Location: {$_SERVER['HTTP_REFERER']}");
I've had problems with variable expressions which contain quotes in strings without braces.
You also need to look out for $_SERVER['HTTP_REFERER'] simply not being set. Some user agents don't set it, some privary tools mask it, and you need to handle people coming to your page without a referrer.
Here is a simple solution.
check and see what $_server['http_referer'] is giving you and if its set then you can redirect and if not put a fall back url something like :
if(isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != ""){
$url = $_SERVER['HTTP_REFERER'];
}else{
$url = "YOUR INDEX PAGE OR SOMETHING";
}
header("Location: ".$url);
This is a browser feature, and any polite browser will send the
correct header (although various 'security' tools will override this
with a fake referer).
It's browser specific so not every browser/security software combination will send it to the server. You're better off setting a session variable on each page load to determine which page the user came from (or something similar with a bit more logic)
header("Location: $_SERVER[HTTP_REFERER]");
Without the single quotes. This is the fastest way to access and concatenate array values without extra concatenating code.
Simply you can use
if(isset($_SERVER['HTTP_REFERER'])){
header("Location:".$_SERVER['HTTP_REFERER']."");
}
One of the mistakes that occure sometimes is, that NO OUTPUT must happen before header('Location: ' ....)
This is not working (shows the output, but doesn't redirect):
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
$cleaned_url = preg_replace('/[^a-z ]+/i', '', strtolower($referer));
$pattern = '/troester/';
$res = preg_match($pattern, $cleaned_url);
echo $res; // <--- OUTPUT COMES HERE
if ($res == true) header("Location: {$referer}");
}
This is working (does redirect properly):
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
$cleaned_url = preg_replace('/[^a-z ]+/i', '', strtolower($referer));
$pattern = '/troester/';
$res = preg_match($pattern, $cleaned_url);
//echo $res; // <--- NO OUTPUT COMES HERE
if ($res == true) header("Location: {$referer}");
}
This is also working, but doesn't make sense ():
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
$cleaned_url = preg_replace('/[^a-z ]+/i', '', strtolower($referer));
$pattern = '/troester/';
$res = preg_match($pattern, $cleaned_url);
if ($res == true) header("Location: {$referer}");
echo $res; // <--- OUTPUT COMES HERE, AFTER header('Location: ' ....)
}
(For better understandig, hope this may help)

Check session and cookie not working in PHP

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.

Categories