Using header() to redirect after using include() - php

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;

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

PHP - setcookie(); not working ( 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 8 years ago.
I am getting this error:
Warning: Cannot modify header information - headers already sent by (output started at /removed/loginform.php:2) in /removed/loginform.php on line 24
I understand that I am getting the error when I try to set a cookie, and it's because setcookie can't have any output before it... the problem is, there is no output before it (At least from what I can see). It is saying that "< ?php" is a header, and I don't understand that. If setcookie can only be used in PHP and < ?php is a header, how is it even possible to use setcookie without getting this header error?
My code:
<!--Database Connections-->
<?php include "../../includes/dbpractice_con.php"; ?>
<?php
//Declare variables
$username = "";
$password = "";
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") { //Retrieve from form when submit is clicked.
//Escape to prevent SQL injection.
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$check = mysqli_query($connection, "SELECT * FROM users WHERE username='$username' AND password='$password'");
$rowCount = mysqli_num_rows($check);
if ($rowCount == 1) {
$cookieExpiration = time() + 757368000; //1 year
setcookie("username", $username, $cookieExpiration);
} else {
$message = "Invalid username or password. <br/>Don't have an account? Click here to register.<br/><br/>";
}
}
?>
<html>
<!--Database Connections--> is HTML output, even if it is just a comment. Remove that and try again.
EDIT:
There is also a space between the PHP blocks. Try putting the include in the main PHP block.
Generally that means you have sent something to client prior to setcookie() call.
Do simple test:
<?php
ob_start();
include "../../includes/dbpractice_con.php"; ?>
# ... rest of your code... #
and before setcookie() call add line
ob_get_clean();
just to be sure that no output was made earlier.
Anything outside of <?php ?> is HTML and is sent to user. So this
<!--Database Connections-->
<?php include "../../includes/dbpractice_con.php"; ?>
outputs <!--Database Connections--> as HTML comment. Another possible output is here
<?php include "../../includes/dbpractice_con.php"; ?>
<?php ...
at least you have new line character between two PHP tags, which is also unwanted output.
You can't have anything to echo, print_r, var_dump data before cookieset() call, check manually for these functions.
Always check all included scripts (with include, require, etc).
BE SURE THEY START WITH <?php WITH NOTHING BEFORE and END WITH ?> FOLLOWING NOTHING.
this is good example:
<?php
// some lines
?>
these aren't
something<?php ?>
or
<?php ?>something
or
<?php ?>
(if file has been saved as UTF-8).
Look at your dbpractice_con.php, check is it saved as ANSI (from notepad check with save as dialog), be sure that everything is between and no one character is before and after the tags. Don't use multiple tags in same script because it increases risk of unwanted output.
Try this:
<?php
// Database connections
include "../../includes/dbpractice_con.php";
//Declare variables
// ... proceed with code ...
If this doesn't work then the problem is probably in dbpractice_con.php

PHP Header relocating and $_GET

I have a website that allows users to upload a picture, but I don't want any nudity in the photos. I found a scan written in php that I have succesfully implemented. The file and record are deleted if nudity is found to be in the file. I am just having trouble alerting the user as to why there pic wasn't kept. It just reloads the page. What could be the problem?
This code is the beginning of non commented code in my new2.php file:
if (isset($_GET['error'])) {
echo "Nudity found. Please try again with a more appropriate picture.";
sleep(5);
header("Location: new2.php");
}
This code is the code that scans the pic for nudity:
if($quant->isPorn()) {
$q = "delete from $table where id='$id'";
$result = mysql_query($q);
unlink("pics/".$picfile);
header('Location: new2.php?error=1');
} else {
header("Location: index.php?id=$id");
}
Any help would be greatly appreciated!
Your echo output won't be seen by the user. Output hasn't been sent to the browser yet, that happens at the end of your script. You redirect before that happens.
If you want to send a message, wait 5 seconds, and then redirect, do it client side.
<?php if (isset($_GET['error'])) { ?>
<p>Nudity found. Please try again with a more appropriate picture.</p>
<script>
setTimeout("self.location='new2.php'",5000);
</script>
<?php } ?>
Javascript is not needed. Just output the page containing your error, but change
sleep(5);
header("Location: new2.php");
to
header("Refresh: 5; url=new2.php");
This has the same effect as a <meta http-equiv="refresh">.
Don't do it from header. Use this instead:
<script> location="whatever.php?a=1"; </script>

Placing Header Location as Sql Die action

I was curious to know if i could do this, but found no examples on line
$info_find = mysql_query("SELECT info FROM sets WHERE category = '$selected_cat'")
or die( header ("location: index.php"));
Firstly doing it as above doesn't work. Can it be done?
Are there any drawbacks?
die() just writes its parameter out, it doesn't execute it. So a "or die()" construct will not help you there.
You can consider something like
or die(createRedirect("index.php"));
with
function createRedirect($where) {
$s='<html><head>';
$s.='<meta http-equiv="refresh" content="1; url='.$where.'">';
$s.='</head><body>If you are not automatically redirected click here';
$s.='</body></html>';
return $s;
}
if you are willing to accept the downsides of client-sided redirection
You can rewrite your code as
$info_find = mysql_query("SELECT info FROM sets WHERE category = '$selected_cat'") ;
if ($info_find === FALSE) {
header ('location: index.php');
die();
}
But, before use the header function, be sure you haven't send any output to the browser.

PHP setcookie warning

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.

Categories