Show a complete PHP Variable - php

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);

Related

Update html page values with 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.

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.

How can I access a variable in one block of PHP code in another block of PHP code in the same file?

I have something like this:
PHP code at the start:
<?php
$variable="example";
?>
Then HTML code:
<html>
<head>
<title>Title</title>
</head>
<body>
Then again PHP:
<?php
// code comes here, and I want to access variable $variable here.
?>
And then HTML code ends:
</body>
</html>
Is it possible to do this somehow? I don't want to create another file; I need to do this in this file.
Not Required unless if you are accessing it under functions ( as it will lose their scope)
test1.php
<?php
$var = 1;
//.. your code...
?>
<html>.....
<?php
echo $var; // prints 1
whereas the below code won't work...
<?php
$var = 1;
function displayVar()
{
echo $var; // You will get a notice .. !
}
Just do what you stated above and it will work.
<?php
$variable = 'Hello';
?>
<html>
<head>
</head>
<body>
<?php echo $variable; ?>
</body>
</html>
The above example will display a simple webpage with 'Hello' as the content. This is one of best strength of PHP actually.
try this
echo ($variable);
or
print($variable);
If it is the same file, yes it is possible, unless the variable is in a function. But this is a very simple question, that you could have tested yourself.

jQuery/PHP - Having more than one PHP block creates extra character of output when read by jQuery .ajax

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

Best practice: where to put the PHP code?

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.

Categories