Redirect Function Php - 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()

Related

Cannot modify header information [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
My problem is that I have a class with a function inside of it, and I get;
Warning: Cannot modify header information - headers already sent by (output started at /home/user/public_html/inc/class.php:105) in /home/user/public_html/inc/facebook/login.php on line 21
When the page I'm using it on redirects a user with the header(); tag. The class is;
class mysql {
private $user;
private $pass;
private $db;
public function __construct($user1, $pass1, $db1) {
$this->user = $user1;
$this->pass = $pass1;
$this->db = $db1;
$this->connect();
}
public function connect() {
$this->connection = mysql_connect('localhost', $this->user, $this->pass);
$select = mysql_select_db($this->db, $this->connection);
}
public function query($x) {
return mysql_query($x);
}
public function fetch($x) {
return mysql_fetch_array($x);
}
public function num($x) {
return mysql_num_rows($x);
}
}
Line 105 is the;
return mysql_fetch_array($x);
And the file trying to do the header redirect just includes this file at the top of the page and does the header lower down.
Thanks in advance.
What is triggering this error?
This error is triggered when some code has already output to the "screen" before you call the header function. Headers must be set before you output anything.
See the description from the header() PHP manual page:
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.
I am not outputting anything so what gives?
I would say that your code is generating an error somewhere. Try setting:
ini_set('display_errors', true);
ini_set('error_reporting', ~0);
In your index.php file as the very first set of commands.
Another possibility is that something somewhere is outputting a space or line return character. You cannot have any output of any kind before you call the header() function.
Possible solutions
There are two ways to fix this.
Use output buffering to catch anything that might be echoed before you have set your headers
Stop the code from outputting anything prematurely although this is a little more brittle
Option 1
To implement solution 1 you would put a call to ob_start() at the very beginning of your code (at the top of your bootstrap file or index.php usually).
Then once all logic has been completed and you are ready to output you would call ob_end_flush() to output everything in the buffer. Usually this would be at the very end of your index.php or bootstrap file.
Option 2
Zend Framework has the following in their coding guidelines to help mitigate the accidental output of new lines and spaces. See http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html#coding-standard.php-file-formatting.general:
For files that contain only PHP code, the closing tag ("?>") is never permitted. It is not required by PHP, and omitting it´ prevents the accidental injection of trailing white space into the response.
When the page I'm using it on redirects a user with the header(); tag. The class is;
That's the problem. You need to put ob_start(); right at the beginning of the file with header();.
That line shouldn't output anything, so that means that output was started because a warning or notice was printed. Fix the problem.
Alternatively, you gave use the wrong source file.
Disable wanrings on php.ini .Those are warnings , if you have access in your php.ini , modify the following
error_reporting = E_ALL & ~E_NOTICE & ~E_DEPRECATED
when in development
display_errors = On
when you'll be in production don't forget to
display_errors = Off
Don't forget to restart apache when you change php.ini
I didn't say to disable errors ,disable only warnings,
Cannot modify header information means you have outputed something before the header.remove all spaces before header();

PHP header not redirecting

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();
$ ?>

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.

While loop combined with header() in PHP

I've written a script to geocode some points which has a structure basically like this:
//get an unupdated record
$arr_record;
while(count($arr_record) > 0)
{
//strings are derived from $arr_record
geocode($string1);
geocode($string2);
geocode($string3);
array_pop($arr_record);
}
function geocode($string) {
//if successful
update($coords)
}
function update($coords) {
//update the database
header('Location:http://localhost/thisfile.php')
}
The trouble is that even when the geocode is successful and the database is updated, and teh header resent, the script still goes back into the while loop without reloading the page and starting again on a new record.
Is this normal behaviour for PHP? How do I avoid it behaving like this?
After header() use die(); to terminate the script and output.
How do I avoid it behaving like this?
Put exit() after header().
another effective way is not to send headers directly in a loop. which is not proper (i couldn't find in php.net manual but i remember it was discussed before in phpusenet).
it may act unexpected in different php versions. & different apache ver. installations.
php as cgi will make problems too.
you can assign it to return as string then you can send header later...
function update($coords) {
//update the database
if(statement to understand update is ok){
return 'Location:http://localhost/thisfile.php';
} else {
return false;
}
}
if($updateresult=update($cords)!=false){ header($updateresult); }
but if i were you... i would try to work ob_start() ob_get_contents() ob_end()
because those are the excellent way to control what will be sent to browser. normal mimetypes or headers... whatever. it's better way while working with headers & html output at the same time.
ob_start(); /* output will be captured now */
echo time(); /* echo test */
?>
print something more...
<?php /* tag test */
/* do some stuff here that makes output. */
$content=ob_get_contents();
ob_end_clean();
/* now everything as output with echo, print or phptags.
are now stored into $content variable
then you can echo it to browser later
*/
echo "This text will be printed before the previous code";
echo $content;

Categories