This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
The following code is not working even after having inserted ob_start(), and ob_flush();
I keep getting the PHP headers already sent error
<?php
ob_start();
include("/home/www/pheincl/config.php");
include("/home/www/pheincl/common_functions.php");
$num = $_SERVER['HTTP_X_UP_CALLING_LINE_ID'];
if($num == null)
{
$num = $_SERVER['HTTP_X_MSISDN'];
if($num == null)
{
$num = $_GET["msisdn"];
}
}
if(strlen($num) > 3)
{
$sql="select count(*) from members where msisdn='$num'";
$r=fetch($sql);
if($r[0] > 0)
{
$r1=fetch("select pin from members where msisdn='$num'");
if(strlen($r1[pin]) > 2)
{
header("Location:http://location1.com?msisdn=$num&pin=$r1[pin]");
}
}
else
{
header("Location:http://location2.com&msisdn=$num");
}
}
else
{
header("Location:location3.com/phe/log.php");
}
ob_end_flush();
?>
UPDATE: After some further testing it looks like this problem is specific to my servier. Someone I know put this on their server and it worked fine
use notepad++ and set encoding to UTF8 without BOM
your BOM (Byte Order Mark) is probably what's causing it
EDIT:
Make sure you do it on all included files
Before any header function, the script shouldn't print anything. That means no echo, no html code outside php tags etc.
So either that sql echoes some error, or your include files do something similar.
Something is sending some output to the browser before your header code executes. Look for any errors output to the screen or any print or echo statements.
You can try to delete the final ?> to avoid the problem. Sometimes this fixes the problem.
Related
I got this error message when i run my php CodeIgniter project:
A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by
(output started at
C:\AppServ\www\tree\application\models\mtree.php:17)
Filename: core/Common.php
Line Number: 442
line 17:
echo $row->members_id . "</br>";
this is my model function:
function convert_all() {
$this->db->empty_table('table1');
$this->db->empty_table('table2');
$this->db->query("INSERT INTO `table1` (`members_id`, `members_username`);
$query = $this->db->get('table2');
foreach ($query->result() as $row) {
if ($row->members_id > 1) {
echo $row->members_id . "</br>";
}
if ($this->isadvanced($row->members_id, $row->members_direct_id)) {
$this->insert_to_right($row, $row->members_direct_id);
} else {
$this->insert_to_left($row, $row->members_direct_id);
}
}
}
While using codeigniter, its best recommended that you echo only in views.
Echoing anywhere randomly sends some data to browser, after which you can't modify headers (this includes attempt to redirect, set content-type, etc)
You should re-organize your code, such that, echo are done within views only. This will solve your header issues in Codeigniter.
This also includes extra whitespaces at the end after the closing brace "} ?>" in non-view php files.
I think it will be helpfull
Use $config['sess_save_path'] = sys_get_temp_dir(); instead of $config['sess_save_path'] = NULL; in your Application/config/config.php file
You can't display anything before the header function is called. You should not display anything form model or controller to avoid this kind of error. If you want to display something form the controller or model then you should store the output to the buffer instead of sending it to the browser. You can store the output to the buffer using ob_start() function before header() function is called. Then you can do something like this
if(true)
{
header("Location:http://google.com");
}
else
{
ob_end_flush();
}
this was your issue - echo $row->members_id . ""; -- as the above answers say, don't echo something in your controllers, push to do it in the views - always
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I am getting this error:
Warning: Cannot modify header information - headers already sent by (output started at /removed/loginform.php:2) in /removed/loginform.php on line 24
I understand that I am getting the error when I try to set a cookie, and it's because setcookie can't have any output before it... the problem is, there is no output before it (At least from what I can see). It is saying that "< ?php" is a header, and I don't understand that. If setcookie can only be used in PHP and < ?php is a header, how is it even possible to use setcookie without getting this header error?
My code:
<!--Database Connections-->
<?php include "../../includes/dbpractice_con.php"; ?>
<?php
//Declare variables
$username = "";
$password = "";
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") { //Retrieve from form when submit is clicked.
//Escape to prevent SQL injection.
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$check = mysqli_query($connection, "SELECT * FROM users WHERE username='$username' AND password='$password'");
$rowCount = mysqli_num_rows($check);
if ($rowCount == 1) {
$cookieExpiration = time() + 757368000; //1 year
setcookie("username", $username, $cookieExpiration);
} else {
$message = "Invalid username or password. <br/>Don't have an account? Click here to register.<br/><br/>";
}
}
?>
<html>
<!--Database Connections--> is HTML output, even if it is just a comment. Remove that and try again.
EDIT:
There is also a space between the PHP blocks. Try putting the include in the main PHP block.
Generally that means you have sent something to client prior to setcookie() call.
Do simple test:
<?php
ob_start();
include "../../includes/dbpractice_con.php"; ?>
# ... rest of your code... #
and before setcookie() call add line
ob_get_clean();
just to be sure that no output was made earlier.
Anything outside of <?php ?> is HTML and is sent to user. So this
<!--Database Connections-->
<?php include "../../includes/dbpractice_con.php"; ?>
outputs <!--Database Connections--> as HTML comment. Another possible output is here
<?php include "../../includes/dbpractice_con.php"; ?>
<?php ...
at least you have new line character between two PHP tags, which is also unwanted output.
You can't have anything to echo, print_r, var_dump data before cookieset() call, check manually for these functions.
Always check all included scripts (with include, require, etc).
BE SURE THEY START WITH <?php WITH NOTHING BEFORE and END WITH ?> FOLLOWING NOTHING.
this is good example:
<?php
// some lines
?>
these aren't
something<?php ?>
or
<?php ?>something
or
<?php ?>
(if file has been saved as UTF-8).
Look at your dbpractice_con.php, check is it saved as ANSI (from notepad check with save as dialog), be sure that everything is between and no one character is before and after the tags. Don't use multiple tags in same script because it increases risk of unwanted output.
Try this:
<?php
// Database connections
include "../../includes/dbpractice_con.php";
//Declare variables
// ... proceed with code ...
If this doesn't work then the problem is probably in dbpractice_con.php
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I am developing an mobile application using jquery mobile and PHP. I encounter a warning when i submit the form for checking the credentials.
Warning: Cannot modify header information - headers already sent by (output started at /home/u387779804/public_html/walcliff/index.php:6) in /home/u387779804/public_html/walcliff/index.php on line 48
The php code
<?php session_start();?>
<?php
if(isset($_POST['sec']))
{
$s=$_POST['sec'];
$user="u387779804_a";
$password="arunvenu123";
$server="mysql.1freehosting.com";
$con=mysql_connect($server,$user,$password);
mysql_select_db("u387779804_a",$con);
$query=mysql_query("select * from details where secretnum='$s'");
if (!$query) { // add this check.
die('Invalid query: ' . mysql_error());
}
$info=mysql_fetch_array($query);
if($_POST['sec'] == $info['secretnum'])
{
$_SESSION['fid']=$info['fid'];
$_SESSION['phone']=$info['phone'];
$_SESSION['name']=$info['name'];
$_SESSION['email']=$info['email'];
$_SESSION['address']=$info['address'];
$_SESSION['city']=$info['city'];
header('Location:list.php');
}
else
{
echo '<script> alert("Wrong User name password")</script>';
}
}
?>
I have attached the screen shoot also.Any possible solutions for this problem is welcomed! Thanks in advance!
The second line is actually your problem here. That's a linebreak, which is considered starting of the body and thus means no-more headers can be sent.
Change the first three lines to the following:
<?php ob_start(); session_start(); ?>
<?php
if(isset($_POST['sec']))
Or, better yet:
<?php
ob_start();
session_start();
if(isset($_POST['sec']))
This question already has an answer here:
Enabling php.ini for backward compatibility
(1 answer)
Closed 9 years ago.
Ok so i want to have an include code on my index.php page that will include all of the other html pages within it. I used to do this using an id?=link.html link and this:
<?php
$id = $HTTP_GET_VARS['id'];
if ( !$id || $id == "" )
{
$number=10;
include("news/show_news.php");
}
else
{
include "$id";
}
?>
but apparantly http_get_vars is unrecognized or something? How can I fix this so that it will work? Or if things have changed, why should I not use this kind of thing for includes?
You can use $_GET to fetch the query string parameter by GET request, e.g.
index.php?id=123
The id value can be obtained by $_GET['id'].
p.s. your PHP codes are really old.
solved with the following:
<?php
if (!empty($_GET['id'])) {
$id = $_GET['id'];
$id = basename($id);
include("$id");
} else {
include("news/newsfilename.php");
}
?>
and
<a href="index.php?id=pagename.html">
Page Name
</a>
as the html
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
Please save me. I know that this question has been asked many times, however, I can't seem to find solutions that are relevant to my situation.
The problem: Warning: Cannot modify header information - headers already sent by (output started at /.../Sites/st.ambulance/resources/views/login.view.php:32) in /.../Sites/st.ambulance/resources/controllers/tables_.php on line 47
This is the code block with line 32:
<label>Month</label>
<select name="dob_month">
<?php for($i=0,$j=1;$i<sizeof($month);$i++,$j++){ ?>
<option value="<?php h($j) ?>"><?php h($month[$i]) ?></option> //line 32
<?php } ?>
</select>
The definition of the h function:
function h($s){
echo(htmlspecialchars($s,ENT_QUOTES));
}
This is tables_.php:
<?php
$error = "";
if(isset($_POST['guest_tables'])){
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
$guest = array();
$volunteer = array();
$guest = isset($_POST['guest']) ? $_POST['guest'] : null;
$volunteer = isset($_POST['volunteer']) ? $_POST['volunteer'] : null;
$seat_array = array($volunteer['seat_no'].$volunteer['table']);
$seat_count = 0;
$table_seat_error = "";
if($form->is_seatOccupied($volunteer['table'],$volunteer['seat_no']) != "")
$table_seat_error .= "Seat (".$volunteer['seat_no'].")
at table (".$volunteer['table'].") is currently occupied";
if($_SESSION['no_guests'] >= 1){
if($guest && $volunteer){
foreach($guest as $gue){
$seat_table = $gue['seat_no'].$gue['table'];
for($h=0;$h<sizeof($seat_array);$h++){
if($seat_table == $seat_array[$h] )
$seat_count = $seat_count + 1;
}
if($form->is_seatOccupied($gue['table'], $gue['seat_no']) != "")
$table_seat_error .= "Seat (".$gue['seat_no'].")
at table (".$gue['table'].") is currently occupied";
$seat_array[] = $seat_table;
}
if($seat_count == 0){
if($table_seat_error == ""){
for($d=0;$d<$_SESSION['no_guests'];$d++){
$_SESSION['guests'][$d]['table'] = $guest[$d]['table'];
$_SESSION['guests'][$d]['seat'] = $guest[$d]['seat_no'];
}
$_SESSION['volunteer']['table'] = $volunteer['table'];
$_SESSION['volunteer']['seat'] = $volunteer['seat_no'];
$form->set_guests($_SESSION['guests']);
$form->set_volunteer($_SESSION['volunteer']);
header('location: /branch/menus.php'); //line 47
exit();
}
else{
$error = $table_seat_error;
}
}
else{
$error = "You have selected the same seat for two or more
people: one person, per seat, per table. Only.";
}
}
}
else{
$_SESSION['volunteer']['table'] = $volunteer['table'];
$_SESSION['volunteer']['seat'] = $volunteer['seat_no'];
if(!$form->is_seatOccupied($_SESSION['volunteer']['table'],
$_SESSION['volunteer']['seat']) != ""){
$form->set_volunteer($_SESSION['volunteer']);
header('location: /branch/menus.php');
exit();
}
}
}
}
?>
EDIT: would it help to know that I'm trying to handle multiple forms on a single page?
Line 47 modifies the response headers:
header('location: /branch/menus.php'); //line 47
Line 47 cannot be executed because the headers have already been sent, which happened to occur on line 32. All that happened on line 32 was that PHP decided it had enough content in the response to start sending it back to the browser.
Generally, if you want to modify the headers (whatever you're doing on line 47), you need to do it at the very beginning of the file.
This is a good time to learn about the MVC design pattern - it would eliminate the possibility of this issue in the future. In MVC, the Controller executes first, and prepares everything for the View. So, you can modify your headers all you want in the Controller, and they won't be sent until during or after the View is processed.
EDIT: It looks like you are using MVC, but somehow your view is executing before the controller has started (or perhaps finished)... that shouldn't happen! Unfortunately, the code you've posted doesn't illustrate how either the controller or view are being accessed... but they're being accessed out of order.
As TRiG point out in the comments below, you probably want to insert an exit() statement after line 47 as follows:
header('location: /branch/menus.php'); //line 47
exit();
This will cause the server to immediately send the Location redirect to the browser, and the request/response cycle is complete. All your header('Location: ...'); calls should be immediately followed by exit();. This doesn't fix the issue at hand, but it is very important.
switch on output buffering, locate php.ini and look for / uncomment / change / add the following line:
output_buffering = On
edit: and include a line saying ob_start(); in some initial include, like some common init.php or database.php
edit^2: the ob_start is not needed (anymore?); this works, save as test.php and request. Seeing is believing.
Output has started
<?php
header("Content-Type: text/plain");
?>
The point is that in HTTP the response of the server consists of 2 parts: the headers and the body.
The headers contain information about the content, the connection etc, like what type of content, e.g.
Content-Type: text/html
or
Content-Type: image/jpeg
indicating it's html or jpg. Without it, the browser wouldn't be sure what to do with the content. Of course once PHP has to start outputting the body part of the response, there's no way to change the header. So you can either do anything header-related first before emitting any byte of the body, or you could instruct php to hold it's breath and emit the body only when the script is done, or when you say so. And that's what they call output buffering.