How to echo usable php code from database - php

I have a settings page in my Wordpress Admin Panel where I save some HTML code(with some PHP code in it) as a Wordpress Option, using update_option.
In phpmyadmin, the value is stored exactly like this:
<img src = \"<?php bloginfo(\'template_directory\'); ?>/images/flexslider/phone.png\">
It works perfect until I try to actually make the code work in a page. I'm printing it like this:
<?php echo urldecode(get_option('wp_slider_code')); ?>
This, unfortunately, prints the PHP code as it was HTML code. So the PHP code doesn't actually get executed; it's treated like a text, the url becoming:
<?php bloginfo('template_directory'); ?>/images/flexslider/phone.png
What can I do to make this PHP code get executed when I echo it on a page?

You have to use the eval() built-in function:
eval( $YourString );
(Edit:) If $YourString return a result, to cath the result you have to use:
$result = eval( $YourString );
Please note:
Caution
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
Read mor on PHP Documentation.

Related

Passing contents of a php variable using the URL

I would like to pass the value of a php variable using the URL, by using the variable name. Here is a sample of what I am trying to achieve, it doesn't work, bu also doesn't crash so I know that I am close....anyone...please:
Unit Learning
Personally I don't like to put little pieces of PHP code inside HTML. It can be done, but it is problematic. Better to write clean PHP code, like:
<?php
$url = 'student_what_learning_unit.php?student='.urlencode($student_user);
echo 'Unit Learning';
You do need the urlencode() for an URL, see:
http://php.net/manual/en/function.urlencode.php
Just add an echo like this:
Unit Learning

PHP code from a file does not execute

I am working on a BB code system for a content manager and I want to be able to use something like [code=php]<?php echo "Hello World!"; ?>[/code] in my textarea. Using GeSHi (A syntax highlighter) I have made the following function to parse the code:
function parsecode($codetype) {
$source = file_get_contents("file.php");
$language = $codetype;
$geshi = new GeSHi($source, $language);
echo '<code class="num">', implode(range(1,count(file("file.php"))), "<br />"), "</code>";
echo $geshi->parse_code();
}
This works perfectly fine!
Now this is where the BB code comes in. Using preg_replace I made a simple system that finds and replaces bits of code:
$find = array(
"/\[code\=(.+?)\](.+?)\[\/code\]/is"
);
$replace = array(
'<?php parsecode("$1"); ?>'
);
Yes, for now this means it only reads the language and parses the file "file.php" but eventually I will have this work different, but that's not important for now.
What happens, is that the BB code gets executed correctly, and the result is that it does in fact execute the code, but it does NOT execute the function parsecode() . I made a small adjustment to find out where the problem is, and made it save to a file and it turns out the file contained the following: <?php parsecode("php"); ?> . Which is exactly what it should contain. When I write this line of code in the file, it executes.
Anything submitted in the textarea gets stored in a file, which is then read using fopen() and then echo'd on a different page.
My question: Why does the function not execute & parse the code like it should?
Thanks ahead!
There is only one way to get PHP code to execute within PHP code (change code dynamically) and that is with eval().
http://www.php.net/manual/en/function.eval.php
This let's you dynamically make code and execute it
Please remember this quote though:
"If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP"
eval() is known for security vulnerabilities and being exploited. Highly not recommended.
However, as long as you're not using user generated code IN the eval you will be fine. You could put a return around it to get the result only in the database.
You could instead achieve the same effect by running this in the script but not replacing it before it's run in the entry but on the forum page itself...

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

Problems with my GET form in PHP

I made a GET form recently.But the problem is that it is highly vulnerable.You can inject your an script as below.
http://mysite.com/processget.phtml?search=Hacked
I'm able to inject any kind of script into my above URL.I'm actually echoing my GET data using an echo in my BODY,so whenever i enter a malicious script it is being executed in my BODY tag.So now how do i limit this http://mysite.com/processget.phtml?search= to just Number,letters and a few symbols which i want.
For ex.The user should only be able to enter
http://mysite.com/processget.phtml?search=A123123+*$
So can anyof you help me fix this bug.I'm kind of new to PHP,so please explain.
if (!empty($_GET['search'])) {
$search = htmlentities($_GET['search'],ENT_QUOTES,'UTF-8');
echo $search;
}
Now it's safe.
But if you want to limit to specific symbols, then you need to use regular expressions.
You can let a user enter whatever you like; the key is to escape the output. Then the string is displayed as desired, rather than included as HTML.
Use a php function like htmlentities
Strip the tags:
echo strip_tags($_GET['search']);
Actually, you may want htmlspecialchars instead, which escapes the tags instead of removing them so they display as intended:
echo htmlspecialchars($_GET['search']);

how to eval() a segment of a string

I have a string that has HTML & PHP in it, when I pull the string from the database, it is echo'd to screen, but the PHP code doesn't display. The string looks like this:
$string = 'Hello <?php echo 'World';?>';
echo $string;
Output
Hello
Source Code
Hello <?php echo 'World';?>
When I look in the source code, I can see the php line there. So what I need to do is eval() just the php segment that is in the string.
One thing to consider is that the PHP could be located anywhere in the string at any given time.
* Just to clarify, my PHP config is correct, this is a case of some PHP being dumped from the database and not rendering, because I am echo'ing a variable with the PHP code in it, it fails to run. *
Thanks again for any help I may receive.
$str = "Hello
<?php echo 'World';?>";
$matches = array();
preg_match('/<\?php (.+) \?>/x', $str, $matches);
eval($matches[1]);
This will work, but like others have and will suggest, this is a terrible idea. Your application architecture should never revolve around storing code in the database.
Most simply, if you have pages that always need to display strings, store those strings in the database, not code to produce them. Real world data is more complicated than this, but must always be properly modelled in the database.
Edit: Would need adapting with preg_replace_callback to remove the source/interpolate correctly.
You shouldn't eval the php code, just run it. It's need to be php interpreter installed, and apache+php properly configured. Then this .php file should output Hello World.
Answer to the edit:
Use preg_replace_callback to get the php part, eval it, replace the input to the output, then echo it.
But. If you should eval things come from database, i'm almost sure, it's a design error.
eval() should work fine, as long as the code is proper PHP and ends with a semicolon. How about you strip off the php tag first, then eval it.
The following example was tested and works:
<?php
$db_result = "<?php echo 'World';?>";
$stripped_code = str_replace('?>', '', str_replace('<?php', '', $db_result));
eval($stripped_code);
?>
Just make sure that whatever you retrieve from the db has been properly sanitized first, since you're essentially allowing anyone who can get content into the db, to execute code.

Categories