php echo php to browser, not showing up, security issue? - php

What happen if i use the following?
<?php echo "<?php echo date('Y'); ?>"; ?>
i could not find an answer anywhere, and when i try it myself, i get:
<?php echo date('Y'); ?></td></tr></table>
However, it does not show up on front browser, only source.
So my question is, does this affect the html/browser/server in any way?
as i do not want to end up creating a security issue should user post their
own php code in a html only format, like a bio page etc.

It's because of the chevrons ('<' and '>'), because the browser interprets them as tags.
There are 2 ways you could get round this.
Either use the codes for special characters, so you would do:
<?php echo "<?php echo date('Y'); ?>"; ?>
Or, an easier way, use the htmlspecialchars() function:
<?php echo htmlspecialchars("<?php echo 'hi'; ?>"); ?>
More info on the htmlspecialchars() function can be found at http://www.php.net//manual/en/function.htmlspecialchars.php

It is not a security problem and will not have any effects on browser or server, at least not because of PHP code. Even if the string contains PHP code it will just be sent to the client which will not attempt to execute it.
The real problem when echoing user-defined HTML is the risk of attacks such as XSS. Users could include arbitrary scripts or images or scramble the rest of the page by inserting arbitrary tags. In other words: Users could modify the whole page with a single line of HTML.
In general, it's a bad practice to allow such arbitrary input. Have a look at strip_tags which provides a very basic level of protection.

Related

Why separate PHP from HTML in a code as much as possible?

Twice now that I have asked and was responded that I should separate PHP from HTML in codes as much as possible. Instead of using:
<?php
echo "<p>The value of x is $valuex greater.</p>";
?>
That I should use:
<p>The value of x is <?php echo $valuex; ?> greater.</p>
Is there any difference I should know other than the format?
One of the unique things about PHP is that it serves the purpose of both a server-side language and a templating language. Ideally, your code would be separated into controllers and views, where your controllers are pure PHP (without any HTML) and your views are mostly HTML (with minimal PHP). When you're writing a controller, PHP is just like any other server-side language. But when you're writing a view, PHP becomes a templating language, in which case HTML should rule.
Another good reason to separate the two is syntax highlighting. In your first example, most editors wouldn't realize that the text within the string is actually HTML, so they wouldn't know to apply syntax highlighting. This means your code will likely be harder to read than it could be, making life difficult for subsequent developers.
The difference is:
<?php $valuex = 6; ?>
<p>The value of x is <?php echo $valuex; ?> greater.</p>
Here you need to echo only php variable part.
<?php
echo "<p>The value of x is $valuex greater.</p>";
?>
Here you need to echo whole part.
You need echo in second one,
<p>The value of x is <?php echo $valuex; ?> greater.</p>
Or simply,
<p>The value of x is <?=$valuex ?> greater.</p>
Read: What's the best way to separate PHP Code and HTML?. Also read Escaping From HTML.
The output will be the same in both cases.
The first example is PHP outputting HTML code
The second example is HTML code with PHP inside it
The "Ideal" example is this:
<p>The value of x is <?=$valuex?> greater.</p>
On the first one change the syntax like
<?php
echo "<p>The value of x is ".$valuex." greater.</p>";
?>
and in the second one change to echo the value like
<p>The value of x is <?php echo $valuex; ?> greater.</p>
But both the notations are same,and work same
The reason for this is that frankly you'll want to always be as flexible as possible. However, mixing your php with html means that your php-core is mixed up with your template, thus you'll have an a lot harder time maintaining, altering & providing different templates/languages etc. Thus always keep it apart.
It's much easier to maintain your code, both HTML and PHP, when separating them.

PHP echo-ing a PHP code inside an echo

I'm quite new here. I'm trying to make a blog/journal site that allows users to post their own journal. I'm still quite reluctant on making it because I am really afraid of malicious code injections.
So here's a sample code:
<?php
$test = "<b>blah</b>"; //User input from SQL
echo "$test";
?>
What will come out is just the word "blah" in bold right? What I was trying to achieve was to echo "<b>blah</b>" instead. I don't want people to put some PHP codes that can actually mess up my whole web page. Please keep in mind that the variable $test is actually a MYSQL query, so that variable will be needed as an example. I know you can do echo '$test'; but it just comes out as "$test" instead. I feel like pulling my hair out I can't figure it out yet.
The second solution I know of is the htmlspecialchars(); function, but I want the strings to display as what I typed, not the converted ones...
Is there any way I can do that?
I think the OP wants the HTML itself to be output to the page, and not have the tags stripped. To achieve this, you can run the string first through htmlentities()
$test = '<b>blah</b>';
echo htmlentities($test);
This will output:
<b>blah</b>
Which will render in the page as
<b>blah</b>
Echo don't execute PHP code from string. This is impossible and this is not security hole in your code.
You can use a template engine like Twig for exemple.
If htmlspecialchars(); is not the one you are looking for, try the header() option.
header('Content-type: text/plain');
When you are gonna give <b>Hi</b> to a browser, it will be displayed in Bold and not the text be returned. But you can try this way, outputting it inside a <textarea></textarea>.
Or the other way is to use htmlentities():
<?php
$test = "<b>blah</b>"; //User input from SQL
echo htmlentities("$test");
?>

String variable to execute PHP code

What I want to do is pull html and PHP code out from a database and then execute it. So for example I may have:
<?php
$test = <<<END
<p> <?php
echo time();
?> </p>
END;
echo $test;
?>
What I want is to get $test to print
<p> 12:00PM </p> //right
instead of printing:
<p> <?php echo time(); ?> </p> //wrong
as occurs when I use the echo function.
Please do not tell me how to do the same thing with JavaScript or other work around. Instead stick to the question and remember the example is just an example to demonstrate my problem. The actual code is much more complicated.
I have looked at Javascript string variable that contains PHP code but none of the answers work.
Thanks,
Brett
I would strongly recommend against doing what you're asking to do. There are a number of very good reasons for this.
The answer to the question, as others have said, is to use eval(). However, eval() has several major issues with it.
Firstly, to follow-up from the comments on the question, code run through it is executed significantly slower than regular PHP code. Although PHP is a scripted language, it does have optimisations to make run faster. None of these optimisations work for an eval block, because the scripting engine can't know what the code will look like until it actually runs it.
Not only that, but loading the code from the database will also be slower than loading it from a file using a regular include() statement.
Secondly, eval() is one of the biggest security headaches you can have. An eval() statement will run any PHP code it is given, which means that an attacker can manipulate the code will be able to do anything on your server. In short, a single eval() statement in your code can turn a minor hack into a catastrophic one.
One alternative solution that doesn't involve changing your concept too much would be to save the PHP code to a file rather than the DB. This would allow you to simple include() it at the appropriate time, and would eliminate the speed issues discussed above. You could still use the DB to store it if you wished, and have it export to a cache file using a cron job or similar, or you could just save it directly to the file.
However, this solution wouldn't necessarily eliminate the security risks. You would still be running effectively arbitrary code, which would still mean that a hacker could do a lot of damage with a relatively simple hack.
I would therefore recommend re-thinking why you need to allow user-input PHP code to be entered into your software.
You can use eval() for this
$test = <<<END
<p> <?php
echo time();
?> </p>
END;
ob_start();
eval("?>$test");
$result = ob_get_clean();
Something like this might be useful...
<?php echo writedata($code_to_parse); ?>
<?php
function writedata($data){
if(substr($data,0,2)=="?>"){
eval($data);
// eval will run & echo the code immediately, so return an empty $code
$code="";
}else{
$code="$data";
}
return $code;
}
?>
Now you can handle either plain html & mixed php/html with one function call.
Sample data:
?>Bonjour. The time now is <?php echo $timenow; ?> in Paris.
<div class="bluebox">Perfect day for swimming</div>
There are some side effects using eval(), remember it will execute as soon as to call it, so can sometimes have unexpected results.

My site is vulnerable to this script..How do i patch it?

One guy tried to exploit it using this script
http://www.searchr.us/web-search.phtml?search=%22%3E%3Cscript%3Ealert%28String.fromCharCode%2872%29+String.fromCharCode%28105%29%29;%3C/script%3E
How do i stop it ?
And he also said that it is vulnerable to XSS and LPI...Please help me stop it.
Thanking You,
You need to HTML-encode all user-entered data that you output, including the user's search string.
To be safe, HTML-encode all values that are not explicitly meant to be HTML code.
The quick solution is to:
<?php echo htmlspecialchars($blah); ?>
instead of
<?php echo $blah; ?>
The long solution is to read a book on web site security.
Seeing as how that is a search query string, I'm guessing you're pulling the value directly from the query string and re-displaying it to the user?
Something along the lines of "Your search of 'something' returned 0 results"?
You need to encode any user entered data before displaying it.

Including dynamic HTML with PHP

I have PHP variables to place within an included HTML file. What's the best way of executing this?
//contents of file1.php
$variable1 = "text 1";
$variable2 = "text 2"
$newContent = include('file2.php');
echo $newContent;
//contents of file2.php
<p>standard HTML with PHP... <strong><?=$variable1?></strong></p>
<p><?=$variable2?></p>
This general method is considered OK but the actual code here doesn't work. Do I use file_get_contents() or include(), how do I execute the PHP within the includes file to output the correct contents?
Should I be using something like HTML>>>
What you're doing is fine, and you'll find that most people use the same exact method. I personally wouldn't use PHP short tags (some hosts don't enable it), but that's a matter of preference.
Edit: As per your edit, it seems like you don't have short tags enabled. Check your ini (http://php.net/manual/en/ini.core.php). But you really shouldn't be using short tags, because as clownbaby mentions, PHP 6 will deprecate them. Even if you don't care about future proofing your code, they're still troublesome (which is evident because your code isn't working). Switch to <?php echo $variable1; ?> and you'll be fine.
I think your code is fine, even most frameworks use it...
regarding the use of short tags, some servers do not allow it, so here is a workaround I use:
if ((bool) #ini_get('short_open_tag') === FALSE){
echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents("path/to/file2.php"))));
}else{
$newContent = include("path/to/file2.php");
echo $newContent;
}
$newContent = include('file2.php');
echo $newContent;
You shouldn't need to echo anything here. Just including the PHP file should execute any code inside it and spit out the interpolated template to the page. Whilst there is such a thing as returning a value from include, it's a rarely used feature you can generally ignore.
As ekhaled said, you may need to enable short tags or replace them with the always-supported <?php ... ?> processing-instruction-style syntax.
However, it's important to htmlspecialchars every text string when including it in HTML, or you've got a potential XSS security hole.
<?php
function h($text) {
echo(htmlspecialchars($text, ENT_QUOTES));
}
?>
...
<p>standard HTML with PHP... <strong><?php h($variable1) ?></strong></p>
<p><?php h($variable2) ?></p>

Categories