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.
Related
This simple, simple code fails to return HTTP response code 500 if there is a blank line at the end of a required PHP file in an AJAX POST endpoint, called cursed.php. With the blank line I always get status code 200. When I remove the blank line I get status code 500, as expected.
Here is the smallest code that reproduces it for me:
index.php
<script>
const xhr = new XMLHttpRequest();
xhr.open("POST", 'ajax.php', true);
xhr.onreadystatechange = function() {
console.log(this.status);
}
xhr.send();
</script>
ajax.php
<?
require_once('./cursed.php');
http_response_code(500);
die("foo");
?>
And this cursed file: cursed.php
<?
?>
See that blank line at the end of cursed.php? If I leave it, the callback always returns 200 OK. If I remove it, it fails and prints status 500. I've googled the heck out of this and found nothing except discussions about why you should or should not have blank lines at the end of files.
I'm running PHP7.2 on Ubuntu 18.x.
Let's take a look at the effect of your require statement. When PHP encounters an include or require statement it terminates the current PHP block with an implicit ?>. Then it starts the included file, embedding what it finds. Then it starts a new PHP block with an implicit <?php (or <?).
With a trailing line after the closing ?> in your included file it gives this result:
<?
?>
<? // require statement here
?>
<?
http_response_code(500);
die("foo");
?>
Notice that blank line in the middle? That is treated as output to be sent to the client. Since it appears before your http_response_code(500); the headers are already sent and PHP can't change the status code. Ergo, your response is a status of 200 with content of a blank line.
Omit the trailing ?> in your PHP code files. If PHP doesn't find a closing delimiter it will assume an implicit ?> after the very last line, thus eliminating the problem.
From the PHP Manual
If a file contains only PHP code, it is preferable to omit the PHP
closing tag at the end of the file. This prevents accidental
whitespace or new lines being added after the PHP closing tag, which
may cause unwanted effects because PHP will start output buffering
when there is no intention from the programmer to send any output at
that point in the script.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I am still getting that error when I run my code. Here is my code.I removed all white spaces as well.my form on my html goes to my php (action="lib/login.php") file to check if user exists. If it exist, then redirect.
dbconnect.php just connects to my database. can anyone help?
FOLDER Layout:
lib
-dbconnect.php
-login.php (code located below)
index.html
<?php
require_once("dbconnect.php");
$loginuser = $_POST['username'];
$loginpw = $_POST['password'];
$usertable = "Users";
$users="Username";
$pw="Password";
$query = "SELECT $users, $pw FROM $usertable WHERE $users='$loginuser' AND $pw='$loginpw'";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if ($num_rows>0) {
header("Location:../index.html");
exit();
}
?>
This message appears if you try to send a HTTP header after you already made some output. This is because in HTTP there comes first the headers and then the body. As ouput goes to the body, it is impossible to send headers anymore after output.
As there is no echo, print or whatever output function used in your code, output can be generated by
A PHP errror message
Content before the opening <?php
To 1:
The ob_* set of functions is a good way to catch all output a script regardless if this are error messages or regular output. So you could add the line:
ob_start();
direct after the opening <?php tag.
Then before the call to header() add:
if(ob_get_size() > 0) {
// there was an error, display it and exit
ob_end_flush();
die();
}
Note that in production environment you should disable the display of error messages at all as they can contain sensitive information. You can do by settings display_errors in php.ini to 0 or per script by:
ini_set('display_errors', 0);
To 2:
Assuming that the code you have posted is the complete content of the php file (no spaces or empty lines before <?php ) it could be that you have a problem with the UTF-8 BOM char. BOM means byte order mark and is used internally by the utf-8 encoding. And it is not visible in a text editor. :)
To remove it, there are several solutions out there.. will google one for you ..... http://www.w3.org/International/questions/qa-byte-order-mark.en.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()
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();
$ ?>
I am a newbie to PHP development. I tried following code sample from PHP5 Power Programming book:
<?php
require_once 'DB.php';
require_once 'PEAR.php';
require_once 'Auth.php';
$auth_options = array(
'dsn' => 'mysql://username:password#localhost/database',
'table' => 'users',
'usernamecol' => 'username',
'passwordcol' => 'password',
'db_fields' => '*',
);
PEAR::setErrorHandling(PEAR_ERROR_DIE);
$auth = new Auth('DB', $auth_options);
$auth->start();
if (!$auth->getAuth()) {
exit;
}
if (!empty($_REQUEST['logout'])) {
$auth->logout();
print "<h1>Logged out</h1>\n";
print "Log in again\n";
exit;
}
print "<h1>Logged in!</h1>\n";
if (!empty($_REQUEST['dump'])) {
print "<pre>_authsession = ";
print_r($_SESSION['_authsession']);
print "</pre>\n";
} else {
print "<a href=\"$_SERVER[PHP_SELF]?dump=1\">Dump session</
?a><br>\n";
}
print "Log Out\n";
?>
there are several problems I am having with this code:
First, when I log in I get following warnings:
Warning: session_regenerate_id() [function.session-regenerate-id]: Cannot regenerate session id - headers already sent in /usr/local/php5/lib/php/Auth.php on line 830
Warning: Cannot modify header information - headers already sent by (output started at /home/myaccount/www/www/test.php:2) in /usr/local/php5/lib/php/Auth.php on line 858
Why am I getting these?
Second, when I click on the Dump session link, it asks me to log in again - i.e., does not recognize that I am already authenticated and logged in.
Could some please explain these to me? Thanks.
Sessions are maintained by a cookie passed between the server and the browser in each request containing a session identifier PHP generates. Since cookies are part of HTTP headers, creation of a session by sending a cookie has to happen before your script outputs any content.
That includes whitespace, which is the likely culprit for your error. There can be no whitespaces, including blank lines, spaces, BOMs at the top of the file before the opening <?php tag, including in the included files.
The second error is a side effect of the first error, so once you fix that, it'll go away as well.