I'm having trouble getting an !isset test working properly.
I tried a few different things but can't get it working as I expected.
Here is the scenario: if the get variable isn't set (i.e. someone visits the page directly and not to the page with the get variables in the url) then send them to another page.
This is what I tried:
if(!isset($_GET["e"])){$goToPage = 'Location: http://'.$_SERVER['SERVER_NAME'].'/';header($goToPage);}
if(!isset($_GET["k"])){$goToPage = 'Location: http://'.$_SERVER['SERVER_NAME'].'/';header($goToPage);}
I also tried this:
if(isset($_GET["e"])){}else{$goToPage = 'Location: http://'.$_SERVER['SERVER_NAME'].'/';header($goToPage);}
if(isset($_GET["k"])){}else{$goToPage = 'Location: http://'.$_SERVER['SERVER_NAME'].'/';header($goToPage);}
I know my variables are fine because if I echo the gets or assign them to variables, I get no problems:
$currentEmail = htmlspecialchars($_GET["e"]);
$currentKey = htmlspecialchars($_GET["k"]);
echo($_GET["e"]);
echo("</br>");
echo($_GET["k"]);
I also heard that by doing the check below, you can find out if someone came to the page by clicking a link. i.e. adding "a" instead of an actual get variable name. Does anyone know if that's true?
if(!isset($_GET["a"])){$goToPage = 'Location: http://'.$_SERVER['SERVER_NAME'].'/';header($goToPage);}
The code you provided works absolutely fine and as expected on my system (Apache 2.2 on Debian).
You may need to check whether your Location: header is actually being sent. I'm guessing you're sending some output before your header() call, which will mean your header won't be sent at all - your header must be the absolute first output, which means you can't even have a blank line before your <?php tag. Depending on your error reporting settings, you may not see a warning when this happens. Take a look at PHP header redirect not working.
The script does not stop after you issue a Location header! If you issue another Location header later in the same script, it's going to overwrite the previous one! exit after you set the header to prevent the rest of the script from executing.
if (!isset($_GET["e"]) && !isset($_GET["k"])) {
header('Location: http://' . $_SERVER['SERVER_NAME'] . '/');
exit; // <----- !!!
}
Related
I was writing a script where I have a redirect header in the end.
Then I added a redirect header in the middle if a specific condition would come up.
I was very surprised to notice that the last header("Location:http//mydomain.com") was the one that triggered. I thought that the header would automatically "jump" from the page, but it seems like it just keeps it in memory and goes through the whole page first.
Any ideas on what the "proper" way to "cut" the flow and change page is?
<?php
$specific_condition=true;
// I wanted this to be the end
if($specific_condition) header("Location: http://google.com/");
// But it still triggers following redirect
header("Location: http://bing.com/");
?>
Always call exit; right after your Location header:
if($specific_condition) {
header("Location: http://google.com/");
exit;
}
header() function by itself just collects the headers to be sent to the client. So it is not supposed to stop execution after any particular header, e.g. Location. But as long as it makes no sense to do something after you decided to redirect user - exit is used
you can use variable to hold location address
This way, you can also execude some code after new location is set.
$location = 'http://bing.com/';
$specific_condition=true;
if($specific_condition) $location = 'http://google.com';
//do something else
header("Location: " . $location);
I'm developing a custom content management script, and I'm working on page redirection.
The code below compares the URL code to the URL for the a certain page ID in the database, and if the two URLs are not the same, the user is redirected.
However, I want to add a variable, so that we can check if the page has been redirected or not. It isn't working.
if (isset ( $_GET ['id'] ) && $rawdata) {
if ($_SERVER ["REQUEST_URI"] != $rawdata ['htmltitle']) {
header ( "HTTP/1.1 301 Moved Permanently" );
header ( "Location: http://${_SERVER['SERVER_NAME']}:${_SERVER["SERVER_PORT"]}${rawdata['htmltitle']}" );
$redirected = true;
;
}
}
if ($redirected == true) {
print_redirect_nonexpected ();
}
function print_redirect_nonexpected (){
echo "<!-- REDIRECTED _ NOT _ EXPECTED ? -->";
}
The function isn't being run, so no echoing.
Any ideas what I'm doing wrong here?
Use this:
header ( "Location: http://".$_SERVER['SERVER_NAME'].$_SERVER['SERVER_PORT'].$rawdata['htmltitle']);
If $rawdata['htmltitle'] is full URL of your page, use this:
header ( "Location: http://".$rawdata['htmltitle']);
And also adding die() after header() is good.
When you send a Location: header, the user-agent stops loading the current page and loads whatever page you tell it to load, so you'll never see the output.
However, your code may* continue to execute in the background, so usually you want to follow your header() with an exit; to prevent unwanted behavior.
* Depends on server configuration and on ignore_user_abort.
Also, header("Location: /{$rawdata['htmltitle']}"); will suffice. Since you are redirecting to the same server, an absolute path suffices. Don't overcomplicate your redirects for nothing with $_SERVER variables.
As soon as the Location header is sent the browser will abort the current operation and fetch the page at the redirected location. This means that for all intents and purposes a location ('header: example.com') will have essentially the same effect as a die (). You can override this behaviour by using output buffering, or you can move the header() calls to lower down in your script. However you can't move them to after the print_redirect_unexpected call, as sending any output to the browser will cause all headers to be sent as well and you won't be able to send any more.
So basically, you need to turn on output buffering.
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!!
Hey, I am trying to make an if statement that redirects them to a different page if true, simple right?
I am not sure why this is not working but I am using:
if ($_POST['accounttype']=='Paid User - £2 p/m'){
$userid = strtolower($_SESSION['X2X2']);
$getuser = mysql_query("SELECT * FROM XXXXXX WHERE X2X2 = '$userid'");
$info = mysql_fetch_array($getuser);
$id = $info['X3X3'];
mysql_query("UPDATE members SET payment = '" . mysql_real_escape_string("XXXXXXXX"). "' WHERE X3X3 = $id");
header('Location: http://beta.XXXXX.co.uk/purchase.php');
mysql_close($con);
}
When I put
<?
echo $_POST['accounttype'];
?>
And I get back
Paid User - £2 p/m
Which is correct?
Any help would be appreciated,
Thanks.
Looks like you want to call exit() before the close brace on your if statement.
The documentation for header has example code like this:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
The end bit of your if statement really ought to be:
mysql_query("UPDATE members SET payment = '" . mysql_real_escape_string("XXXXXXXX"). "' WHERE X3X3 = $id");
mysql_close($con); // do this before sending a redirect header
header('Location: http://beta.XXXXX.co.uk/purchase.php');
exit();
Also, header doesn't work if you've already sent any output, per this warning from the documentation for header:
Remember that header() must be called
before any actual output is sent,
either by normal HTML tags, blank
lines in a file, or from PHP. It is a
very common error to read code with
include(), or require(), functions, or
another file access function, and have
spaces or empty lines that are output
before header() is called. The same
problem exists when using a single
PHP/HTML file.
As it seems to depend on £, you have several possibilities depending on which values $_POST['accounttype'] can have.
First I suggest you try:
if ($_POST['accounttype']=='Paid User - £2 p/m'){
(as £ is £ in HTML).
If this doesn't work, what is the part of the string, that makes it unique? Paid User or 2 p/m? If any of these, it is sufficient to check against a substring like:
if (substr($_POST['accounttype'],-5)=='2 p/m'){
or
if (substr($_POST['accounttype'],0,9)=='Paid User'){
or any combination (avoiding £).
You haven't by any chance already output something to the browser have you? If you modify the location header after using the echo or print statements, it will issue a warning which you probably won't see unless you have verbose errors or logging turned on.
I know this can happen with UTF-8 files in some versions of PHP - the byte order mark (BOM) of the UTF-8 file are output before the PHP script starts execution, which prevents the location header from being sent.
Altering the HTTP header with header requires that the HTTP header has not been sent yet. This can be one reason for why it doesn’t work for you as the HTTP header is sent together with the first output of your script (any output including text before <?php).
When you set error_reporting to E_ALL and display_errors to true, PHP will display you all errors immediately. This can help you to determine the cause of you error.
My first inclination would be to check if there are any extra characters on your POST data by trying the following:
if (trim($_POST['accounttype']) == 'Paid User - £2 p/m') {
I have a php page that takes in a bunch of url parameters and sends out an email. I am trying to have this page call another web page using the same url parameters, after the mail is sent. If I do the following, will my email be sent reliably? Is a redirect what I really want to do?
Update: Thanks for the tips. As you can see by my use of the +, I don't know any php. After reading all the answers so far I have come up with this:
Random code to send email...
file_get_contents('http://www.othersite.com/' . $_SERVER["REQUEST_URI"]. "?". $_SERVER["QUERY_STRING"]);
I believe this should initiate a GET on the other site with all the current parameters, which is exactly what I want. This way I don't have to deal with redirects. Any problems to this solution?
Update 2: Since my url was https, file_get_contents caused me some problems. There are ways to get around this but I just used header for a redirect and all worked well. Thanks everyone!
The question raised in the other answers whether your basic approach is really what you want is valid - check that first. Anyway, if it really is what you want to do (Is your target URL really identical to the one you're on?) you can indeed use
header('Location: http://www.othersite.com/' . $_SERVER["REQUEST_URI"]);
Just note the use of . to concatenate the string instead of +, you can't do that in PHP.
To do it really properly, you could use http_build_url to build a full valid URL from the current GET array. Code from the manual, modified a bit:
<?php
echo http_build_url("http://user#www.example.com/pub/index.php",
$_GET,
HTTP_URL_STRIP_AUTH | HTTP_URL_JOIN_PATH | HTTP_URL_JOIN_QUERY
);
?>
The header location call will be only called after the mail code so it won't affect your email.
Don't forget to call exit() after your header location call.
Also the string concat operator is not + it's . (dot).
if its the same application, why dont you call the same functions ?
if you want you could do file_get_contents .. instead of a redirect for the same effect.
If you just want to hit that page why not use file_get_contents
$data = file_get_contents('http://www.othersite.com/' . $_SERVER["REQUEST_URI"]);
echo $data;
The benefit with this is you don't have to physically go to the other site if you don't want to, equally if you control the script on the other site you could return a true or false in the HTML which could be checked upon return.
For full compliance (sometimes Chrome will not work with just a Location: header)
header( "HTTP/1.0 302 Found" );
header( "Status: 302" ); # this is for chrome compliance
header( "Location: http://www.othersite.com/' . $_SERVER["REQUEST_URI"] );
Another option is to echo the HTML tag:
<meta http-equiv="Refresh" content="1;url=http://www.othersite.com/<?php echo $_SERVER['REQUEST_URI']; ?>">
This allows you to set a delay time for redirecting (usually 1s), which is good in some situations so that the user doesn't become confused by a flash of content. You can put a 'Stand by while we redirect you' message or similar.