Redirecting if statement not working - php

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') {

Related

PHP: header not working

Ive read pretty much alot of post about this but seems like its not helping me.
I have been working an a testing local server and everything has been working swimmingly, but when I uploaded it to the web the php is suddenlly not working properly. I am connected to the db and all. the main issues I have is with the header (as far as I know).
I have been shaving bits of code and simplifying it to narrow down the problem and came to the conclusion that it was the header:
<?php
require 'admin/Connections/Connections.php';
session_destroy();
if(isset($_POST['Login'])){
$UN = $_POST['Username'];
$PW = $_POST['password1'];
$result = mysql_query("select * from admin where Username='$UN'");
$row = mysql_fetch_array($result);
echo $row['Password'];
echo $_POST['password1'];
if($PW == $row['Password']){
header('Location: admin/home.php');
}else{
$_SESSION["LoginFail"] = "Yes";
}
}
?>
the echo spits out both $post and $row as the same value so I know it should execute the header, but it just refreshes the page with the added echos.
I tried replacing the url with something like http://www.google.com/ but that takes me to a blank page with the echos. what am I missing? if it is something obvious you have permission to trash me as long as you give me an answer...
Echoing output before you use header() will stop the header from working. From the PHP 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.
At minimum, the header() call should precede the echo calls you have in your code. If that doesn't work, check to see if any output is happening in the require()ed file at the top of your code.
You are outputting HTML with echo. Therefore, header will not redirect.
Solutions:
1) Add ob_start() at the page start. This will store all your output to buffer and thus your page will not have any HTML output, redirection will occur.
2) Comment the code of echos.
3) Use javascript redirect:
echo "<script>window.location.href='admin/home.php';</script>";
This will work irrespective of what is output on the page.
You cant use PHP's header function after an echo, just put it before your echo, then it should work.
You cannot use header() function if you make any output to the client. Sometimes it's referred as "headers already sent" notice.
Also, consider moving alway from mysql_* functions as they're deprecated and won't be supported anymore. Try mysqli.
First, remove your echo statements or comment them.
when you are taking the user to some other page why the hell are you echoing anything here? To show to whom?
and write ob_start(); at the top of your PHP file i.e:
<?php
ob_start();
--------the rest of your code---

PHP header location not working with clean urls

<?php
$result = mysqli_query($link, $query);
$url=$_SERVER['REQUEST_URI'];
if (!$result) {
$url.="/signup";
header("Location:".$url);
} else {
$url.="/home";
header("Location:".$url);
}
?>
Hello friends I am in a bit problem I am doing a project and using clean urls my htaccess is good everything is going good but after a signup form submission when I want to change header location
php gives an error can't change header location
kindly help
I would post a comment but I dont have enought rep.
Anyway, probably you are seeing error about headers already sent. It is common problem and it have nothing to do with clean urls. what you can do?
1. Make sure you are not outputting anything before header() call
Problem is based on fact how web server and HTTP works. When you are outputting server will send headers and content as soon as it is ready. And you may be outputting even whitespaces, so double check this first.
2. Turn on output buffering
If for any reason you need to output something before headers manipulation, you can turn on output buffering. This way server first "buffers" your data and then sents everything out. Hovewer you are paying in load time for this. Use only rarely, when it is really needed!
You can use a ob_start()for this
If that is your PHP script, I can see whitespaces before <?php tag.
<?php
^^^^--- WHITESPACES
These whitespaces will be written to output buffer even before PHP interpreter kicks in, and when you call header() it will give an error. This is because no output should be sent to client before calling header().

PHP header redirect not working and staying on login.php

I am trying to redirect a login page using PHP to the profile.php page. I have tested that the code pulls out the information form the database using the sessions. Everything works fine up until the final If statement. It isn't giving me any errors but it comes back blank and doesn't move away from the login.php file( where the script is running).
session_start();
//print_r($_POST);
if(isset($_POST['email'], $_POST['password'])){
require 'php_includes/db_connect.php';
$query = $dtb->prepare("SELECT * FROM users WHERE email=:email AND password=:password");
//$query->bindParam('ss', $_POST['email'], $_POST['password']);
$query->bindParam(':email', $_POST['email'],PDO::PARAM_STR);
$query->bindParam(':password', $_POST['password'],PDO::PARAM_STR);
$query->execute();
//die('Connection error, because: '.$query->errorInfo());
//echo 'hi';
//$query->close();
if($row = $query->fetch()){
echo 'hi';
$_SESSION['email'] = $row['email'];
header("location: profile.php");
}
}
Remove the echo. There must be no output before a header redirect.
This includes any type of accidental white space so whenever you include another file before the redirect you have to be sure there was no output before calling the redirect.
Usual approach:
Most coding frameworks will use the ob_* functions -- meaning they will capture all outputs to the browser into a buffer and they will decide if/when the output should be sent.
With an output buffering solution in place on the entire application (such as the init/bootstrap file) it becomes much easier to ensure that cookies, sessions and header redirects occur correctly because you control the exact point in the application where the output is sent.
Small & hard to find issues:
Because of this files which do not output anything such as files containing only function definitions or class files should not end with a ?> because a white space after the ?> is considered output.
Files must also all be saved in the same format such as ASCII or UTF-8 with BOM or UTF-8 without BOM otherwise, the differences between formats might be misinterpreted as outputs (usually 1-2 characters of output) very hard to find indeed.
Debuging:
Set your error_reporting() to E_ALL and ini_set('display_errors', true). This will echo various notices an warnings that you might not otherwise see. One of those warnings will be something like "headers already sent" mentioning a particular file/line where the first output occurred.
If the file/line of output looks familiar then you can remove that output. If you can't find the place the first output occurred you may have one of the "small & hard to find issues".
Along with removing the echo 'hi'; and whitespace as Mihai Stancu stated
it's recommended to put an exit(); after a header location, like this:
if($row = $query->fetch()){
$_SESSION['email'] = $row['email'];
header("location: profile.php");
exit();
}
Just using header() does not mean the code stops executing. Whenever using header() to redirect you need to explicitly call exit() to stop execution of the script.

PHP redirect within a function call

I have looked at some of the other posts made on similar topics but I cannot follow what they are instructing.
Basically my problem is this, I want to redirect to the main log in page of my website after a successful password reset has happened.
Here is what I have so far:
if (isset($_POST['Resetpw'])) {
if ($query == $_GET['token'] & $_POST['password'] == $_POST['confirmed_password']) {
$passwordTest = $_POST['password'];
$result = mysql_query("SELECT `tempTicket` FROM users WHERE `username` = '" . $_POST['username'] . "'limit 1;");
$query = mysql_fetch_array($result);
mysql_query("UPDATE users SET `tempPass` = '$passwordTest' WHERE `username` = '" . $_POST['username'] . "' ");
echo '<div class="success">Password successfully changed!</div> ';
//header("Location: www.google.com");
//exit;
This is all within a function, the commented out part is where I want to redirect to my webpage.
So to wrap it up, can I force the function to redirect to the start page after a function finishes. I am using KISSMVC framework for this project if that matters.
You should remove the echo before the redirect.
What you have commented out should work if you use the full path, e.g.: http://google.com.
Another thing: you should really drop the use of mysql_* functions (it will be deprecated in the future) and use either mysqli_* or PDO.
Yet another thing: you're application is vulnerable to SQL injection.
First, I hope I don't need to go into depth about sanitizing your inputs before accessing the database with them.
I am unaware of the KISSMVC. But I am aware of how PHP and browser-server interactions happen. So I'll approach your question from that format.
I see two things here. One is that you want to give the user an alert when a transaction has successfully happened. That can be done dynamically with a redirect, but it depends on where you send them. If you send the user to a location that you have no control over (your example cited google.com) then you will have to deliver your alert (and your input) with javascript and ajax. The reason for this is because header redirects won't function if you sent some output to the user's browser already. So, you will need to implement some .js into your code that makes an AJAX call to a script that executes your code and returns a success/failure flag, which then triggers a message (of success/failure).
If you do have control of the content you are redirecting to, and you do not wish to touch any .js, you can redirect to an intermediary page that uses a variable that you created to hold the success/failure message, output it to the browser and a button that links to your next page after that with the data appended to the query string. All that can be done in php/MySQL.
Yes, just get rid of the echo statement before it. You cannot echo anything to the screen before a header call.
You might also want to add some error handling so that you are really sure it was successful and switch to prepared statements to avoid sql injection.
Output Buffering
Everyone else here has said you can't echo anything before the header call (including whitespace). But that is fact incorrect. If you use output buffering in the php.ini file for example to output buffer the entire page - then you are free to use header() ANYWHERE in the script (so long as the code does not manually flush it). http://php.net/manual/en/outcontrol.configuration.php
You want to set this in php.ini
output_buffering = On;
And then you can use header() anywhere in your code. Just remember that after a redirect, to use die() or exit() to prevent the PHP page carrying on execution after the redirect.
Without Output Buffering
You must NOT print anything to the browser including whitespace otherwise the headers have already been sent and can no longer be modified by PHP. Output buffering stops this as the entire generated page is sent in one go at the end of the script meaning headers are free to be changed anywhere in the script.
P.S.
As others have mentioned, your SQL is vulnerable to SQL injection and you should no longer be using mysql_* but instead switch to pdo or mysqli_* due to mysql_* being depretiated.

PHP: Redirect ( header)

header("profil.php?id=" . $show["id"]);
What i tried to do, but headers are already sent at top, so how can I redirect the user? Should I use window.location.replace("URL"); (javascript) instead?
If you can't control the very beginning of the script, where headers would be sent, then yes, your only method is to use JavaScript.
Also, the proper syntax is header('Location: profil.php?id=' . $show['id']);
You need the Location: part so the browser knows what header it's receiving. Also, don't forget to do an exit() or die() right after the redirect.
Someone correct me if i'm wrong, but I think you can use ob_start() at the beginning of your page and that will allow you to redirect via PHP even if headers are already sent.
You should redesign your application, to make it more sensible.
It should start output only when it necessary, not just every time this file is called.
You have to modify all your code by dividing every script to 2 parts. First part will contain all data manipulations and second will contain output only. It will be better to put the latter one into separate file, called template. thus your profiles php will looks like
include 'dbc.php';
//some code that sends headers, gets data etc
//after it's all done, call your template files
include 'top.php';
include 'profiles.tpl.php';
include 'bottom.php';
there can be some variations, but the main idea would be the same: separate your data manipulation from data presentation.
From the header documentation:
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.
The headers are being sent before your call to header() due to output from the script. You just need to track down where the output is coming from.
I see it that you have two options
1) You try to ensure that your headers are not set until after you have executed your code. Your headers being set before you have even determined what you are sending back to the user suggests your code is a little messy, or you are constrained in some way.
2) You can use your javascript solution. However, I would consider this as a hack, rather than an appropriate solution. Try to figure out the answer to why you can't use approach 1.
EDIT: A code example added
Your code should look something like this
<?php
// perform logic to determine if you need to do the redirect or not.
// if you do need to redirect, set the following
$iNeedToRedirect = true;
// if you do not need to redirect, set the following
$iNeedToRedirect = false;
if ($iNeedToRedirect) {
header("Location: profil.php?id=" . $show["id"]");
die();
}
// if code gets here, carry on as normal
include("dbc.php");
include("top.php");
... etc etc etc
?>

Categories