Update html page values with PHP - php

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.

Related

Call PHP variable in HTML

I wrote a code involving nested PHP and HTML parts as below. Why variable "v" is not displayed, But the variable "u" is?
<?php
$v= rand (1,15);
$u= rand (1,15);
$h = <<<EOD
<!DOCTYPE html>
<html>
<body>
<p style="margin-top:80px">This is a random number:</p>
<?php echo $v ?>
</body>
</html>
EOD;
echo $h;
?>
<html>
<body>
u=<?php echo $u ?>
</body>
</html>
PHP has two modes.
Inside <?php...?> (and other PHP tags) PHP code is evaluated
Outside those tags, code is streamed directly to the output
You have <?php echo $v ?> inside a PHP section (inside a string created with HEREDOC).
It doesn't trigger PHP evaluation of the content when the string is created because it is just part of the string. It doesn't trigger PHP evaluation when you later echo it because you are just echoing a string.
<?php echo $v ?> will be in the (invalid) HTML sent to the browser, and the browser will treat it as an unknown tag. The value of $v will be one of the attributes. The browser won't render anything for this unknown tab, but you will be able to see it in the Developer Tools Inspector or with View➝Source
Rethink your application design. Don't try to store strings containing PHP code. Generate the string with the data you need in it in the first place.
$h = <<<EOD
<!DOCTYPE html>
<html>
<body>
<p style="margin-top:80px">This is a random number:</p>
$v
</body>
</html>
EOD;
echo $h;

PHP GET parameter not showing without page refresh

any idea what is wrong here. I generate link list from database. When I click link, it navigates to another page, but echo is missing. However, if I check "View page source", I can found my echo. If I want to see it on page, I need to refresh page manually, so I can see my echo. I don't to refresh page, so any idea what is problem here?
Source codes:
page.php:
<?php
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
foreach ($line as $col_value) {
echo '<li>'.$col_value.'</li>';
}
}
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>
test.php:
<?php
echo 'TEST ';
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>
In your test.php page, replace your code with the following code:
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
echo 'TEST ';
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>
</body>
</html>
Let me know if it works now!
Edited: Explanation of why this solution worked
The image shown in the question showed 2 windows. The confusion starts there. The window on the left is the browser at work displaying the html code that was rendered, while the window on the right is the "Source Code"! What that means is that the browser probably didn't understand what TESTHELLO dbName meant and made a blank page, but when adding all the default tags, then the browser was happy to interpret it as text within the pages body.

Order of inclusion and interpretation for php and html

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.

Show a complete PHP Variable

im trying to show a complete Php Variable, my code looks like:
<!DOCTYPE HTML>
<html>
<body>
<?php
if (isset($_POST["appendedInputButtonRoom"])) {
$CodeRoom = "<room xs=\"zwinky3\" ac=\"f\" sf=\"N\">" .$_POST["appendedInputButtonRoom"] . "</room>";
echo $CodeRoom;
}
else
{
echo "Error";
}
?>
</body>
</html>
So, for example: I enter "dsf" into the textbox, click "add" and PHP starts to work. It will just show the "dsf" part on the Site, but it should be supposed to show the code like:
<room xs="zwinky3" ac="f" sf="N">dsa</room>
like it does in the source code.
Any one got a idea?
You'll have to html encode your output so the browser wont read the tags
echo htmlspecialchars($CodeRoom);

Cannot modify header information [duplicate]

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.

Categories