PHP won't retrieve cookie - php

First off, please bear with the question as I am just starting out with this.
So I have the following running in an index.php:
<?php
if(isset($_COOKIE['language'])) {
if (($_COOKIE['language']) == 'en')
print "<SCRIPT LANGUAGE=\"JavaScript\">window.location=\"URLGOESHERE\"</SCRIPT>";
elseif (($_COOKIE['language']) == 'fr')
print "<SCRIPT LANGUAGE=\"JavaScript\">window.location=\"URLGOESHERE\"</SCRIPT>";
}
else {
print "<SCRIPT LANGUAGE=\"JavaScript\">window.location=\"URL-FOR-COOKIE-SETTING-PAGE\"</SCRIPT>";
}
?>
The "else" statement redirect goes to the page where the user sets their language preference, and once they do so, that page sets a cookie then sends them to the proper version of the site. However, when the user goes back to this main index.php, it cannot seem to find the cookie and skips right to the "else" statement. The redirects used to be used done with PHP using 'header,' and it didn't work then either. I had read elsewhere that that could pose some troubles, so I switched it to try printing Javascript.
The weird thing is that I can find the cookie as soon as it is set, exactly where it should be, with the correct name and variable all present. I've done it exactly like the books tell me to (to my knowledge). I've tried this both in Firefox and Safari with no luck.
What did I miss?
EDIT: Here's the script that actually sets the cookie. The parameter is sent from the link via a url encode like this: <a href="setlang.php?lang=en">
<?php
$lang = urlencode($_GET["lang"]);
setcookie("language", $lang, time()+60*60*24*90, ".URL");
switch ($lang) {
case 'en':
header('Location: URLGOESHERE');
break;
case 'fr':
header('Location: URLGOESHERE');
break;
}
?>

the cookie isnt available to the script that set it.
you have to set the cookie and then on the next page load the cookie will be available to the php code

Try this code:
setcookie("language", $lang, time()+60*60*24*90, "/");
I'm uncertain what .URL was supposed to do o.o

Related

PHP redirect to page version based user’s location (IPAPI) and remember in a session

I'm attempting to include some code in the head.inc file that will check if the page is available in the user's location language and if so it'll redirect to that page. Obviously this isn't a great for UX but alas my client is keen.
The only issue I need to overcome is if the user has already been redirected then don't do it for every page... store the fact that the user was redirected and don't do it again until the session has ended. Something like that.
I have written the code below but a) I'm unsure this is the best way to do it and b) it seems to get stuck in a redirect loop (which I thought I'd avoided by my second session check).
I'm using the ipapi.com to check the user's location. I’m also using ProcessWire’s ‘$session’ which is effectively the same as PHP session.
if (!$session->get("lucentLightingRegion")) {
$session->set("lucentLightingSessionRedirected", "false");
if ($page->ipapiGetUserLocation()['continent_code'] === 'NA') {
$session->set("lucentLightingRegion", "NA");
if ($page->viewable('na')) {
$url = $page->localUrl('na');
$session->redirect($url);
}
} else {
$session->set("lucentLightingRegion", "INT");
if ($page->viewable('default')) {
$url = $page->localUrl('default');
$session->redirect($url);
}
}
} else {
$sessionRegion = $session->get("lucentLightingRegion");
bd($sessionRegion);
if ($page->viewable($sessionRegion) && $session->get("lucentLightingSessionRedirected") == "false") {
$url = $page->localUrl($sessionRegion);
$session->redirect($url);
$session->set("lucentLightingSessionRedirected", "true");
}
}
Calling $session->redirect($url); before $session->set("lucentLightingSessionRedirected", "true"); appears to be your issue.
Looking at the source code of $session->redirect() it executes:
header("Location: $url");
exit(0);
Which is preventing $session->set("lucentLightingSessionRedirected", "true"); from being called, resulting in the redirect loop, as lucentLightingSessionRedirected was never set to "true".
To resolve the issue, you should be able to change the order of operations.
if ($page->viewable($sessionRegion) && $session->get("lucentLightingSessionRedirected") == "false") {
$session->set("lucentLightingSessionRedirected", "true");
$url = $page->localUrl($sessionRegion);
$session->redirect($url);
}
Do Keep in mind that Wire::__call() is being used to issue Session::__redirect()
However it appears that you also have a logic flaw with the sessions and regional redirects, that may result in an undesired state. Since $page->localUrl() is using lowercase values but lucentLightingRegion is uppercase, I am not aware of how your application is designed to handle them. Additionally the default region of INT loading the default page, which may not work as desired when redirecting to $sessionRegion = 'INT'. I would need more details on how this is expected to work and if there is indeed different states for NA, na, INT and default and what is supposed to happen when none of the specified values are a viewable() page when lucentLightingRegion is set. Currently if lucentLightingRegion is set and is not viewable() or lucentLightingSessionRedirected is "true", none of the conditions will be met.

Avoiding redirect loop

I am finished setting up a maintenance function on my webpage. This is the index.php code
<?php
session_start();
require_once("system/functions.php");
require_once("system/config.php");
if($maintenance == 1){
require_once(header("Location: index.php?page=maintenance"));
die();
session_destroy();
}elseif($maintenance == 0)
{
getPage();
}
?>
I have also tried with
header("Location: index.php?page=maintenance");
Instead of the require once header code above.
But if I put
require_once("frontend/pages/maintenance.php");
It will work. The problem then is that people can type in every page they want in the address bar and this will show up. I need it to use it's own url (Which works with the 2 header codes above, but I get too many redirects error) and no matter what, you will be redirected to this url to see the maintenance screen
The php part of the maintenance.php file:
<?php
if($maintenance == 0){
header("Location: index.php?page=index");
die();
}
else{
header("Location: index.php?page=maintenance");
die();
}
?>
I can remove the else code part on the maintenance.php file, but then it will always redirect to "websitename"/index.php(Still maintenance screen though, the same problem as mentioned above)
So I need to change my code so when there is maintenance, you will be redirected to index.php?page=maintenance no matter what. Sorry if I missed out on some details, it's late. Feel free to ask me about this, if it is needed :)
Indeed this looks like you are looping. The following is executed when you are in the index.php script:
require_once(header("Location: index.php?page=maintenance"));
So you actually load the script you are already running, again. And it will again find maintenance==1 and do exactly the same thing again.
You should just redirect once, and then when you see you are already on the page=maintenance URL actually display what you want to display as maintenance message, like this:
session_start();
require_once("system/functions.php");
require_once("system/config.php");
if($maintenance == 1){
if ($_GET['page']) == 'maintenance') {
// we have the desired URL in the browser, so now
// show appropriate maintenance page
require_once("frontend/pages/maintenance.php");
} else {
// destroy session before exiting with die():
session_destroy();
header("Location: index.php?page=maintenance");
}
die();
}
// no need to test $maintenance is 0 here, the other case already exited
getPage();
Make sure that in frontend/pages/maintenance.php you do not redirect to index.php?page=maintenance or you will still get into loops.
So frontend/pages/maintenance.php should look like this:
// make sure you have not output anything yet with echo/print
// before getting at this point:
if($maintenance == 0){
header("Location: index.php?page=index");
die();
}
// "else" is not needed here: the maintenance==0 case already exited
// display the maintenance page here, but don't redirect.
echo "this is the maintenance page";
// ...

PHP cookies and session not kept

I've been google-ing this for a while, and I have reviewed my code over and over again, still no clue about it.
Here is the deal:
I have a multi-language website. When clicking on a different language preference, I pass it thorugh url as ?lang=en, or so.
Then, the code uses GET to read the language, start session and creating a cookie named "lang".
Good so far, and actually it was working perfectly.
I was thinking about creating a subdomain, so I got it and I wanted to use the same cookie through the subdomain and i found that I could achive it using (name, value, time, '/', '.domain.com')
It never worked, so I reverted things back to normal: (name, value, time) and that is it. I used to have it with no path or domain values. Actually it is working the same way with a different website.
Long story short, after reverting changes, I am NOT able to get a session or cookie stored in the browser. I have looked in the stored info and there is no such thing as session or cookies for that site.
Answer: YES, I have cookies enabled, plus, my other sites are working perfectly and other public sites using cookies are working fine as well.
I have tried using echo to print the cookie and session value, still no luck.
Here is part of my handle code:
<?php
session_start();
header('Cache-control: private'); // IE 6 FIX
if(isSet($_GET['lang']))
{
$lang = $_GET['lang'];
// register the session and set the cookie
$_SESSION['lang'] = $lang;
setcookie("lang", $lang, time() + (3600 * 24 * 30));
}
else if(isSet($_SESSION['lang']))
{
$lang = $_SESSION['lang'];
}
else if(isSet($_COOKIE['lang']))
{
$lang = $_COOKIE['lang'];
}
else
{
$lang = 'es';
}
switch ($lang) {
case 'en':
$lang_file = 'lang.en.php';
$lang_dir = 'en';
break;
case 'es':
$lang_file = 'lang.es.php';
$lang_dir = 'es';
break;
default:
$lang_file = 'lang.en.php';
}
include_once 'languages/'.$lang_file;
?>
This one is actually working, since I am using this and works:
<?php
$page = $_GET['page'];
if (!empty($page)) {
$content .='html/'. $lang['DIR_PATH']. '/'. $page. '.html';
include($content);
}
else {
include('html/'. $lang['DIR_PATH']. '/'. 'home.html');
}
?>
Using the link
index.php?lang=en
The previous code reads the "en" value, but as soon as I click any link, it is changed to "es".
If include file would not be working, the $lang['DIR_PATH'] would not work and no content would be displayed. Do you agree? Or am I wrong? But it does and changes language succesfully. The thing is that I can not keep the preference stored.
Thanks in advance
Wow!
Finally I double checked everything.
I got the answer already.
I realized that, somehow (don't know why), my **
php.ini
** file was modified and now was asking for a different path to save the session.
I anyone has this problem, go to php.ini file and look for
session.save_path
And either create the specific folder, or change the path showing there
Thanks for reading, anyway, for your help and your time.

Am i testing for a PHP $_SESSION variable too soon after setting it?

I have a login that I've implemented with AJAX and the PHP on the backend sets $_SESSION['guest'] before sending the response text back. Then it the javascript on the front end redirects me to the guest page which checks whether or not isset($_SESSION['guest']), but often this results in false, and i'm taken to another page (using my else branch).
I'm wondering if maybe I'm checking for it too early and that's why isset($_SESSION['guest']) results in false. But I make it count down 5 seconds before redirecting to the page that tests for it, so this is what I don't understand.
After it happens a couple of times (i logout and log back in again), it stops failing and I can't get it to fail which obviously doesn't help! Thought that may be a caching/cookie problem but I've cleared all that and it still won't fail again.
Any ideas?
//this is the login script snippet
if($rows == 1){
$_SESSION[$type] = $username; //$type is posted over as guest or client. this is valid right?
$_SESSION[$type.'_id'] = $result['id'];
echo $_SESSION['welcome'] = 'You have logged in successfully.';
}
<?php
//snippet from the guest page. session_start() is invoked within the included 'page_top.php'
include('page_top.php');
if(isset($_SESSION['guest'])){
if(isset($_GET['sect'])){
if($_GET['sect'] == 'photography'){
include('view_album.php');
}
else{
include('404.html');
}
}
else{
include('welcome.php');
}
}
else{
include('403.html'); //i get redirected here!
}
include('page_bottom.php');
?>
edit: i now think that when it fails the session variable just isn't getting set because if i reload my guest page, it results in the 403.html page every time, so it's not a delay, it just doesnt get set.
I don't think you should be echo-ing a variable as you are setting it? That doesn't make any sense to me.
echo $_SESSION['welcome'] = 'You have logged in successfully.';
If $type is being posted over as guest or client, shouldn't it be $_SESSION[$_POST['type']];
or are you setting $type to the POST variable somewhere else in the page?
You must include this at the top of the page (before ANY HTML or whitepace output, and after the < ?php):
session_start();
EDIT:
I know this is an old post. But for anyone that needs it in the future here it is!

redirect problem in for loop in PHP

i am using xajax framework
i want redirect my url in for loop.
every time its go to the home.php at last
my sample code is this
for($i=0;$i<4;$i++) {
if($i == 1) {
header("index.php")
} else {
header("home.php")
}
}
Well, since the start value of '$i' is 0, the else-block will be called the first time which points to home.php.
Why even have a loop to do this? It makes no sense.
What exactly is the point of that code? You can only have one redirect in your script.
And, it should be written like this:
header('Location: home.php');
exit;
without the exit, the code keeps running.
It's a simple mistake that I fall into a lot myself, but header() can set plenty of different headers; you need to actually specify the Location header (with the page to redirect to):
header("Location: index.php")
The point is that after a redirect, its a whole new page load.
PHP starts everything a new, so your loop will be started new. That means on every page $i will start at 0 and loop to 3.
header("Location... does not automatically redirect you, you have send something to the user or stop the page (with exit or die) to send the headers. So your for loop will always redirect to home.php because it's the last header set in the for loop, not because its the first.
I agree with this post: redirect problem in for loop in PHP
But if you still want to do this, you can find some workaround by passing a variable defining that your loop has already been executed + you should end execution while redirecting page.
You can use this code and change in your way:
if(!isset($_GET['ex']) || $_GET['ex'] != '1') //can use ether isset or/and check its value
{
for($i=0;$i<4;$i++)
{
if($i == 1)
{
header("index.php?ex=1");
die(); //or exit();
} else {
header("home.php?ex=1");
die(); //or exit();
}
}
}

Categories