This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
error:
Warning: Cannot modify header information - headers already sent by (output started at functions.php:37) in functions.php on line 207
add.php
<?php include('functions.php'); ?>
<?php global_header("Add"); ?>
<?php page_navigation(); ?>
<?php
// If no form has been submitted, present form
if (empty($_POST))
{
add_form();
}
// if a form has been submitted
else
{
// if form_validity() == 1, proceed to connect
if (form_validity() == 1)
{
// connect to mysql + database
connect();
// get values from form, insert into database
$saleItemCheck = isset($_POST['saleItem'])?"y":"n";
$discItemCheck = isset($_POST['discountedItem'])?"y":"n";
$sql=("INSERT INTO inventory (name, manufac, model, descrip, onhand, reorder, cost, price, sale, discont, deleted)
VALUES ('$_POST[itemName]', '$_POST[manufacturer]', '$_POST[model]', '$_POST[description]', '$_POST[numberOnHand]',
'$_POST[reorderLevel]', '$_POST[cost]','$_POST[sellingPrice]',
'$saleItemCheck', '$discItemCheck', 'n')");
// if the query doesn't work, display error message
if (!(mysql_query($sql))) { die ("could not query: " . mysql_error()); }
add_form();
redirect("view.php");
}
else
{
// if form is not valid (form_validity returns 0), display error messages
add_form();
}
}
?>
<?php page_footer(); ?>
My redirect function
<?php
function redirect($page)
{
header('Location:'.$page); <------------------------------------ line 207
}?>
Header function
<?php
function global_header($page_title)
{
$content = '<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DIMAS OLYMPIC WEIGHTLIFTING EQUIPMENT - ' . $page_title . '</title>
<meta name="description" content="BTI320 Assignment 1">
<meta name="author" content="Marcel Olszewski - 078-681-103">
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<div><img src="logo.png" id="logo" alt="I (Marcel Olszewski) created this in photoshop" /></div>';
echo $content; <------------------- LINE 37
}
?>
It worked before, doesn't now, not too sure why.
You don't need to close and re-open the PHP tag -- this:
}
}
?>
<?php page_footer(); ?>
can be converted to:
}
}
page_footer();
You don't even need the closing PHP tag. By closing the tag you run the risk of leaving whitespace after the closing tag which will be echoed out to the browser and will cause the issue you're having.
In general, you don't need to close your PHP tags if they come at the end of a file.
Edit: Here's your problem:
Change:
<?php include('functions.php'); ?>
<?php global_header("Add"); ?>
<?php page_navigation(); ?>
<?php
to:
<?php include('functions.php');
global_header("Add");
page_navigation();
This is because you have already outputed some stuff to the stdout. Look at your code. If you have not explicitly done that, it might be that there are errors in the execution of your code (like MySQL connection error, for instance) and the display_errors is On in your php.ini making the error messages being written prior to your header call.
Also, if the encoding of your PHP code has changed, a BOM character might have been prepended to your code, being an involuntary, but very real output before you send your headers.
Another thing that could have caused the problem, is having close-open ?><?php tags which might leave whitespaces (or even other characters) in your code in between the PHP blocks, sending unnecessary output to the browser across HTTP, causing the problem.
It looks you had output buffering on before because you definitely have output before you try to redirect.
Related
I would like to update html page several times during my PHP script execution.
I understand, that when I requested something like http://index.php the index.php script will return html page in response.
I have my index.php code like:
<?php
set_time_limit(120);
$_SESSION['my_number'] = 0;
//header('Refresh:2 url=http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
?>
<!DOCTYPE html>
<html lang="en">
<head/>
<body>
<p style="color:blue;">my_number is <?php echo $_SESSION['my_number']; ?> </p>
</body>
</html>
<?php
foreach (array(1,2,3,4) as $v) {
$_SESSION['my_number'] = $v;
sleep(10);
}
?>
It displays only my_number is 0
If I move foreach before html body - it display my_number is 4.
But I would like to get the html page with the updating my_number every 10 seconds.
So the number should be overwriteen every 10 seconds.
I tried to add
header('Refresh:2 url=http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); but still no luck.
Somehow I need to send several responses to browser before exiting the php script. Fist response to load page, others - to update my_number values.
I prefer to get solution only within php. Not using javascript if possible.
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
How do I get PHP errors to display?
(27 answers)
How can I get useful error messages in PHP?
(41 answers)
Closed 5 years ago.
Learning PHP and MySQL. Made a short script that retrieves contents from the database, and populates it in a tag in my html header.
index.php:
<?php
$link = mysqli_connect('localhost', 'root', 'abdullah');
if (!$link) {
echo "Could not connect";
exit();
}
if (!mysqli_select_db($link, 'chitra')){
echo "Could not find database";
exit();
}
$query = 'SELECT * FROM photos;';
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
$categories[] = $row['category'];
}
include 'main.html';
?>
main.html:
<!DOCTYPE html>
<html>
<head>
<title>Chitra</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<header>
<div id="header_username">username</div>
<div id="header_cat">
<select>
<?php foreach ($categories as $category): ?>
<option><?php echo htmlspecialchars($category, ENT_QUOTES, 'UTF-8'); ?></option>
<?php endforeach; ?>
</select>
</div>
</header>
<main>
TODO
</main>
</body>
</html>
This code was initially working. I started working on the body for a while, until suddenly, it started returning me a blank white page. I removed my main content to start over from scratch, but it still give me the same result.
I put echo statemnts throughout the PHP file, everything is executing fine until right before the include statement. I checked my Apache, MySQL, PHP installations, checked that everything is up and running. Everything is. I can't figure out the issue.
You can not use raw PHP functions etc in HTML files,
try to change the extension to .php maybe this helps you.
I am trying to display different content on a page based on some options.
Also, I am trying to avoid using php echo for all the html output.
I came up with the following solution accidentally, and now I'm confused about how it actually works.
test.php
<?php
function get_content() {
$page = 0;
if($page == 0)
include('page0.php');
else
include('page1.php');
}
?>
<html>
<body>
<?php echo get_content() ?>
</body>
</html>
page0.php
<?php
$link = "http://www.google.ca";
$name = "GOOGLE";
?>
<?= $name ?>
page1.php
<?php
$link = "http://www.yahoo.ca";
$name = "YAHOO";
?>
<?= $name ?>
It seems like the php interpreter would end up including html tags into a <?php ?> block when it reaches the following line, but somehow, this code works, and the outputted html is valid.
include('page0.php');
Can someone explain what exactly is going on here?
When a file is included, parsing drops out of PHP mode and into HTML
mode at the beginning of the target file, and resumes again at the
end. For this reason, any code inside the target file which should be
executed as PHP code must be enclosed within valid PHP start and end
tags.
From PHP manual, include function.
I've managed to boil this problem down to the bare essentials: So I've got two simple .php files:
TEST.PHP
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>My Page</title>
<script src='/root/js/jquery-1.6.3.js'></script>
<script>
$(document).ready(function() {
$.ajax({
url : 'test_ajax.php',
type : 'GET',
timeout : 10000,
dataType : 'text',
data : { 'param' : 'whatever' },
success : function(data,status,jqXHR) {
$('#status').html(data.length+"-"+data);
},
error : function(jqXHR,textStatus,errorThrown) {
$('#status').html("Error: "+textStatus+" , "+errorThrown);
},
complete : function(jqXHR,textStatus) {
}
});
}); // end ready
</script>
</head>
<body>
<p id='status'>
</p>
</body>
</html>
and TEST_AJAX.PHP
<?php
?>
<?php
echo "ok";
?>
The data that should be returned from TEST_AJAX.PHP is "ok". However, what is being retrieved by the jQuery/ajax code is a THREE character string which is outputted as " ok" (although the character at [0] is not equal to " ").
This ONLY happens if I have the two php blocks in TEST_AJAX. If I delete the first block, leaving only the second one, then it returns "ok" as a two character string, as it should.
What on earth is going on here? AFAIK, it should be perfectly acceptable to have multiple php blocks in a .php file - even though it's obviously unnecessary in this simplified example.
Note that there is a blank line between the two php blocks. It also get's displayed. Change it to
<?php
?><?php
echo "ok";
?>
and it should be fine.
PHP is a templating language. Everything outside of your tags will be not parsed and returned literally.
Example
<html>
..
<body>
<?php echo "Hello world";
// white space within the tags
?>
</body>
</html>
Will return
<html>
..
<body>
Hello world
</body>
</html>
White space in the PHP blocks is ignored, but the space between the PHP blocks will always be returned. You may have better luck printing a json string like:
{'response':'ok'}
Then change your data type to json in your ajax request, and accessing the response with data.response
That way any extra spaces will not affect parsing
I do admit this question is going to be a bit vague, but I will try to explain what I'm trying to accomplish by a few examples. I have some PHP code that loads a bunch of variables from the MySQL database, contains some declarations, some functions to quickly output HTML code etc. However I would love to do all that stuff before anything is sent to the client.
So I do:
<?php
include("somefile.inc");
function bla()
{
...
}
if (fails)
echo "Error: ...<br />";
?>
<!DOCTYPE>
<html>
<head>
<script>
...
<?php echo $someString; ?>
...
</script>
</head>
<body>
...
</body>
</html>
This is all fine and ok, until I get an error. The echo will not show in the browser because it's before all HTML... So I modified:
<!DOCTYPE>
<html>
<head>
<script>
...
<?php echo $someString; ?>
...
</script>
</head>
<body>
<div class="error_block">
<?php
include("somefile.inc");
function bla()
{
...
}
if (fails)
echo "Error: ...<br />";
?>
</div>
...
</body>
</html>
Now I can actually see errors, which is good. But now the problem arises that in the header, or scrips, I cannot access variables that will be loaded later on in the newly created error_block.
I really don't like splitting the code in the error_clock to some above the HTML document and some in the error_block. And I also don't want to use PHP's die() function which abrubtly ends the execution.
Anyone can give their 2 cents on this issue? Thanks.
If you're looking for an alternate solution, I have one for you. What I like doing is having the logic in before the DOCTYPE
if(error) { $error = "Please do something" }
Than, down in the document I have a div just for the error (Thanks #Dave for the input)
<?php echo $error != '' ? '<div id="error">' . $error . '</div>' : ''; ?>
This div will not appear if there isn't an error (meaning $error is empty) and it makes it easier for you to style the error message the way you would like
#error { color:red; }
If you want to get fancy, you can use some jQuery to hide/show the div so that the error doesn't have to persist.
$('#error').show().delay(7000).fadeOut();
You should look into using try-catch blocks and generating exceptions if you want to do some post-processing with the error message, which includes display.
What is often forgotten is that PHP is an INLINE programming language in essence, this means it is designed to be processed by the server as the server reads down the page, and with this it is designed to be split up into chunks. Recently OOP (Object Oriented Programming) has been introduced to PHP making it more flexible.
So with this information in hand I would take the OOP path in this case and do something like:
<!DOCTYPE>
<?php
include("somefile.inc");
function bla()
{
...
}
function failureError($code){
if(!empty($code)) ...
}
if ($a = $b) {
code goes here
} else {
$code = 'error123';
}
?>
<html>
<head>
<script>
...
<?php failed($code); ?>
...
</script>
</head>
<body>
...
</body>
</html>
By writing using functions you can cut down your development time and group the majority of your code just calling what you need when you need it.
Another way of declaring your error class(es)/functions to help with server response time is to do something like:
if ($a = $b) {
code goes here
} else {
include("errorStuff.php");
}
This will only include the error class(es)/functions when an error is encountered.
Just remember when you're writing PHP with OOP techniques like this that the server will take longer to process the script than if you write inline. The biggest advantage to an OOP basis is it will cut down your development time and if done correctly it will make it easier to administer future updates to your script.