How to fix PHP sprintf behavior? - php

Context
PHP
XAMPP
Why does this not print anything?
$a=sprintf('<s');
echo $a;

Are you outputting into a browser? The <a could be interpreted as the start of a tag (which happens to be incomplete/unclosed) and therefore hidden. If this is the case, check the page's source. Never trust the main browser window when debugging script output, as it'll hide things from you by design.

It works fine on my Linux machine.
$ php <<< '<?php $a=sprintf("<s"); echo $a; ?>'
<s
You might be getting bitten by buffering. Try adding a newline to your printout, or use var_dump().
echo "$a\n";
var_dump($a);

It does print <s
<swesley#ubuntu:~$ cat blah.php
<?php
$a=sprintf('<s');
echo $a;
?>
wesley#ubuntu:~$ php blah.php
<s
wesley#ubuntu:~$
My guess is that your running this in a browser and that interprets it as the start of a html tag.

If you view source on your rendered html you will see that it is in fact there.
you have to escape the html character "<" otherwise your browser will try to render it.
$a=sprintf('<s');
echo $a;
Reference

Related

Render html to page from database PHP [duplicate]

How would one go about showing PHP code on user end. Sort of like w3School does?
Having lets say a grey area div, and then showing the code in there without activating it?
You can use html entities <?php in the html it will be rendered as <?php
You can use htmlspecialchars to encode your code to use html entities.
Use <pre> or <code> tags to wrap your code.
Take a look at http://php.net/manual/en/function.highlight-string.php to further see how you can make the code look pretty.
Since passing a large block of code to highlight_string() can be messy, you may want to look at output buffering in combination with highlight_string to output colorized php code.
Something like:
<?php
ob_start();
?>
phpinfo();
echo "this echo statement isn't executed";
<?php
$code = ob_get_clean();
highlight_string($code);
?>
Simply you can use following code to display php code on webpage.
highlight_string("<?php print('This is php code.'); ?>");
It will give output like
<?php print('This is php code.'); ?>
The first step is to not wrap that code in PHP tags. So instead of this:
<?
var sample = "code";
?>
You would have this:
var sample = "code";
It's not the code itself which triggers the server-side compile from the PHP engine, it's the tags which indicate to that engine what blocks of the file are code and what are not. Anything that's not code is essentially treated as a string and output to the page as-is for the browser to interpret.
Once you're outputting the code, it's then a matter of formatting it. The old standard is to wrap it in pre tags to get rid of HTML-ish formatting:
<pre>
var sample = "code";
</pre>
You can also apply CSS style to the pre tags (or any other tags you want to use for displaying code, such as div) as you see fit.
There are also very useful code syntax highlighting plugins and tools to make the code a lot "prettier". Google-code-prettify often comes highly recommended.
Typically this is done by showing code within <pre> or <code> tags.
You can use this template........
######################################################################
echo "<h2><br>Source Code of ".basename((string)__FILE__) . "</h2><hr>";
show_source(__FILE__);
echo "<hr>";
echo "<h2>Output of ".basename((string)__FILE__) . "<hr></h2>";
#######################################################################
It will show the source code and output following.
use the header function of php, this will rea
<?php
header("content-type: text/plain");
?>
The PHP code will just be a string that you can echo or print onto the page, no different than any other data you want PHP to display for you. If you want to keep the formatting (ex. the indentation), put it inside a <pre><code> block.
Ex:
$php_code = '<?php $foo = bar; ?>';
echo "<pre><code>$php_code</code></pre>";

beginner's curiousity

I have a following question. I have put a long text (variable type LONGTEXT) into MYSQL database - through command line. Somewhere in this text there's a <br> tag, and near the end of text there's <?php phpinfo(); ?>. If i type SELECT * FROM mytable WHERE id=1, this whole text shows as it is, so it is unaltered (read: both <br> AND <?php phpinfo(); ?> are there. But when I submit query via php like this:
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
echo $row[1];
}
}
Then the text is displayed exactly as I want it on my webpage, that means that <br> tag is processed by the browser as newline, AND <?php phpinfo(); ?> part is IGNORED. That is actually exactly what I want. But my question IS: WHY doesn't <?php phpinfo(); ?> part get processed via browser?? Does the PHP's echo function ignore the <?php tag??
Thanks in advance for explanations.
Because echoing a string is not the same as evaluating it.
PHP generates HTML, which is then processed by the browser. However a string containing PHP code won't be evaluated unless you specifically put it through eval() (hint: DON'T!)
Browsers don't process PHP. It is a server side technology.
Your PHP is reading some text from the database and outputting it to the browser. That the text includes the string <?php is immaterial, it is output from the PHP programme, not part of the script.
When the browser parses it, it just looks like invalid HTML and it tries to perform error recovery (more or less ignoring it as an unrecognised tag).
try this in a new empty browser window:
javascript:document.write('<b>hello <?php ?> is here!</b>');
Then open up firebug/inspector.
In safari, the <?php ?> thing seems to be interpreted as/converted to a comment.
PHP echoes anything you throw to it. If you want to execute the longtext, use eval, if you want to properly display it, you could use the http://php.net/manual/en/function.htmlentities.php function for example.

Output PHP delimiter (<?php, ?>) without PHP interpreting the delimiters

I run PHP in JavaScript files, e.g....
var = '<?php /*some code*/ ?>';).
I need to use JavaScript to scan a string for PHP delimiters (the < ? php and ? > that open and close PHP).
I already know the code using JavaScript...
if (b.value.indexOf('<?php')>-1) {alert('PHP delimiter found.');}
What I'm having trouble with is that I need to keep the ability for PHP to be interpretted in JavaScript files (no exceptions). I simply need to output the delimiter strings to the client in JavaScript and not have them interpreted by the server.
So the final output (from the client's view) would be...
if (b.value.indexOf('<?php')>-1) {alert('PHP delimiter found.');}
With the following code...
if (b.value.indexOf('<?php echo '<?php'; ?>')>-1 || b.value.indexOf('<?php echo '?>'; ?>')>-1)
I get the error: "Parse error: syntax error, unexpected T_LOGICAL_AND"
Javascript will never find the <?php in your strings because simply, they have already been parsed by your PHP Server. Javascript is a client-side script and is executed after your server-side scripts.
You could take advantage of Javascript's ability to parse hex as a character:
if (b.value.indexOf('<\x3fphp')>-1) {alert('PHP delimiter found.');}
In Javascript '<\x3fphp' is exactly the same thing as '<?php', but it has no meaning in PHP.
Use output buffering on the PHP, then htmlspecialchars() on the buffered output. You then search for the HTML entities with the JavaScript.
the first thing that came into my mind and should work is this simple, little "cheat":
<?php echo '<'.'?php'; ?>
the php interpreter doesn't see a <?php, but the output is as desired.
<?php echo '<?php'; ?> ... <?php echo '?>'; ?>

Do I need to escape this?

It might be a bit unusual, but I need to echo <?php. However, I think that PHP treats it as an actual <?php and starts executing code instead of treating it as a string. How can I escape <?php and ?> so they can be treated as strings? There was nothing in the manual about this.
Thanks, I know this is a bit unusual.
just use htmlentities function
<?php echo "<?php echo \"hello\" ?>" ?>
prints out <?php echo "hello" ?>
Check out PHP's sourcecode of functions on how they print out data.
http://in2.php.net/source.php?url=/manual/en/function.htmlentities.php
You can use the < and > html entities (to replace '<' and '>'). These are only handled in the browser, so PHP would not attempt to run that code.
In HTML,
<?php
Or in PHP:
echo htmlentities('<?php');
If this is your code:
<?php
echo '<?php';
?>
And you run that as a web page, you will see nothing. But not because PHP is not echoing your string <?php, but because the browser sees < and thinks that's the start of a tag, and tags are not displayed. It's obviously an error, but that's what the browser is doing.
To get around this, escape the < part, use htmlentities():
<?php
echo htmlentities('<?php');
?>
Which when it gets echoed, will result in HTML source of:
<php
Which when displayed in the browser shows:
<?php
If they are echoed in a string they will not be executed.
echo '<?php ?>'; // prints <?php ?>
echo "<?php ?>"; // prints <?php ?>
No, you do not have to do anything special.

php's $_SERVER['REQUEST_URI '] encoding problem?

When I output $_SERVER['REQUEST_URI']; on:
http://localhost/tools/?tool=cs&sub=1
I get:
/tools/?tool=cs⊂=1
Is there other solution to get /tools/?tool=cs&sub=1 besides using & instead of & ?
It's because you're echoing it to your browser - &sub is being interpreted as an HTML entity (⊂).
If you echo htmlentities($_SERVER['REQUEST_URI']); you'll get what you expect.
You have to use the right encoding for the environment you're in - in HTML that means using &.
try this
echo urldecode($_SERVER['REQUEST_URI']);
How are you outputting this value? If you're dumping it to the browser, are you sure it's not trying to 'decode' embedded ampersands?
Try a file with just
<?php phpinfo();
and look to see what the value is displayed as (near the bottom)

Categories