PHP setcookie warning - php

I have a problem with 'setcookie' in PHP and I can't solve it.
so I receive this error "Warning: Cannot modify header information - headers already sent by (output started at C:\Program Files\VertrigoServ\www\vote.php:14) in C:\Program Files\VertrigoServ\www\vote.php on line 86"
and here is the file..
line 86 is setcookie ($cookie_name, 1, time()+86400, '/', '', 0);
is there any other way to do this ??
<html>
<head>
<title>Ranking</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#EEF0FF">
<div align="center">
<br/>
<div align="center"><div id="header"></div></div>
<br/>
<table width="800" border="0" align="center" cellpadding="5" cellspacing="0" class="mid-table">
<tr><td height="5">
<center>
</tr>
</table>
</center>
</td></tr>
<tr><td height="5"></td></tr>
</table>
<br/>
<?php
include "conf.php";
$id = $_GET['id'];
if (!isset($_POST['submitted']))
{
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
</div></td></tr>
<tr><td align="center" valign="top"><img src="images/ads/top_banner.png"></td></tr>
</table>
</form>
<?php
}
else
{
echo '<font color="red">You must select a valid server to vote for it!</font>';
}
}
else
{
$kod=$_POST['kod'];
if($kod!=$_COOKIE[imgcodepage])
{
echo "The code does not match";
}
else
{
$id = mysql_real_escape_string($_POST['id']);
$query = "SELECT SQL_CACHE id, votes FROM s_servers WHERE id = $id";
$result = mysql_query($query) OR die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$votes = $row['votes'];
$id = $row['id'];
$cookie_name = 'vote_'.$id;
$ip = $_SERVER['REMOTE_ADDR'];
$ltime = mysql_fetch_assoc(mysql_query("SELECT SQL_CACHE `time` FROM `s_votes` WHERE `sid`='$id' AND `ip`='$ip'"));
$ltime = $ltime['time'] + 86400;
$time = time();
if (isset($_COOKIE['vote_'.$id]) OR $ltime > $time)
{
echo 'You have already voted in last 24 hours! Your vote is not recorded.';
}
else
{
$votes++;
$query = "UPDATE s_servers SET votes = $votes WHERE id = $id";
$time = time();
$query2 = mysql_query("INSERT INTO `s_votes` (`ip`, `time`, `sid`) VALUES ('$ip', '$time', '$id')");
$result = mysql_query($query) OR die(mysql_error());
setcookie ($cookie_name, 1, time()+86400, '/', '', 0);
}
}
}
?>
<p>[Click here if you don't want to vote]</p><br/>
<p>Ranking.net © 2010-2011<br> </p>
</div>
</body>
</html>
Thanks a lot!

You cannot have any output before header() and setcookie() calls.
https://stackoverflow.com/search?q=+headers+already+sent+by
https://stackoverflow.com/tags/php/info
Any output includes any <html> before the openeing <?php marker, or any print or echoing of content. Another culprit is the UTF-8 BOM http://en.wikipedia.org/wiki/Byte_Order_Mark - which most text editors do not show visibly, but confuses PHP when at the beginning of files.

Setting a cookie requires sending a header to the client, and you can't send headers if the output has already started.
You have to put the PHP code before the HTML markup so that you can call setcookie before any output is sent and you also separate PHP code from presentation which you should do anyway.

You should put the cookie code at the top of the page. A better layout would be something like this:
<?php
//include config
//check posted data (included settings cookies)
//set needed variables
?>
<html>
.....
You could also separated the php code and html. This is generally what i do. My uses generally involve a view class or (in the past) smarty. but a quick example would be to add this code at the bottom of the above php code and get rid of the html:
<?php
if(empty($tpl)) {
$tpl = 'index';
}
if(file_exists("template/{$tpl}.tpl.php")) {
include("template/{$tpl}.tpl.php");
}
else {
header('Location: /');
}
?>
YOu would need to create a directory called 'templates' and add the html code to files that end in the .tpl.php extension.
Really they are just php pages, but the .tpl. part help you remember that its just mark up.
Make them php pages (not html) so you can output variables
Then in your varios parts of your code above you would set $tpl to be the template you want to load.
This is a just a base bit of code, but it should give you a general idea on how to separate this data. THe main idea is that all html and text will be outputted "after" all programming code has been done.

What you need to do is to create a nice buffer to hold all the headers in until you are down processing. ob_start does the job for you and here is a reference to it. http://php.net/manual/en/function.ob-start.php
When you are finished loading all the different headers use ob_get_contents like this
$text = ob_get_contents();
echo($text);
ob_end_clean();
I hope this helps.

You can not use PHP to set a cookie after any thing has been outputted, and the html before the first php tag does count as output. to keep to a purely php method you'd have to move the whole part about determining what to put int he cookie and setting it up to the very top.
or what I do in situations where that would require to much extra work to do it that way is to have php echo out the JavaScript code to set a cookie. now if you make or get a nice JS cookie setting function and either embed it or link it into the page. then all you have to do is have php echo the function call with the proper data in it at that point. then when the page loads while php still will not set the cookie, but when the browser when it runs the js code it will. and so you get what you want the cookie is set. and you did not have to move the stuff up to the top.

Related

header("Content-Type: image/png"); php

when implement this code i have no image
<?php
include('confing.php');
echo '<img src="getImage.php?id=2" >';
?>
file => getImage
<html >
<body>
<?php
include('confing.php');
$id = $_GET['id'];
$sql="SELECT * FROM images WHERE id=$id ";
$result=mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
  // Set the content type header - in this case image/png
header("Content-Type: image/png");
echo $row['content'] ;
?>
body>
html>
body
html
body>
html>
body
html
body>
html>
body
html
The errors you are getting:
Undefined index ID: It would appear that you are calling it without passing the ID argument. Obviously you should check that. But also, you should add some error checking to your code to ensure that it doesn't crash if the ID is not passed, or if the ID is invalid.
Undefined variable $connection: Your database connection variable is not set. Maybe you config.inc include doesn't actually set the connection? Or maybe you've got the variable name wrong? You need to check your config.inc to find out why this is happening. In any case, this leads directly onto the next error...
mysqli_query expects connection parameter: Because the $connection variable is not set, your DB query can't be run. Some error checking here would be helpful, even if you do sort out the connection variable, as there may be other reasons the connection may fail.
mysqli_fetch_assoc expects result parameter: This occurs because the result variable is not set due to the query not being run. You should add some error checking for this as well, since there may be other reasons why a query fails to run.
The errors didn't even get as far as hitting the header() function call, which would also fail because the program has already output some content. You should remove the <html><body> tags from the top of the program, as they are not necessary for outputting an image; in fact, they would cause the image to be invalid.
Your line:
echo '<img src="getImage.php?id=2">';
will output this into your html page:
<img src="getImage.php?id=2">
Second, it will not load, execute and insert the result of getImage.php.
Here's a solution:
First page:
<?php
include('getImage.php');
$id = $_GET['id'];
$img = getImage($id);
echo "<img src='$img' >";
?>
getImage.php:
<?php
include('confing.php');
function getImage($id){
$sql="SELECT * FROM images WHERE id=$id ";
$result=mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
return $row['content'] ;
}
?>

Using header() to redirect after using include()

I have a page structured like below and I am having issues getting the redirect to work. This page gets an ID from the URL and uses it in the query. If there isn't a match, just redirect to another page.
I am getting the "headers already sent error," due to the include. I need the include to be there regardless. Is there a different way I can do the redirect if the query result is empty?
include('somepage.php');
$id = $_GET['id'];
$query = mysql_query("My query is here");
if(mysql_num_rows($query)==0) { header('Location:htp://example.com'); }
I've tried using exit(); and the various stop processing functions.
somepage.php:
<html>
<head>
(standard html)
include('sql-connect.php');
</head>
<body>
(code to format the header portion of the site)
You can put ob_start() at the beginning of the file, so that it looks like this:
<?php
ob_start();
include 'somepage.php';
$id = $_GET['id'];
$query = mysql_query("My query is here");
if(mysql_num_rows($query)==0) { header('Location:http://example.com'); }
Also, you can echo html redirect:
<?php
if(mysql_num_rows($query)==0) { echo '<meta http-equiv="refresh" content="0; url=http://example.com/">'; die(); }
You need to add ob_start() at the beginning of the file and if this still does not work then you also need to add ob_flush(); to fully flush out the old header.
flush(); // Flush the buffer
ob_flush();
header("Location: http://example.com");
You may have a blank line after a closing ?> This will cause some literal whitespace to be sent as output, preventing you from making subsequent header calls. Note that it is legal to leave the close ?> off the include file, which is a useful idiom for avoiding this problem.
ob_start() may fix your problem.
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>
"headers already sent error" means that your script (somepage.php) already sent headers to the browser, so you can't change these headers and redirect user to the other URL.
The best solution is to move the "include" operator after your check:
$id = $_GET['id'];
$query = mysql_query("My query is here");
if(mysql_num_rows($query)==0) { header('Location:http://example.com'); }
include('somepage.php');
Also, you can prevent your somepage.php from sending any data to the client.
The second variant is to use the functions ob_start(), ob_get_contents(), ob_end_clean():
ob_start();
include('somepage.php');
$id = $_GET['id'];
$query = mysql_query("My query is here");
if(mysql_num_rows($query)==0) { header('Location:http://example.com'); }
$content = ob_get_contents():
ob_end_clean();
echo $content;

Why is my Javascript not working from the PHP file?

I have the following files. For some reason my JavaScript (inside PHP 'echo' tags) does not work:
HTML (index.php):
<form action="submit.php" method="post">
<div id="edit-box">
<INPUT type="submit" name="save-text" id="save-text" value="Save">
<textarea id="editor" name="editor">
<?php echo $content; ?>
</textarea>
</div>
</form>
PHP (submit.php):
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = getRealIPAddress();
if ($content != '') {
mysql_query("INSERT source SET submit_date='$submit_date', ip='$ip_address', content='$content'")
or die(mysql_error());
// The following line is not working! I need help here!
echo '<script type="text/javascript"> alert("Your file saved!");</script>';
mysql_close($connection);
}
?>
The "submit.php" does not have any other PHP or HTML script/tags. I understand I am using obsolete PHP/MySQL API (instead of PDO / MySQLi), but that's beside the point.
It should should print an alert.
Are sure you are printing the script? I can see it might die on an
error in the query.
If that is not the case, what are you including in the connect-db.php,
it might be that somewhere in the required file you are messing up
the output buffer..
Also I'm pretty sure the sql is incorrect:
INSERT source SET submit_date='$submit_date', ip='$ip_address', content='$content'
INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content');
And that is not a secure query, however... that is beside the point.
Here is some more reasons why this could happen:
The include("connect-db.php'); might kill the execution of the script.
If there is something wrong inside of it.
The query might die.
The output is redirected to somewhere else, in the php configuration,
or inside of "connect-db.php"
getRealIPAddress() is not documented, and might cause the script to break.
There might be something bogus in $_POST['editor'] that might break cause
the sql to die.
Try below code
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = getRealIPAddress();
$content = $_POST["editor"];
if ($content != '') {
mysql_query("INSERT source SET submit_date='$submit_date', ip='$ip_address', content='$content'")
or die(mysql_error());
// The following line is not working! I need help here!
echo '<script type="text/javascript"> alert("Your file saved!");</script>';
mysql_close($connection);
}
?>

Problem with Session in php

Code:
<?php
include ("conf/conf.php");
include ("classes/dbhelper.php");
$conf = new Dbconf();
$dbURL = $conf->get_databaseURL();
$dbUName = $conf->get_databaseUName();
$dbPword = $conf->get_databasePWord();
$dbName = $conf->get_databaseName();
$nameOfDbWithWorkers = $conf->get_nameOfDbWithWorkers();
if($_POST['auth']){
$login = trim(($_POST['login']));
$pass = trim($_POST['pass']);
$dbHelp = new DbHelper($dbURL, $dbUName, $dbPword, $dbName, $nameOfDbWithWorkers);
$userType = $dbHelp->getUser($login, $pass);
switch ($userType){
case "admin":
startSession($login, $pass);
header("Location: adminpage.php");
break;
case "user":
startSession($login, $pass);
header("Location: operatorpage.php");
break;
case "nomatch":
echo
'<html>
<body>
<table width=100% height=100% border=0 cellpadding=0 cellspacing=0>
<tr valign="center" align="center">
<td>
<form action="authorize.php" method="post">
Логин:<input type="text" name="login"><br>
Пароль:<input type="password" name="pass"><br>
<input type="submit" name="auth">
<font color = red> Неправильный пароль или логин</font>
</td>
</tr>
</table>
</form>
</body>
</html>';
break;
}
}
else{
header("Location: index.php");
}
function startSession($login, $pass){
session_start();
$_SESSION['login'] = $login;
$_SESSION['pass'] = $pass;
$_SESSION['usr_id'] = md5(crypt($login,$pass));
}
When I enter right login and pass information, i have a next errors.
Warning: Cannot modify header information - headers already sent by (output started at Z:\home\ecl.ru\www\classes\dbhelper.php:24) in Z:\home\ecl.ru\www\authorize.php on line 20
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at Z:\home\ecl.ru\www\classes\dbhelper.php:24) in Z:\home\ecl.ru\www\authorize.php on line 53
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at Z:\home\ecl.ru\www\classes\dbhelper.php:24) in Z:\home\ecl.ru\www\authorize.php on line 53
How to solve this?
You need to start the session before you do anything. Read the docs.
There is something outputted at you file dphelper.php, as the notice says:
Warning: Cannot modify header information - headers already sent by (output started at Z:\home\ecl.ru\www\classes\dbhelper.php:24) in Z:\home\ecl.ru\www\authorize.php on line 20
As headers are sent before any kind of output, your session_start() comes in too late. One suggestion, as people already stated, is to put session_start() on top of the file, another one (could be implemented together with the first one) - to look into dbhelper.php and make sure it does not output anything (from the name of the file - it should not, anyway). And, when I say "output", it is not necessarily echo / print / etc, it could also be white space after the closing php tag at the end of the file.
You can work around this by enabling output buffering, that way the headers will always be sent before the data.
Start your session before using headers
Looking at your code, there isn't any content obviously being sent before session start, however, you have various functions calls. Do any of them output content?
Is that the complete file? Even a line return before <?php will count as content sent to the browser....
Just put session_start(); on top before your includes so when you call your startSession function anywhere in your code it will just set any values you assign to $_SESSION.

Passing sessions variables through an iframe, php

First timer to the site, not an overly experienced php programmer here :)
I have a problem, i am using an iframe within a site which im attempting to use a session variable inside, firstly ive just been trying to display the session variable to make sure they are accessible from within the iframe:
echo "session of productcheck ".$_SESSION['productcheck']." ";
echo "session of productcheck1 ".$_SESSION['productcheck1']." ";
echo "session of productcheck2 ".$_SESSION['productcheck2']." ";
echo "session of productcheck3 ".$_SESSION['productcheck3']." ";
this just shows "session of product check" with nothing after each one, I set the session variable as such:
$_SESSION['productcheck'] = $productBox;
the $productBox is a GET from the URL:
echo " <iframe src=\"homeview.php?productBox=$product1\" name=\"FRAMENAME\" width=\"594\" height=\"450\" scrolling=\"No\" id=\"FRAMENAME\" allowautotransparency=\"true\" > </iframe >";
What's strange is if i just take the $productBox variable retrieved from the URL and use that then the code works, its only when i store it in a session variable that it gets confused. I want to retrieve a second $productBox and assign it to session var productcheck1 and so forth down the line. Unfortunately, i have to take one var in at a time, otherwise i could just pass all 4 products and not worry about the sessions.
Perhaps I'm making this far too complicated, any help would be much appreciated Thank you!!
You have to use session_start() in both scripts, the one setting the values (and presumably printing the <iframe>-element?) and the script that produces the contents for the iframe.
e.g. the "outer" script
<?php // test.php
session_start();
$_SESSION['productcheck'] = array();
$_SESSION['productcheck'][] = 'A';
$_SESSION['productcheck'][] = 'B';
$_SESSION['productcheck'][] = 'C';
session_write_close(); // optional
?>
<html>
<head><title>session test</title></head>
<body>
<div>session test</div>
<iframe src="test2.php" />
</body>
</html>
and the script for the iframe content
<?php // test2.php
session_start();
?>
<html>
<head><title>iframe session test</title></head>
<body>
<div>
<?php
if ( isset($_SESSION['productcheck']) && is_array($_SESSION['productcheck']) ) {
foreach( $_SESSION['productcheck'] as $pc ) {
echo $pc, "<br />\n";
}
}
?>
</div>
</body>
</html>
Not sure what's up with your session variables, but you can definitely pass all four variables through the url in your iframe. You just need to separate your key value pairs with an ampersand. So something like this:
file.php?key1=val1&key2=val2&key3=val3 and so on.
This is probably a better way than using session variables if your just trying to get data into that other file.

Categories