I am using php 5.3.6 and below is my code and it is producing an error
Warning: Cannot modify header information - headers already sent by (output started at ............
<?php
ob_implicit_flush(true);
print "<pre>";
$loop = true;
$counter = 0;
while ($loop) {
$counter++;
// some code
print "some output of code. \n";
if ($elapsedTime > 300) {
$loop = false;
print "5 minute passed and loop ended. \n";
}
}
print "</pre>";
ob_end_flush();
header("refresh:5;url=test.php" );
?>
what I wanted to do is displays contents from each loop while the loop is active.
then when the loop is ended I need to flush all the previous output or header and send a new header to refresh the current page.
The short version is, you can't. You can not send headers after the content.
You could print out a link at the end, that the user can click on to refresh the page. Or if the generation will take a fixed amount of time (say 5 minutes) you could put an HTML meta refresh tag on the page that goes after 5 minutes and 1 second.
http://en.wikipedia.org/wiki/Meta_refresh
Header redirects generally take the form Location: ?test.php, if there's a new format that looks just like the meta refresh format, I'm not aware of it, and it would seem to violate how the other headers work (namely key: value). Short version: I don't think that header will work even if it does go first.
As suggested by preinheimer the header must be sended before each page ouput. Without using the headers you can use one row of javascript code for a simple redirect. This may be a solution for you:
<?php
print "<pre>";
$loop = true;
$counter = 0;
while ($loop) {
$counter++;
// some code
print "some output of code. \n";
if ($elapsedTime > 300) {
$loop = false;
print "5 minute passed and loop ended. \n";
}
}
print "</pre>";
# The php code has ended and the javascript code is ready for redirecting... (external to php tags)
?>
<script type="text/javascript">
window.location="http://www.example.com/";
</script>
Related
I have made an ordering system that right now goes from the product form to a review page. I have the page set up to use PHP loops to show what products they selected form the prior page and it works great. Now I need to have a "order" button that emails the order on. I the practice of writing less code, I would like to not have to re write all the code to email this form on another php form. Is there a way to have email headers on this page and dump the generated html into the body of the email to send?
Here is how I loop the form contents from the previous page. Basically it goes though all the products and if its there, show them on the review. If not, dont.
for ($i=0; $i<8; $i++) {
if (!empty($_REQUEST['driver'][$i]['select'])) {
//add the club to the total of clubs
$club = $_REQUEST['driver'][$i]['select'];
array_push($club_total, $club);
//add the price to the cost
list($shaft, $price) = explode(":", $_REQUEST['driver'][$i]['shaft']);
array_push($cost, $price);
//show the user
echo '<h3>' .$_POST['driver'][$i]['name']. ' - $'. money_format('%i', $price).'</h3>';
echo '<ul>';
if (!empty($_REQUEST['driver'][$i]['left'])) {
echo '<li><strong>Left Handed</strong></li>';
}
echo '<li>Length: '.$_POST['driver'][$i]['length']. '"</li>';
echo '<li>Shaft: '.$shaft. '</li>';
if (!empty($_REQUEST['driver'][$i]['hossel'])) {
echo '<li>Purist Hossel: ' .$_POST['driver'][$i]['hossel'].'</li>';
}
if (!empty($_REQUEST['driver'][$i]['color'])) {
echo '<li>Purist Color: ' .$_POST['driver'][$i]['color'].'</li>';
}
echo '</ul>';
}
You could capture your html in the output buffer, then store it in a variable for later use (as in, putting it into the body of an email).
ob_start();
for ($i=0; $i<8; $i++) {
// ... your code
}
$my_html = ob_get_contents();
ob_end_clean();
then put $my_html as your email body and send it along.
The idea of putting it all in a variable the first time around also works, but this might save you some effort of rewriting everything.
Instead of echoing out the html, build up a string, so $out .= "your html" etc, then you can easily set that lump of html to the body of the email function.
I am assuming you know how to code that, else I'll add code example for you.
I have created a php page to display a image from a set of five images. The image is displayed based on the data read from a text file.Another application is continuously updating data in that text file.So my php page need to read data from that file whenever the file is updated and display image based on that data. I created a infinite loop to read data. But when i tried to access the php page from a browser , it is not loading because of the infinite loop.
$myfile1 = fopen("readfile.txt", "r") or die("Unable to open file!");
$readJsonData = fread($myfile1,filesize("readfile.txt"));
fclose($myfile1);
$obj = json_decode($readJsonData);
$urllogo = 'tatalogo.png';
if(($obj->{"FrontLeft"}) == "TRUE")
{
$url = 'images/FrontLeft.png';
}
else if(($obj->{"FrontRight"}) == "TRUE")
{
$url = 'images/FrontRight.png';
}
else if(($obj->{"RearLeft"}) == "TRUE")
{
$url = 'images/RearLeft.png';
}
else if(($obj->{"RearRight"}) == "TRUE")
{
$url = 'images/RearRight.png';
}
else
{
$url = 'images/Normal.png';
}
// infinite loop
while(1)
{
//reading from the file and refreshing the page.
}
In PHP Set header like this to refresh the php page
header("Refresh: 5;url='pagename.php'");
In HTML Head tag
<html>
<head>
<meta http-equiv="refresh" content="5;URL='pagename.php'">
</head>
</html>
<?php
Your php script here..
?>
Using Javascript
<script type="text/javascript>
window.setInterval(function(){
reload_page();
}, 5000);
//Here 5000 in miliseconds so for 5 seconds use 5000
function reload_page()
{
window.location = 'pagename.php';
}
The most reasonable way to do it would be to use the client side to refresh the page.
Get rid of all that infinite loop stuff on the PHP side. PHP will only output the image as it stands at the moment it was generated.
On the client side you could do something as simple as:
<META http-equiv="refresh" content="5;"> to force a refresh every 5 seconds.
If you only want to update when the file is updated you have to get more advanced. You could do an ajax call that checks if the file has changed and if so it refreshes. Websockets would be another option.
You could possibly do some nasty hack on the PHP side to make it work using ob_flush and sleep and header within a loop that checks to see if the file has changed but this will cause you to lose sleep once you realize what you've done. As pointed out below, this would never work.
I made php code to add something like posts on side and above is time of adding it but only first post are getting updated time but next posts have time of first one (first are getting 16:35 and next have 16:35 also) here is code of data.php
session_start();
$dzien = date("d");
$mies = date ("m");
$rok = date("Y");
$_SESSION['data'] = $dzien.".".$mies.".".$rok;
$godz = date("G");
$min = date("i");
$_SESSION['czas'] = $godz.":".$min;
header("Location: edit.php");
exit();
And here is file.php which add posts and time:
session_start();
header("Location: data.php");
$tekst ="<div class='wpis'><div class='data' ><p class='tdata'>".$_SESSION['data']." ".$_SESSION['czas']."</p></div><div class='klaska'>". $_POST['pole']."</div></div>";
$fp = fopen("inne.txt", "r");
$stare = fread($fp,filesize("inne.txt"));
fclose($fp);
$ntekst = $tekst.$stare;
$fp = fopen("inne.txt", "w");
fputs($fp,$ntekst);
fclose($fp);
header("Location: index.php");
exit();
I want to get in next posts updated time of add
Line 2 of file.php prepares a header to redirect to data.php, but at the end of the file you prepare another header to redirect to index.php. See comment by shutout2730 at yahoo dot com in link:
Likely the first redirect is replaced by the later one and hence does nothing. There appear to be exceptions based on output echo, print and buffering.
Are you running data.php from someplace else to initialise it?
I suspect data.php is not called as you expect and hence session is not being updated.
I have a problem with this program of Sessions & Cookies.
Plz see the following code:-
<?php
session_start(); //session starts
if(! isset($_COOKIE['cnt']))
{
#$_SESSION['nv'] = 1;
}
else
{
#$_SESSION['nv'] += 1;
}
$val = $_SESSION['nv'];
echo $val;
setcookie("cnt", $val, time()+30 );
echo "<h1>No. of visits=".#$_COOKIE['cnt'] ."</h1>";
if (#$_COOKIE['cnt'] == 5)
{
setcookie("cnt", 0, time()-30);
session_destroy();
}
?>
It is not giving the correct output.
When I run the program for the first time, it shows:
No. of visits=
Means nothing..
& when I run the program for the second time, it shows:
No. of visits=1
I want that my output should be displayed as "No. of visits=1" when I run the program for the first time. But it shows this output at 2nd time.
Do help me please..
The cookie set by setcookie is sent along with the HTTP response the server sends to the client and, quoting the documentation:
Once the cookies have been set, they can be accessed on the next page
load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
You should print the session var
echo "<h1>No. of visits=" . $_SESSION['nv'] . "</h1>";
So i'm writing this code so that you either get forwarded to a certain page if you're the first one to hit the link, or you are sent back to the original page after being displayed a message if you're not what beginner mistake am i making?
<?php
$count = file_get_contents('counter.txt');
$count = trim($count);
if ($count="0")
{
$count = $count + 1;
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
header("Location: newpage.html");
}
else
{
fclose($fl);
echo "Sorry but the item has already been sold out";
header("Location: oldpage.html");
}
?>
As for the delay, you can accomplish it two different ways. The first is to use PHP header (like you are currently doing), but change it to look like this:
<?php
header("refresh:5;url=oldpage.html");
echo "Sorry but the item has already been sold out";
?>
The other way is to echo out a piece of HTML code, the meta-refresh:
<?php
echo '<meta http-equiv="refresh" content="2;url=oldpage.html">';
echo "Sorry but the item has already been sold out";
?>
In both examples, 5 is the amount of seconds until the refresh. Experiment with each one to see if it will fit your needs.
This might be some sort of syntax that I'm not familiar with, but none of my scripts have ever had the
<? code
I simply use
<?
Also since you did not delay our header tag the user will not see the previously echoed statement above it. It will automatically redirect before the page has time to output fully.