Strange problem with PHP and sessions - php

So the basis of this page is I set a session value when the page loads, and clear it on any other page they visit. Then the page can make an ajax call to download a file. If the session value matches the value I pass through the URL I allow them to download the file. If not I return a 404 error. I was having some weird issues, so I removed the 404 and set it to echo out the values instead to see what I was getting. Here is the top of the code on the page:
$code = $this->_request->getParam('code');
$confirm = $_SESSION['mp3_code'];
echo $code."-1-".$confirm;
if($code != $confirm)
echo $code."-2-".$confirm;//header("HTTP/1.1 404 Not Found");
else
{
Here is what displays on the page from the ajax call
12723430-1-12723430-2-
As you can see when it echos out the first time they exist, then somehow after I compare them and it fails you see that it echos out blank values like they suddenly ceased to exist. Any ideas?

It is imperative that you make sure to call session_start at the top of any script using sessions. I think this may be the case here.
In your code, it's echoing $code and $confirm. But $confirm is an empty string since you are not actually retrieving the session data (why has yet to be determined), the condition will most of the time evaluate to TRUE.

Related

Function still executes from link without active session

I got some code that executes with value's inside a $_GET and some code that checks for an active session. Yet, when I go to the link directly without active session it still executes the function and after that returns to the login page.
My code:
My loginheader:
<?php
session_start();
if (!isset($_SESSION['Username'])|| $_SESSION["Actief"] == 0||
$_SESSION["Actief"] == 2) {
return header("Location: main_login.php");
exit();
}
My webpage (only the needed code):
require "../loginheader.php";
require "../AdminOnlyHeader.php";
// --some code with sql instructions--
$result = ExecuteQuery($sql);`
AdminOnlyHeader is just to check for admin status. This too seems to be bypassed by just entering a link.
So if you still don't understand what I mean, here's a short summary of what I do:
I make one of those links that contain the get data needed to execute it;
I log out and get returned to the login page;
I enter the the link I made before;
After some loading I am still on the login page but when I look at my database I see that the record has been updated and thus the function (ExecuteQuery) was executed.
Remove return from
return header("Location: main_login.php");
We need two references to understand this:
Return part:
If called from the global scope, then execution of the current script file is ended. If the current script file was included or required, then control is passed back to the calling file.
Header part:
If you redirect but you don't die() / exit() the code is always executed and displayed.
Basically, since you returned, it won't reach the exit() part, meaning that it will return the execution to the main script - the one with the function that shouldn't be executed in this circumstance.

problems using 'header' in php to redirect on load

No headers are already sent, this is the first piece of code accessed on the page.
I am making a multilingual site and as it has very little text am trying to redirect users to different directories based on their language. I have written this in php and every time I assess the site, I receive an error and it wont load.
$lang=$_SERVER['HTTP_ACCEPT_LANGUAGE'];
$es=array("es", "es-es", "es-us", "es-mx");
if(array_key_exists($es, $lang)){
header('Location: http://www.site.com/es');
exit;
}else{
header('Location: http://www.site.com');
exit;
}
In Firefox I receive the error 'Firefox has detected that the server is redirecting the request for this address in a way that will never complete.'
And in Safari 'Too many redirects occurred trying to open "websitename". This occurs when opening a page it redirects you to another that, when opened, you are redirected to another page.'
But I have no copy of the language check script in the sub folder. When I make the if statement very simple if($lang =='es-es') it works perfectly. There must be something wrong with my syntax but I can't see what it is.
As I understood, correct me if wrong, if you are on the ELSE statement, it redirects you to the same site, where the check is performed once again, and redirects you once again, and again, causing an endless loop.
Use in_array to check instead - or turn your dictionary array into a hash:
1)
if (in_array($lang, $es)){
// ...
}
2)
$es = array_flip(array("es", "es-es", "es-us", "es-mx"));
if (isset($es[$lang])) {
// ...
}
As it stands, your $es array is an indexed one, but you're trying to search in its keys - which are simple numbers (0, 1, 2, 3...).
Yet there's another problem here. What if someone tries to access your site.com without any variation of es in HTTP_ACCEPT_LANGUAGE header? They will be redirected to it again... and again... and again, as each subsequent redirect is re-checked by that if clause.
The solution is to make some default page, which won't be checked for that language setting; thus the eternal redirection loop will be broken. )
You need to use in_array instead of array_key_exists
First, try to do this:
var_dump("<pre>", $lang); die();
and see what are you actually getting in $lang.
What every you are getting, copy past it into your $es array values.
It is saying so because you are redirecting it to the same page again and again. try redirecting to some other page if your condition gets false or simply alert a message saying language do not found or something like this.
As I Getting your Problem...
Change these two lines
$es=array("es", "es-es", "es-us", "es-mx");
if(array_key_exists($es, $lang)){
with following lines
$es=array("es"=>es, "es-es"=>es-es, "es-us"=>es-us, "es-mx"=>es-mx);
if(array_key_exists($lang, $es)){
Basically In the array_keys_exits($key, $array-name) function there are two parameter pass & it is to be first parameter is the value of (key) you want to search or Second parameter is pass the Array name.
I Think you pass the array_key_exits with null value as key & wrong syntax description.
http://php.net/manual/en/function.array-key-exists.php

Clearing url variables

i am trying to sort out the error section of my settings page, and because i am validating all the data on a seperate script i have to use the url variables to check whether an error is present
so it looks like this if there is an error
localhost/site123675/settings.php?eid=1
however, the error shows fine, but i want a way to remove it, becuase if the user gets an error then enters a correct answer, it still shows the same error.
So, how can i clear the url of any variables before the user resubmits the page?
Any ideas?
Not exactly sure what exact problem you're facing, but you could just do a header redirect:
if (isset($_GET['eid'])) {
header('Location: /site123456/settings.php');
exit;
}

Redirecting Pages with PHP causing problems

I have a page which has a link to a php page which takes data from $_GET and updates a database. After that it returns the user to the homepage with:
header("Location: http://localhost/");
The thing is that this seems to "interrupt" the mysql part of the code. If I remove this redirect, everything in the database is updated, but when I put it back, nothing gets updated...
This is the database update code, I am using a class of mine as a mysql wrapper:
$conn->where('hash',$data1['hash']);
$conn->update(TABLE_ITEMS,$newData1);
$conn->where('hash',$data2['hash']);
$conn->update(TABLE_ITEMS,$newData2);
Notes:
-There is no text or echo()'s on the page and no space before the <?php tag
Order of Code:
Data received from $_SESSION and $_GET
Data processed and placed into arrays
Data placed into mysql database
header(); used to redirect page
Code
<?php
require_once('config.php');
import();
if ( isset ( $_GET['g'] ) && isset ( $_SESSION['itemA'] ) && isset ( $_SESSION['itemB'] ) ) {
$itemA = $_SESSION['gameA'];
$itemB = $_SESSION['gameB'];
$newData1 = processData($itemA);
$newData2 = processData($itemB);
$conn->update(TABLE_ITEMS,$newData1);
$conn->update(TABLE_ITEMS,$newData2);
header('Location: http://localhost/');
} else {
header('Location: http://localhost/');
}
If you send a header when previously content is outputted, you will get an error that may cause your script to stop execution. So if the header is above the update, the update may not be executed at all. It depends on your settings whether you see this error or not.
<?
echo 'yo';
header('Location: ....'); // <-- error
Update(); // Never gets executed
The output doesn't have to be an echo. It can even be a single space before the opening <?.
Without seeing much of the code, it's hard to be certain, but my guess would be that the PHP page is continuing to work exactly at it was before. What I would suggest might be happening is that the redirected page (ie your home page) is itself doing some database work which is overwriting the changes that had been done by the original page.
As I say, that's quite a wild guess in the absence of any more code (or even any detail about the data in question or what the site does), but I'd say it's worth investigating that possibility.
Try putting ob_start() at the top of the file. It sometimes helps. You can't output before calling header().
Show more code. It's to less of it to think what is wrong.
I have no idea why this worked, but it turned out that if I change this:
header("Location: http://localhost/");
to this:
header('Location: http://localhost/');
everything works. Weird!!

PHP when are $_SESSION vars evaluated?

So my issue is that I'm setting a message in a session var to carry over in a page redirect.
And then setting the var to an empty string so it doesn't redisplay everytime.
Like so:
if ($successMsgs || !empty($_SESSION['msg_success'])) {
$success_block[] = '<ul id="success-block">';
foreach($successMsgs as $success) {
$success_block[] = '<li>'.$success.'</li>';
}
if (!empty($_SESSION['msg_success'])) {
$success_block[]='<li>'.$_SESSION['msg_success'].'</li>';
$_SESSION['msg_success']='';
}
$success_block[] = '</ul>';
$success_block = implode('',$success_block);
}
The problem is that the clearing of the session var seems to have a retro-active effect so the message never gets displayed. It only works if I take out the line that re-sets it to an empty string. I'm thinking there's something about when session vars are evaluated that I don't understand?
Except for the freedom to define functions and classes after invoking them, there is definitely nothing retro-active in PHP. Session variables will be available after the session_start() command. Unsetting a session variable inside the block won't have an effect in the code before it occurs.
Your problem must have to do with something else - maybe the page gets called twice, or a header redirect takes place?
It turned out that the code beneath the redirect was getting run, before actually redirecting. The solution was simply to add an exit to the redirect function.
well, the only possibility i can think of is that you are calling this piece of coding twice. and in the first call it doesn't get printed. maybe you are redirecting twice for some reason...

Categories