Cannot modify header information - Baffled [duplicate] - php

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I'm getting the typical 'Warning: Cannot modify header information - headers already sent by (output started a... line 14)'. This is usually due to an echo statement before the header() method, but confusingly I don't have any echos being called before the header() itself. Please can you tell me where the output is occuring and why as its currently baffling me, and further, so I can fix this in the future.
Line 14 is a line within the content div:
<p>Lorem ipsum...</p>
Thanks in advanced,
Max.
<html>
<head>
<title></title>
<!-- CSS -->
<link ... />
</head>
<body class="index not-admin">
<div id="wrapper">
<div id="logo"></div>
<div id="headerInvoice">
</div>
<div id="content">
<form name="signup" action="" method="GET">
<input name="email" type="email" placeholder="Email Address" />
<input type="submit" title="Submit!"/>
</form>
<?php
if($_SERVER['REQUEST_URI'] == '/betas/') {
header('Location:http://betas.maxk.me');
}
if (isset($_GET['email'])) {
$email = $_GET['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = 'Email Address is invalid.';
}
else {
mysql_connect('localhost', '...', '...');
mysql_select_db('...');
$email = mysql_real_escape_string($email);
if (mysql_num_rows(mysql_query("SELECT * FROM testers WHERE `email_address` = '$email'")) < 1) {
mysql_query("INSERT INTO `testers` (`email_address`,`accepted`) VALUES ('$email','0')");
$error = !mysql_error()? 'Success!' : "We came across an error, please try again! " . mysql_error();
}
else {
$error = 'Sorry, but you have already signed up! Please try emailing me to see if I need any testers through my homepage.';
}
}
echo $error;
}
?>
<br />
Login
</div>
<div id="footer">
</div>
</div>
</body>
</html>

The problem is here:
if($_SERVER['request_URI'] == '/betas/') {
header('Location:http://betas.maxk.me');
}
Calling header after any html in a file will cause an error. The PHP documentation explains this in depth.

This doesn't just apply to echo specifically. Anything outside of <?php tags is also emitted and will cause this problem.

You should put your redirection code at the top of your file, not embedded inside, as HTML has already been outputted at that point.
E.g.
<?php
if($_SERVER['REQUEST_URI'] == '/betas/') {
header('Location:http://betas.maxk.me');
}
?>
<html>
...

Everything before this line:
<?php
if($_SERVER['REQUEST_URI'] == '/betas/') {
header('Location:http://betas.maxk.me');
// .. etc
Count as output. By the time you've called header(), a bunch of content has already been sent to output. You could perhaps capture it with the ob_* functions, but I bet there's a better solution.

All of the HTML before the opening PHP tag counts as data being sent, so you need the PHP header statement right at the top of your file even above your HTML code.

Anything that is not within <?php ?> tags is treated in the same way as an echo statement and is sent straight to the browser as it occurs in the script. Any header call (or anything that involves HTTP headers) must be from the first PHP block. Note that white space at the beginning of the file will cause this problem too.

Related

PHP: form redirection after validating its fields [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 3 years ago.
I have done a simple form like this:
index.php:
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<?php
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
// handle missing field
} else {
$name = $_POST["name"];
}
}
if($name != '') {
header('location: http://localhost/new_page.php');
exit();
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<span class="label">Name</span>
<input type="text" name="name">
<button><span>Validate</span></button>
</form>
</body>
</html>
I would like the following behaviour:
staying on the form if the name field is not set by the user
going to new_page.php if name field is set
I have the following error right now: if I set the name, I am redirected to a blank.php page.
Can someone help me on this ? Or at least give me some tips to debug this as I am not really a PHP specialist.
Thank you !
Your header call comes too late.
an HTTP Response first has a header, then a body. HTML code is the body.
You need to put all output AFTER your PHP code. Since you start with <html>, headers will already have been sent and so your redirect will not work.
Also, regarding white pages (White screen of death or WSOD):
For the best error logging experience, set error_reporting to -1, turn display_errors off, and set a custom error_log. Then in the terminal, type 'tail -f /path/to/error_log'. Your notices, warnings and errors will now scroll past in real time, without distorting your web page's display.
The answer given by #delboy1978uk is correct.
All you have to do is change your file content to:
<?php
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
// handle missing field
} else {
$name = $_POST["name"];
}
if($name != '') {
header('location: http://localhost/new_page.php');
exit();
}
}
?><!DOCTYPE HTML>
<html>
<head></head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<span class="label">Name</span>
<input type="text" name="name">
<button><span>Validate</span></button>
</form>
</body>
</html>

PHP header() not working? [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 5 years ago.
I'm struggling with this issue, for some reason header("Location:http://corocloud.com/index.php/");
is not working, i've tried other paths to the file but none work,
header("Location:index.php");, header("index.php");, header("./index.php/");
none of these work, my code is this:
<!DOCTYPE html>
<html>
<head>
<title>CoroCloud</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./js/material.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.pink-indigo.min.css" />
<style>.mdl-layout{align-items:center;justify-content:center;}.mdl-layout__content{padding:24px;flex:none;}</style>
</head>
<body>
<div class="mdl-layout mdl-js-layout mdl-color--grey-100">
<main class="mdl-layout__content">
<div class="mdl-card mdl-shadow--6dp">
<div class="mdl-card__title mdl-color--primary mdl-color-text--white">
<h2 class="mdl-card__title-text">CoroCloud</h2>
</div>
<div class="mdl-card__supporting-text">
<form method="POST">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="text" name="uname" />
<label class="mdl-textfield__label" for="uname">Username</label>
</div>
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="password" name="pass"/>
<label class="mdl-textfield__label" for="pass">Password</label>
</div>
<div class="mdl-card__actions">
<input type="submit" class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect" name="sub">
</div>
</form>
</div>
</div>
</main>
</div>
<?php
session_start();
// this will trigger when submit button click
if(isset($_POST['sub'])){
$db = new mysqli("localhost","user","password","db");
// create query
$query = "SELECT * FROM users WHERE user='".$_POST['uname']."' AND password='".sha1($_POST['pass'])."'";
// execute query
$sql = $db->query($query);
// num_rows will count the affected rows base on your sql query. so $n will return a number base on your query
$n = $sql->num_rows;
// if $n is > 0 it mean their is an existing record that match base on your query above
if($n > 0){
$_SESSION['username'] = $_POST['uname'];
$_SESSION['password'] = $_POST['pass'];
$_SESSION['userobj'] = mysql_fetch_assoc($query);
header("Location: index.php");
exit();
} else {
echo "Incorrect username or password";
}
}
?>
</body>
</html>
I know the code is being executed, as the every $_SESSION var is getting value, why does header not work?
The file i'm trying to redirect is in the same folder by the way.
EDIT:
Don't run the snippet, as it has PHP
Add this code at the top of your code // before html code
ob_start();
session_start();
// this will trigger when submit button click
if(isset($_POST['sub'])){
$db = new mysqli("localhost","user","password","db");
// create query
$query = "SELECT * FROM users WHERE user='".$_POST['uname']."' AND password='".sha1($_POST['pass'])."'";
// execute query
$sql = $db->query($query);
// num_rows will count the affected rows base on your sql query. so $n will return a number base on your query
$n = $sql->num_rows;
// if $n is > 0 it mean their is an existing record that match base on your query above
if($n > 0){
$_SESSION['username'] = $_POST['uname'];
$_SESSION['password'] = $_POST['pass'];
$_SESSION['userobj'] = mysql_fetch_assoc($query);
header("Location: index.php");
exit();
} else {
echo "Incorrect username or password";
}
}
// Put here html code //
You cannot output stuff and after that perform a "header" operation in php.
So, modify your code to first do all the php stuff and after that output html.
You MUST not have ANY output (html, warnings, etc.) before that "header" line.
see: http://php.net/manual/en/function.header.php
As Icewine pointed out correctly, headers should be set before any output is created.
So either move your code that is setting the header to the beginning of your script, or capture all output with output buffering, by calling ob_start() at the beginning of your script.
Also It is customary to not send any content when redirecting with a Location header, another reason to move your logic for the redirect to the beginning of your script, and then call exit() after setting the header.
Please try with ob_start() function before and Header Location
ob_start();
header("Location:http://corocloud.com/index.php/");
exit;
I hope it will help ! you please provide the error what you are getting over there.
You may not produce output (HTML or echo) before a header is called. http://php.net/manual/en/function.header.php
Better way is always try to follow some php basics.
<?php
ob_start();
session_start();
exit after header
header("Location:demo.php");
exit;

php header gives me the error [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
First of all don't think that its dublicate question.
I have tried all sollutions but nothing helps me.
I get the following error:
"Cannot modify header information - headers already sent by (output started at /home/gogiavag/public_html/maxkapital/user.php:7) in /home/gogiavag/public_html/maxkapital/func.php on line 4"
All pages I have converted to utf8 (without BOM). I have no leading space in begining, but besides nothing helps.
Here is my code:
login.php
<?php session_start();?>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<?php include "header.php"; require_once 'func.php';?>
<form method="POST" action="user.php">
<table style="margin-top: 10px;">
<tr>
<td><label for ="txtuser">name:</label></td>
<td><input type="text" style="padding:5px;" id="txtuser" name="txtuser" value="<?php if (isset($_SESSION['txtuser'])
){echo $_SESSION['txtuser'];}else{echo '';} ?>" </input></td>
</tr>
<tr>
<td><label for ="txtpassword">password:</label></td>
<td><input type="password" style="padding:5px;" id="txtpassword" name="txtpassword"> </input></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value ="Enter" style="padding:5 55 5 55;background-color:#3f4194;color:#fff;" name="btnsubmit" id="btnsubmit"> </td>
</tr>
</table>
</form>
<?php
if (isset($_SESSION['err'])){
if ($_SESSION['err']===true){
echo gg_stringformat("<img src='error.png' style='margin-left:50px;'><img/> <span style='font-size:10pt; color:#ff0000'>{0}</span>", $_SESSION['errmsg']);
}
}
if(isset($_SESSION['err'])){unset ($_SESSION['err']);};
if(isset($_SESSION['errmsg'])){unset ($_SESSION['errmsg']);};
if(isset($_SESSION['txtuser'])){unset ($_SESSION['txtuser']);};
if(isset($_SESSION['txtpassword'])){unset ($_SESSION['txtpassword']);};
?>
</body>
</html>
user.php
<?php session_start();?>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<?php require_once'func.php';
if (!isset($_POST['btnsubmit'])){
gg_redirect('block.php');
exit;
}
$user=$_POST['txtuser'];
$pass=$_POST['txtpassword'];
$_SESSION['txtuser'] = $user;
$_SESSION['txtpassword'] = $pass;
if (gg_trim($user)===''){
$_SESSION['err']=true;
$_SESSION['errmsg']='User name required';
gg_redirect('login.php');
exit;
}elseif(gg_trim($pass)===''){$_SESSION['err']=true;$_SESSION['errmsg']='Password required';gg_redirect('login.php');
exit;
}
echo $user, "<BR>", $pass;
?>
</body>
</HTML>
header.php
<div id="divheader" >
<p> <img src="coins.png"></img>MAX_KAPITAL</p>
</div>
func.php begins with ...
<?php
mb_internal_encoding("UTF-8");
function gg_redirect($url){
header("location: $url");
}
....
It gives me the error when user don't enters password or username.
Please find error in my code.
thanks in advance.
regards George Gogiava
PHP is not lying to you, you indeed already started output at line 2 in user.php - you print <html> to response there.
Then you print <head> and some more HTML, then you call the function gg_redirect() from func.php if !isset($_POST['btnsubmit']), which causes the error, because it is not longer possible to send the redirect header since output was started already.
You need to check the inputs and possibly redirect before you send anything back to the client (apart of other response headers)., specifically, don't print any HTML before you're done handling the possible redirects:
<?php
// includes here - they must have no output!
// check if all is OK, set $redirectURL if redirect is needed to that URL
if ($redirectUrl) {
header("location: $redirectUrl");
exit(); // header() won't cause the script to stop executing
}
?>
<html>
<head>
...
The files included before the redirect must not print any output - not even a blank line, so they must all have <?php as the first characters of the file, whole file must be PHP without any output to response body, and must end with ?> with no newline or space afterwards (PHP may trim some whitespace in this case but don't rely on that).
Call to session_start() is safe and can be before the redirect (useful if you need session variables), since it will not send any response body. It may set a cookie, but that's OK because cookies are sent in headers.
While #Jiri already explained it correctly, to be more explicit:
move this:
<?php require_once'func.php';
if (!isset($_POST['btnsubmit'])){
gg_redirect('block.php');
exit;
}
to the very top of you php script, maybe even adding the first line to it like this:
<?php
if (!isset($_POST['btnsubmit'])){
gg_redirect('block.php');
exit;
}
require_once'func.php';
session_start();
?>
and then the rest of your page.
EDIT
The func.php is adding headers, by including it before your redirect, you get that error. Move the inlude line to some place after the redirect or check your func.php, see the edited code above

Weird behaviour with QR Code generation

I've below working code in PHP
<?php
include('../../lib/qrlib/qrlib.php');
QRcode::png('PHP QR Codep :)');
?>
The weird part is if I put a space in front of
<?php
then the same code does not work & error log does not show any details either. Also, if I put any other function in the top code before this code, the QR code does not get generated. No error in log either.
What am I missing here???
Update:
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$myErr = "";
$myid = "";
function generateRandomCode() {
// returns random code
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["myid"])) {
$myidErr = "myID is required";
}
$code = generateRandomCode();
}
?>
<h2>My Project</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
My ID: <input type="text" name="myid" value="">
<span class="error">* <?php echo $myidErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>QR Code:</h2>";
$tem = '"myid":"' . $myid . '","code":"' . $code . '"}';
include('../../lib/qrlib.php');
QRcode::png($tem);
?>
</body>
</html>
Looking at the source code for QRcode::png(), I can see that it sends a Content-Type header prior to displaying the PNG image data. That is necessary to inform the receiving browser or device that the data is a PNG image.
// Excerpted from source:
if ($filename === false) {
Header("Content-type: image/png");
ImagePng($image);
// etc...
https://github.com/t0k4rt/phpqrcode/blob/f0567ce717fa1172cb66c48ebae017a094de64b1/qrimage.php#L30
If you have leading whitespace before the opening <?php or any output of any kind before that function is called, PHP will not be able to send the necessary headers.
For full details on this issue and all its potential causes, see How to fix Headers already sent errors in PHP.
Always when developing and testing code, ensure that you have enabled PHP's error display. If it were on, you would have seen PHP issuing warnings related to headers already being sent.
Warning: Cannot modify header information - headers already sent by....etc...
// At the very top of your script:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Or set error_reporting and display_errors in your php.ini. The fact that you saw no errors in your log suggests you either have log_errors disabled in php.ini, or a conservative setting for error_reporting which is not reporting on E_WARNING errors. Best to use E_ALL.
Update after code posted:
You have attempted to call QRcode::png() inside the same script which is currently generating your HTML page. You can't actually do that, because the QR code has to be generated and inserted into an <img> tag. Even though it is generated at runtime by PHP, from the browser's perspective it isn't any different from a real image read from a file on disk so you have to use it the same way in HTML markup as you would a file from disk.
The easiest method to handle this properly is to move the QR code generation to a different PHP file where it is the only action taking place. Then reference that file in an <img> tag's src.
File: generate_qrcode.php
This PHP script is intended to be referenced as example.com/generate_qrcode.php?myid=abcdefg. If you called it as such from the browser, it should just display the bare QR code.
// Contains only QR generation
// Move the $code here, and pass the myid in the query string
// Also move the function definition here
function generateRandomCode() {
// whatever...
}
$code = generateRandomCode();
// This value was originally POSTed to the main script, so
// it needs to be passed from the main script to this one via the query string
$myid = $_GET['myid'];
$tem = '"myid":"' . $myid . '","code":"' . $code . '"}';
include('../../lib/qrlib.php');
QRcode::png($tem);
Main PHP file:
To really use it the way you want in context of your HTML page requires an <img> tag though.
Include an <img> tag which sources the QR code and passes $myid in its query string. The PHP/HTML should not call QRcode::png() itself.
<img src="generate_qrcode.php?myid=<?php echo htmlspecialchars($myid); ?>" alt="QR code" />
This would result in a tag like <img src="generate_qrcode.php?myid=abcdefg" alt="QR code" />
For full context, your main script would now look like:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$myErr = "";
$myid = "";
// This function is defined instead in the QR code script...
//function generateRandomCode() {
// returns random code
//}
// POST handling is the same!
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["myid"])) {
$myidErr = "myID is required";
}
// But this is done in the other QR code script
//$code = generateRandomCode();
}
?>
<h2>My Project</h2>
<!-- The form is the same! -->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
My ID: <input type="text" name="myid" value="">
<span class="error">* <?php echo $myidErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if ($myid) {
echo "<h2>QR Code:</h2>";
// Now include an <img> tag
echo "<img src='generate_qrcode.php?myid=$myid' alt='QR code' />";
}
?>

Cannot modify header information - headers already sent [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I know that this is well known problem but I've tried all solutions with no avail :(
Here is my code:
<?php
ob_start();
if (!empty($_POST)) { // if submit
$username = $_POST['username'];
$userpass = $_POST['userpass'];
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('ita4') or die($connection_error);
function login($username, $userpass) {
$sqlQuery = "SELECT COUNT(userid) FROM users WHERE name='$username' AND password='$userpass' AND admin='t'";
$runQuery = mysql_query($sqlQuery);
return (mysql_result($runQuery, 0) == 1) ? TRUE : FALSE;
}
if(login($username, $userpass)) {
setcookie("username", $username, time()+60*60*24*30);
$_COOKIE['username'] = $username;
echo "Me:".$_COOKIE['username'];
//echo "<script> location.replace('done.html'); </script>";
} else {
echo "<script> alert('Your input data is not found!'); </script>";
}
}
?>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv=content-type content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="upper">
Home • Login • About
</div>
<div id="container">
<div id="loginDiv">
<form action="login.php" onsubmit="return checkEmpty()" method="post" name="loginForm">
<table>
<tr>
<td style="width:100px">Name: </td>
<td>
<input name="username" id="username" type="text" style="width:250px"></td>
</tr>
<tr>
<td style="width:100px">Password: </td>
<td>
<input name="userpass" id="userpass" type="password" style="width:250px"></td>
</tr>
<tr>
<td colspan="2" style="text-align:center"><input id="loginImg" type="image" src="images/loginButton.png"></td>
</tr>
</table>
</form>
</div>
</div>
<div id="lower">
<br><br><br><br><br>
<p style="text-align:center">COPYRIGHTS © 2013 • WWW.HISHAM.WS</p>
</div>
<script type="text/javascript">
function checkEmpty() {
var username = document.getElementById("username").value;
var userpass = document.getElementById("userpass").value;
if(username=="" || username==null) { alert("You've to enter your name!"); }
else if(userpass=="" || userpass==null) { alert("You've to enter a password!"); }
else { return true; }
return false;
}
</script>
</body>
</html>
Thanks in advance
So against my initial reaction to not help you, I decided to go ahead and build the database and table like you have. I created a new database named ita4 and added a table called users with four fields (userid, name, password, and admin). I added a user named josh with a password of josh and an admin setting of 't'. I then put your file into my local development environment and named it login.php. I then loaded up the page in my browser and entered josh for the username and josh for the password and it resulted in it displaying "Me:josh" at the top of the page and the login page still displaying below it. I get no errors.
If you aren't getting that far, then the error message may be because the database connection details are bad or your table doesn't have one of those fields. You do have a "or die(mysql_error()" after the database connect code.
The header needs to be the first thing in the document. Your code should look something like
<?php header("header information"); ?>
<html>
... Your HTML HERE ...
</html>
More information can be found in the PHP documentation here.
As far as i understand, you want to redirect the user to another page if a login occurs.
You could use javascript and/or meta redirections in order to do that.
This question might also help : How to redirect if user already logged in
You did not tell the line number that causes the notice. But I assume it is because you are doing setCookie().
You are already using ob_start() so that is good.
What I suggest is that you pay attention to that NO CHARACTERS should be at the start of the document, before the ob_start(). Look especially for any characters or even white spaces or enters (new lines), before you start <?php. Let <?php be the very first thing in your file.

Categories