PHP header not redirecting - php

I've been trying to forward a url after checking two initial conditions. It's a simple bit of code. And what I am trying to achieve is check two initial conditions that will be loaded from a CSV file then if the conditions meet I want to forward the user to a different page.
This is my CSV file contents
katz,26.06.2011,http://www.google.com
<?php
error_reporting(E_ALL|E_STRICT);
ini_set("display_errors", "On");
$name_value=$_GET['query'];
$fh = fopen('db.csv', 'r');
$now = date("d.m.Y");
$data=fgetcsv($fh);
$name=$data[0];
$date=$data[1];
$url=$data[2];
if($name_value == $name AND $date>=$now)
{
header("Location: $url");
}
else
{
echo("not successful<br>");
}
echo "name1 is $name_value<br>";
echo "name2 is $name<br>";
echo "date is $date<br>";
echo "now is $now<br>";
exit;
?>
I am getting this warning
Warning: Cannot modify header information - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/x/client_authorized.php:5) in /Applications/XAMPP/xamppfiles/htdocs/x/client_authorized.php on line 17
Where am I going wrong ?

You cannot send headers after the output is already started (the headers have to be the first things out the door).
Make sure you don't have anything (including whitespace -- like new lines, tabs, and space) before your opening <?php.

You should also call exit() or die() after the header function call.
see redirect examples here http://us2.php.net/manual/en/function.header.php

You can try with output buffering on
$ <?php
$ ob_start();
$ --------
$ --------
$ ob_end_flush();
$ ?>

Related

Cannot Modify Header Information Headers Already Sent

I know this question has been asked many times but I have seen so many different answers and have tried them all and none have worked for me. So let me provide you with my specific context, and see what you recommend:
I am developing on Mac OS X El Capitan. I am using PHP version 5.5.31. error message
I have output buffering turned on in my php.ini file. I have obsessively checked there is no white space before the header is sent. Here are the lines the code is referring to:
(edit_subject.php:6)
<?php require_once("../includes/session.php");?>
<?php require_once("../includes/db_connection.php");?>
<?php require_once("../includes/functions.php");?>
<?php require_once("../includes/validation_functions.php");?>
<?php find_selected_page();?>
<?php
if(!$current_subject){
**redirect_to("manage_content.php")**;
}
?>
(edit_subject.php:38)
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) >= 0) {
// Success
$_SESSION["message"] = "Subject edited succesfully.";
**redirect_to("Location: manage_content.php");**
} else {
// Failure
$message = "Subject update failed.";
}
(functions.php:3)
<?php
function redirect_to($new_location) {
redirect_to("Location: . $new_location");
exit;
?>
I've been pulling my hair out for the last 48 hours. I'd appreciate some guidance here.
Thanks,
Chris
The following line is triggering the warning (functions.php line 3):
redirect_to("Location: . $new_location");
It is attempting to send headers, after something has already been output (probably another error/warning considering your syntax is broken). Check your error logs.
try flushing the buffer before redirecting. the problem arises if there is already something outputted and you try changing the header in this case by redirection.
You can use ob_start() at top, and ob_end_flush() to flush before changing the header.
Note: Flushing the buffer only hides the problem, its not the solution. There's some piece of bad practice of coding, try figure that out.

Cannot modify header information error recieved [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP error: Cannot modify header information – headers already sent
Headers already sent by PHP
if ((isset($username)) && (isset($userid))){
}else{
header( 'Location: teacherlogout.php' ) ;
}
I have an if/else statement above, what I want to do is that if the else statement is met, then navogate to the teacherlogout.php page. But instead of this I am getting an error stating:
Warning: Cannot modify header information - headers already sent by (output started at /:431) in / on line 1654
I don't quite get what I am doing wrong? Line 431 is just a var qremain = <?php echo (int)$_SESSION['textQuestion']; ?>; line of code. Line 1654 is the header( 'Location: teacherlogout.php' ) ; line. What is happeing here?
UPDATE:
Actually will it be better to use ajax to navigate to teacherlogout.php script in background as so:
<?php
}else{
echo "Please Login to Access this Page | <a href='./teacherlogin.php'>Login</a>";
?>
<script type="text/javascript">
$.ajax({
url: "teacherlogout.php",
async: false,
type: "POST",
});
</script>
<?php
}
?>
Cause:
This error is caused if the your PHP scripts are printing to the browser prior to sending headers. A common example is printing the html tags prior to starting a session, or setting a cookie. The error tells the line that needs to be altered (in this case, it is on line 431).
Resolution:
To resolve this error remove the lines from the PHP code that are printing to the browser prior to sending headers.
Another common cause for this error is white space either at the beginning or end of the file. The fix is to remove that whitespace from the file. Read the error message carefully. It says output started at ... followed by a file name and a line number. That is the file (and line) that you need to edit. Ignore the second file name - that is only a file that included the file that has the whitespace. The first file is the one you have to edit, not the second one.
Make sure there isn't any whitespace at the top of your file. For example, if you have a blank line at the top, you will get this error.
(Blank Line Here)
<?php
if ((isset($username)) && (isset($userid))){
} else {
header( 'Location: teacherlogout.php' ) ;
}
?>
header( 'Location: teacherlogout.php' ) ;
The above function (header) only works if there has been no echo (output to screen). Check if something is printed before the function call.
HTML newline (usually considered as a whitespace) may also cause problem. Like a blank new line on page start.

Redirect Function Php

I have a function, 'redirect_to()' written on php script that is called after a successful update to a page on my custom CMS. It works fine on the localhost, but when I try it on my actual live domain I get the following error message:
Warning: Cannot modify header information - headers already sent by (output started at /hermes/bosweb/web119/b1192/ipg.typaldosnetcom/edit_listing.php:7) in /hermes/bosweb/web119/b1192/ipg.typaldosnetcom/includes/functions.php on line 20
Here is the code for the redirect_to() function:
function redirect_to ($location = NULL) {
if ($location != NULL) {
header("Location: {$location}");
exit;
}
}
I've made sure to call the function before I output any HTML, so I'm not sure what the problem really is.
My question: Why am I receiving this error?
It's not lying. You've output something before getting to this point. Check the locations mentioned in the error messages.
Show us the first 25 lines of each of the files mentioned.
you already sent your output to the page before you set the header. first you need to set the headers and then can the output come.
It can even be a whitespace.
It means something was already outputted on the suggested line. Try going there and see what it does.
Try pasting the surrounding code on that position for a better clarification if you can't find the problem yourself.
One common cause is to have a line after a php file you're including...
Simple solution: remove the closing php tag "?>" from all files as it's not needed..
You can test if you have a character before the opening php-script tag by removing any closing php-script tag. This way you are sure there isn't any character left (it's not needed).
Use output buffering:
<?php
ob_start();
// Test buffered output.
echo 'hello world';
function redirect_to ($location = NULL) {
if ($location != NULL) {
header('Location: ' . $location);
exit;
}
}
// rest of php file here
ob_end_flush();
?>
Docs: ob_start() and ob_end_flush()

How do you format php error messages? they don't respect css

Whenever PHP outputs an error message it disregards css and a beautifully designed page by outputting the message at the top of the page removing anything that stands in its way.
for example
some code} else {
echo "error, please do something!";
How do I get it to (or ask it nicely) to output the text inside a div that already exists inside my css so that it will obey the formatting and alignment rules that comes with that div.
You can use the following php.ini settings:
error_prepend_string = "<div class='error'>"
error_append_string = "</div>"
Or something to that effect.
EDIT
Actually, I just realized the "error" you're talking about involves an echo/print out. Here's the problem.
You're printing (echoing) the string error DIRECTLY TO the output buffer (which sends the HTML to the browser when you're finished running all your code). echo() and print() sends what you are echoing/printing straight out, unless it's in an output_buffer block (I won't confuse you with details on that).
So, you're managing your regular html/text output in such a way as to NOT print the page content out to the output buffer, but in this case you are using an echo, which sends the string data directly to the buffer AT THAT MOMENT.
For instance:
Your problem in a simple example
<?php
$mystr = "<html>";
$mystr .= "<body><h1>Hello World</h1></body></html>";
echo "<head></head>";
echo $mystr;
?>
Which would give me on output to the browser:
<head></head><html><body><h1>Hello World</h1></body></html>
I am storing the string data, but echoing the HEAD block before I echo the other html data.
What I need to do instead:
<?php
$mystr = "<html>";
$mystr .= "<head></head>";
$mystr .= "<body><h1>Hello World</h1></body></html>";
echo $mystr;
?>
Which would give me on output to the browser:
<html><head></head><body><h1>Hello World</h1></body></html>
I am storing the string output (your error, in this case) until I need to output it later. This is what you need to know, and accomplish in your code.
I would investigate error_reporting(0)/display_errors, error_get_last, and set_error_handler.
http://www.php.net/manual/en/function.error-reporting.php
http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
http://php.net/manual/en/function.error-get-last.php
http://www.php.net/manual/en/function.set-error-handler.php
So that you could stop sending all errors immediately to the output buffer (which is why it's at the top of the page), and then capture, store and present your errors.
error_reporting(0);
set_error_handler('phpLogError');
function phpLogError() {
$error = error_get_last();
if ($error['type'] == 1) {
//do your stuff
}
}
function phpGetLoggedErrors() {
// return your prettified html errors
}
Or, in other words...
php_error_handle.php
<?php
$GLOBAL['_logged_php_errors'] = array();
error_reporting(0);
set_error_handler('phpLogError');
function phpLogError() {
global $_logged_php_errors;
$error = error_get_last();
if ($error['type'] == 1) {
$_logged_php_errors[] = "<span>$error</span>";
}
}
function phpGetLoggedErrors() {
global $_logged_php_errors;
return "<ol><li>".implode('</li><li>',$_logged_php_errors)."</li></ol>";
}
?>
other.php
<?php
require_once 'php_error_handle.php';
// other stuff, pages included/required, etc...
Just make sure this require_once happens at the first line of code.
Extending #mario above, I've used this at the top of my php file (in dev, not production of course!) which works great. Even in Wordpress admin files!
ini_set('error_prepend_string',"<div class='error'>") ;
ini_set('error_append_string',"</div>") ;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Try...catch
http://php.net/manual/en/language.exceptions.php
You can make the error echo in your own css.
echo '<div class="yourerrorclass">error, please do something!</div>';
If it is in the wrong place in the output, that is because you output the error too soon. The entire HTML is outputted sequentially by PHP. If you output the error before any of the other HTML, the error will be on the top of the page and will actually make your HTML invalid.
Displaying errors to screen should be entirely suppressed when running in production, instead log them to file for checking, and fixing. There are details, and the suggested settings in the php.ini file.

header php not working

well am trying to use the header to send information, but my html is already outputting information, I tried to fix the problem by using the ob_start() function to no avail
ob_start();
require('RegisterPage.php');
if(isset($_POST['register']))
{
if(register($errormsg,$regnumber))
{
$to = $_POST['email'];
$subject = "Registration";
$txt = "You need to return to the Classic Records homepage and enter the number given in order to finish your registration ".$regnumber."";
$headers = "From: registration#greenwichtutoring.com";
mail($to,$subject,$txt,$headers);
header('Location:emailNotification.html');
}
else $error=$errormsg;
}
ob_end_flush();
Check if any scripts included before the ob_start() function are outputting HTML. Sometimes an included file can contain a space after the PHP closing tag. That space will be outputed as is. To fix this, leave the PHP closing tag from your file.
E.g.
<?php
class someClass {
...
}
?><whitespace>
Can give you some good headaches. This is fine and fixes the above problem:
<?php
class someClass {
...
}
You need to call ob_start before any output has happened. So, for example, as the first statement in your main PHP script file (make sure that there is nothing before your <?php like some whitespace of a BOM).
Here you're trying to redirect to a different page and show a message. It can't happpen.
Instead, try using a link, or echo-ing:
<meta http-equiv="Refresh" content="(delay in seconds);URL=(destination)">
in your <HEAD>.
In your case, you want this to be instant, so:
<meta http-equiv="Refresh" content="0;URL=emailNotification.html">
The better alternative, is simply to not require the page until after the if.
If i remember correctly the header(); is executed at the end of the execution of the php script , so try moving it in the beginning of the if
Cheers
You have to buffer the html output, not the php logic. E.g:
ob_start();
<html>...
/* PHP */
...
ob_end_flush();
header('Location: http://www.foo.com/emailNotification.html');
1 space after Location:
and
full url
With Your Dynamic HTTP_HOST
header('Location: http://'.$_SERVER["HTTP_HOST"].'/emailNotification.html');
Chris.

Categories