php header gives me the error [duplicate] - php

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

Related

Login issue with PHP Session

Hi I have meet a problem here.
I need to log in an account here
but after i key in all the details and click Sign-In the page will redirect me back to the log in page. But actually the account is already logged in just that it cant redirect back to the Home Page after log in.
What problem is this? Im using Session.
and i put my session_start in connect.php(which is use to connect to database)
Below is The Code
<?php error_reporting(0) ?>
<?php
include_once 'connect.php';
//Code Refer to http://www.w3schools.com/php/func_http_setcookie.asp
if(isset($_SESSION['user'])!="")
{
header("Location: Home.php");
}
if(isset($_POST['btn-login']))
{
$username = mysql_real_escape_string($_POST['username']);
$upass = mysql_real_escape_string($_POST['password']);
$res=mysql_query("SELECT * FROM user WHERE u_username='$username'");
$row=mysql_fetch_array($res);
if($row['u_password']==md5($upass))
{
$_SESSION['user'] = $row['u_ID'];
header("Location: Home.php");
}
else
{
?>
<script>alert('wrong details');</script>
<?php
}
?>
<?php
$year = time() + 31536000;
setcookie('rememberme', $_POST['username'], $year);
if ($_POST['rememberme'])
{
setcookie ('rememberme',$_POST['username'], $year);
}
else
{
setcookie(rememberme, $past);
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<link rel="stylesheet" href="Style.css" type="text/css" />
</head>
<body>
<div id="header">
<div id="left">
<label>AngelService</label><br/>
<p>Royal Borough of Greenwich</p>
</div>
</div>
<center> Home Page | View Post | Post A Service</center>
<center>
<div id="login-form">
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="username" placeholder="Your Username" required value="<?php
echo $_COOKIE['rememberme']; ?>"/>
</td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Your Password" required />
</td>
</tr>
<tr>
<td><button type="submit" name="btn-login">Sign In</button></td>
</tr>
<tr>
<td>
<input type="checkbox" name="rememberme" value="rememberme" style="font- size:6px;"> Remember Me<br>
</td>
</tr>
<tr>
<td>
Sign Up Here</td>
</tr>
</table>
</form>
</div>
</center>
<div id="footer">
<div id="center" align="center">
<br/>
<p>Angel Services | Royal Borough of Greenwich | Created By UOG Student: Kuai Boon Ting</p>
</div>
</div>
</body>
</html>
You are missing action="Your redirection page" in form tag i.e.,
<form method="post" action="forexample-Home.php">
.....
</form>
There are several things you can do to improve your code. For starters, you do not need to close and open PHP tags directly after each other, like you have
<?php error_reporting(0) ?>
<?php
include_once 'connect.php';
could just be
<?php error_reporting(0);
include_once 'connect.php';
The statement if(isset($_SESSION['user'])!="") doesn't do exactly what you think it does. isset($_SESSION['user']) returns a boolean (true/false), so checking whether or not a boolean is empty won't work. You can do if (!empty($_SESSION['user'])) {... to check if it's set and if it's empty or not. Check out the documentation for isset() and documentation for empty().
For your actual problem though: Note also that your header(); functions cannot be called after any output is made to the browser (any whitespace, HTML or PHP echo). This would appear as a PHP Warning, which will be reported should you put error_reporting(-1); instead of ignoring all errors (as you currently are doing with having error_reporting set to 0).
The other answer suggested using the HTML action-attribute for the form, but in case the login is invalid, it's best to have it sent to the same page, and only redirect should the login be valid. This is called "validate and redirect".
These pointers below are just to improve your code, and not necessarily the cause of your problem.
If you want to set a cookie, it has to be done before any and all output is sent to the browser (see this post), so in case the if($row['u_password']==md5($upass)) statement fails, and it enters the else-brackets, your cookie will not be set.
You should stop using mysql_* functions if you can. They are deprecated, and will be removed in the future. Switch over to mysqli_* or PDO instead. (Check out this post).
Usage of md5 hashing is not that secure. If you have PHP 5.5.0 or higher, you should perhaps look into usage of password_hash and password_verify
After every header("Location: ...."); you should always put a exit;, so that the code stops executing after it's redirecting. (Check out this post).

Session variables not passing to next file

So I've searched this site about this issue and tried what has been suggested and still no luck. I thought maybe it was my 'server' (On my tablet using KSWEB, no computer right now) so I created 2 simple files to share a session variable between the two and it worked fine. I have no idea why this isn't working for these two. I'm trying to create a login page (an insecure one, I know). The error function USED to work (this is what gets me), and now it doesn't. The files are below. I only included the top portion of admin.php because I've commented out the rest. It really shouldn't matter. Right now, if you submit the form without entering anything into the admin prompt, an error should display next to the asterisk saying "Admin needs to be filled out". Despite my best efforts, this doesn't work anymore and I'm completely stumped as to why.
Login.php
<?php
session_start();
?>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<script>
function submitForm()
{
document.adminform.submit();
}
</script>
</head>
<?php echo $_SESSION["adminErr"];?>
<h2>Administrator login page</h2>
<form method="post" action="admin.php" name="adminform">
Admin: <input type="text" name="admin" style="position:absolute; left:100px">
<span class="error" style="position:absolute; left:285px">*<?php echo $_SESSION["adminErr"];?></span>
<br><br>
Password: <input type="password" name="password" style="position:absolute; left:100px">
<span class="error" style="position:absolute; left:285px">*<?php echo $_SESSION["passwordErr"];?></span>
<br><br>
<button onclick="submitForm()">Submit</button>
</form>
<br><br><br>
<p><?php echo $_SESSION["flogin"];?></p>
</html>
<?php
session_destroy();
?>
Admin.php
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == POST)
{
if (empty($_POST["admin"])) // Check to make sure Admin field is filled out
{
$_SESSION["adminErr"] = "Admin field must filled"; // Set error if not filled
header("location:login.php"); // Return to login page
}
}
?>
Don't destroy the session at the end of the file..
</html>
<?php
session_destroy();
?>
Also you should put exit; after each header('Location: ...');.
When sending the header, the browser recognized to change the location but the script does not end. The browser in fact, would not even have to follow the header, it can also just go on with the script. You have to stop the script because the headers do not exit the script.
instead of
<button onclick="submitForm()">Submit</button>
use
<input type="submit" value="Submit">
Then put a check before echoing
<?php echo isset($_SESSION["adminErr"])? $_SESSION["adminErr"]: "not set" ;?>
further debugging:
var_dump($_POST);
var_dump($_POST["admin"]);
var_dump($_SESSION);
var_dump($_SESSION["adminErr"]);

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.

Cannot modify header information - Baffled [duplicate]

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.

PHP - Problem with cookies/setcookie

I'm having problems with the following code: http://pastebin.com/MCkhzQjs
This works locally (on localhost) but when I upload it to the server it does not login. I think it is to do with cookies not being sent. The meta refresh is so that the page is refreshed after the cookie is set. Thank for any help.
the answer is simple.
You can only set cookies, start sessions, set headers IF there has been not content echo'd or sent (including html) outside of php code blocks.
Examples:
Won't Work:
<div>
<?php setcookie(/*....*/); ?>
</div>
Reason: Because the <div> has already been sent forcing the headers to be sent, there for cookies cannot be added to the headers, because there sent
Another:
<?php
setcookie(/*....*/); //works
echo "test";
setcookie(/*....*/); //does not
?>
Your code should look like:
$title = "Admin panel";
if(!isset($_COOKIE['login'])) $_COOKIE['login'] = false;
if(!isset($_POST['password'])) $_POST['password'] = false;
if($_POST['password'] == "tt83df")
{
if(isset($_POST['permlog']))
{
$expire = time()+60*60*24*365;
setcookie("login", "tt83df", $expire, "/admin");
}
else
{
setcookie("login", "tt83df", 0, "/admin");
}
header("Location: " . $_SERVER['PHP_SELF']);
exit;//Stop here and SEND Headers
}
if($_COOKIE['login'] == "tt83df")
{
$html = '<ul><li>News control panel</li><li>Video control panel</li><li>Schedule control panel</li>
<li>Events control panel</li><li>Notices control panel</li></ul>';
}else
{
$html = 'Password:<form method="post"><input type="password" name="password" /><input type="submit" value="Submit"><br />
<input type="checkbox" name="permlog" value="true" /> Stay logged in? (do not use on a public computer)</form>';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="icon" type="image/vnd.microsoft.icon" href="images/favicon.ico" />
<title><?php echo $title; ?></title>
</head>
<body>
<?php echo $html; ?>
</body>
</html>
Have you error_reporting enabled? Your code contains whitespaces before the first php-tag, what is an output and forces the server to send the headers(error_reporting should give you a notice about that).
I think that the issue consist of setting a cookie after writing HTML to the output stream. Cookies or header modifications can only done before the header is sent. Writing content to the output stream forces the header to be automatically written.
Try using ob_start(); at the top of your code, and ob_end_flush(); at the bottom. This will initialize a buffer which will be filled with everything that is written to your output stream. So basically. ob_start is for initializing an output buffer, and ob_end_flush for writing the buffer back to the client.

Categories