PHP - Problem with cookies/setcookie - php

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.

Related

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

Warning: session_start(): Cannot send session, I have tried my all possible solution

I tried some solution from internet, I put session_start(); at first line, also try by using #ob_start(); Any other solution???
My code is here:
<?php
session_start();
require_once('page.inc');
?>
<!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>site 1</title>
<meta name="keywords" content="universe, blog theme, black, website template, templatemo" />
<meta name="description" content="About Universe, Our Company, free website template" />
<link href="templatemo_style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery-1.6.3.min.js" ></script>
</head>
<body>
<?php
if(!isset($_SESSION['loggedinuser']))
{
if (isset($_POST['Signin']))
{
$username=$_REQUEST['username'];
if($username=='a')
$_SESSION['loggedinuser']=$username;
else
echo " the username or password you entered do not matchted ! ";
}
else
{
?>
<form method="post" action="index.php" >
<input type="text" name="username" id="username" >
<input name="Signin" type="submit" value="Signin" />
</form>
<?
}
}
else
//something else
?>
</body>
</html>
here the error is:
Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /usr/local/apache2/htdocs/jasi/medu_quiz_22111_bl/index.php:1) in /usr/local/apache2/htdocs/jasi/medu_quiz_22111_bl/index.php on line 2
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /usr/local/apache2/htdocs/jasi/medu_quiz_22111_bl/index.php:1) in /usr/local/apache2/htdocs/jasi/medu_quiz_22111_bl/index.php on line 2
Check whitespaces before <?php, ensure that the <?php is the first character, not tabbed or spaced.
I have tried your code and all works fine, I copied pasted it as is and the form is showing normal
even submitted the form twice once with the correct value and form disappeared and once with the wrong value and the message that it is a wrong value
if you have placed some white space before :
<?php
session_start();
....
?>
That might produce an error, nothing should come before the session_start() part, maybe you have note created the page: page.inc and that is doing the damage
This is the new code I tried, and these are step you can take:
I have checked it with opera, yes at first it was not showing, but with a heavy refresh it did show, try to do a no caching mechanism, by maybe sending it to page with a random id, this will clear the cache, the problem is not session in opera, the session is working, it is in caching,
Refresh your opera and you will, I took the address and copied it into another tab on opera, and the session showed, This is the complete copy on my version:
<?php
session_start();
require_once('page.inc');
?>
........
<?php
if(!isset($_SESSION['loggedinuser']))
{
if (isset($_POST['Signin']))
{
$username=$_REQUEST['username'];
if($username=='a')
$_SESSION['loggedinuser']=$username;
else
echo " the username or password you entered do not matchted ! ";
}
else
{
?>
<form method="post" action="index.php" >
......
</form>
<?
}
}
else if(isset($_SESSION['loggedinuser']))
{
$ses = $_SESSION['loggedinuser'];
echo "LINE 47 session is $ses ";
}
else
{
$ses2 = $_SESSION['loggedinuser'];
echo "LINE 51 session is $ses2 ";
}
?>
</body>
</html>
This produces:
Line 2 included a page LINE 47 session is a 56
page.inc
<?php
echo " Line 2 included a page ";
?>

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' />";
}
?>

header() function in php : No any redirection!

I have written a very very very simple!! script in php. header redirection not working.
1- encoding : UTF-8 without BOM
2- with adding ob_start() the problem is countiueing.
What is wrong in my code;
login.php:
<?php session_start();
require_once("funcs.php");
db_connection();
$username = $_POST['username'];
$password = $_POST['pwd'];
$submit = $_POST['login'];
if($submit){
if (!filled_out($_POST)) {
echo "please fill all fields";
}
else{
$query = "SELECT * FROM *** WHERE username ='{$username}' AND password ='{$password}'";
$result = mysql_query($query);
if(mysql_num_rows($result) == 1){
$found_user = mysql_fetch_array($result);
$_SESSION['id'] = $found_user['id'];
$_SESSION['username'] = $found_user['username'];
$_SESSION['password'] = $found_user['password'];
setcookie(session_name(), '', time()+86400, '/');
header("Location: tst.php");
}
else{
echo "incorrect username or password";
}
}
}
?>
<!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>Untitled Document</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="username">
Username:
</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="textfield">
Password
</label>
<input type="password" name="pwd" id="pwd" />
</p>
<p>
<input name="login" type="submit" id="login" value="Log in" />
</p>
</form>
</body>
</html>
<?php
db_disconnect();
?>
and tst.php:
<?php session_start();
require_once("funcs.php");
if (!isset($_SESSION['id'])){
header("Location : login.php");
}
?>
<!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>Untitled Document</title>
</head>
<body>
<table id="structure">
<tr>
<td id="navigation"> </td>
<td id="page"><?php echo "welcome"."". $_SESSION['username']; ?></td>
</tr>
</table>
</body>
</html>
wthit oppening tst.php directly, header() doesnot redirect to login.php
Try adding die():
header("Location: tst.php");
die();
You should always add a die() because a location header is just a request to the browser to change the page. If you don't die(), the rest of the page will still reach the browser, including possibly sensitive data the user is not meant to see.
Try removing the space after "Location":
header("Location: login.php");
Please heed my comment about formatting your code correctly as it's extremely difficult to spot anything else that may be amiss.
Check for white space before your opening <?php tags. It's hard to tell from your formatting here whether there is any, but the whitespace will be sent before your code executes, preventing headers. Also check for white space after any closing tags in included files. (better practice is to omit closing tags altogether)
old answer
You're using setcookie() which will send headers, then trying to redirect. You cannot redirect once headers have been sent. (sorry, this was incorrect)
I guess the redirect works, but you overwrite the Session-Cookie with an empty value. So the tst.php creates a new empty Session and redirects back to login.php.
Try:
// DELETE this line: setcookie(session_name(), '', time()+86400, '/');
header("Location: tst.php?".SID);
Importent: header+session always need SID for not loosing the session!
Corrected: Thanks to #Pekka.
header is not just a php function. It really modifies a part of http header, so it is impossible to have a part of header, then html data, then another header. To make it work, you should put your header at the beginning of the file, before any html output is done.
The redirection can take a relative or absolute URL. The problem is with the space BEFORE the colon. Try it like this:
header("Location: whatever.php");
As well as the other answers, the Location: header should contain an absolute URL, example header("Location: http://example.com/");
you need to put an exit() or die() after the header function - otherwise the rest of the script will continue to execute.

Cookies are Not Being Set Properly in PHP Script

Im very new in php and try to use cookie but it is not woking in my site, can anyone guide me please , what is going wrong in my code:
<?php
session_start();
?>
<script>
function Redirect(url)
{
location.href = url;
}
</script>
<?php
define('_VALID_ACCESS', true);
include_once "includes/connect.php";
include_once "includes/login.php";
if(empty($_POST['loginname']) || empty($_POST['password']))
{
$msg = "User or password is empty";
}
else
{
if(login($_POST['loginname'], $_POST['password']) == true)
{
$usern = $_POST['loginname'];
session_register('loginname');
$loginname = $usern;
sleep(1);
if(activestatus($_POST['loginname'], $_POST['password']) == true)
{
$usern = $_POST['loginname'];
session_register('loginname');
$loginname = $usern;
sleep(1);
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['loginname'], $hour);
setcookie("Key_my_site", $_POST['password'], $hour);
$test = $_COOKIE["ID_my_site"];
$msg = "<script> Redirect ('home.html?testname=".$test."')</script>";
//header("Location: home.html");
}
else
{
$msg = "<script> Redirect ('valid.php?testname=".$usern."')</script>";
}
}
else
{
$msg = "<font color=red>User or Password is wrong</font>";
}
}
echo '<div id="divTarget">' . $msg . '</div>';
?>
<link rel="stylesheet" href="css/blueprint/screen.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="css/blueprint/print.css" type="text/css" media="print">
<link rel="stylesheet" href="css/blueprint/ie.css" type="text/css" media="screen, projection">
<body>
<div class="container" id="login_container">
<form id="login" action="action.php" method="post" name="loginform" >
<fieldset id="login_screen" style="width:350px">
<label id="login_label" for="login">User Login </label>
<br><br>
<label for="login">Email Address</label>
<input type="text" name="loginname" id="loginname" value="email#coolmates.com">
<p id="space"><label for="password">Password</label>
<input type="password" id="password" name="password" value="********" ></p>
<input type="checkbox">Keep me signed in until i signout
<p id="test"><input type="submit" value="Submit"></p>
<a href="forgetpassword.html">Forgot
your password</a> |<span id="free">Not a member?</span>Sign up<blink><span id="free">Free</span></blink>
</p>
</fieldset>
</form> </div>
</body>
Turn on display_errors and set your error_reporting to E_ALL and you should see an error message about 'headers already sent' - you have to call setcookie() BEFORE ANY HTML IS SENT. From php.net/setcookie:
setcookie() defines a cookie to be
sent along with the rest of the HTTP
headers. Like other headers, cookies
must be sent before any output from
your script (this is a protocol
restriction). This requires that you
place calls to this function prior to
any output, including and
tags as well as any whitespace.
In the code block that you posted this bit:
<script>
function Redirect(url)
{
location.href = url;
}
</script>
Is being output directly to the browser well before you ever attempt to set the cookies.
Your two possibilities would be to use output buffering so that you output everything at the very end or to switch to a method where all of your processing code is executed first in one script and there you set $_SESSION and cookie values and then include a second script at the tail end of the first that contains the code to be output to the browser.
Try this (specifying the root of your site) :
setcookie("ID_my_site", $_POST['loginname'], $hour,'/');
or try this (adding quotes to your loginname) :
setcookie("ID_my_site", "$_POST['loginname']", $hour,'/');
1st you don't need session_register, you can just do.
Since session_register is the preferred method since 4.1.0 and deprecated as of PHP 5.3
$_SESSION["loginname"] = $_POST["loginname"]
2nd if you are going to use sessions, your flow could be better, since this does not work.
$_SESSION["foo"] = 1;
header("Location: stuff.php");
Then you can't view the session data in stuff.php. You could either send the user to the main page, and do the authentication there, and if it passes then you just continue on with the loading of the main page, and if it doesn't, then you send the user back to the login page like this.
if($_SESSION["authenticated"] == 0)
{
header("Location: login.php");
die();
}
Also you should not be storing a password is cookie data -- this is a big security No-No!!!
If you want to do something like that set a unique - random - identifier that changes when they login and use that instead (you should still MD5 it)

Categories