Storing and echoing php code in db - php

I have been trying to test this out. I put in the code below in the database.
<?php
$test = "Whats up";
print $test;
?>
And then on a page i do select and then i try to echo but it won't do it unless i rid the entry of the start and end tags. So if i wanted to execute this php by calling it from the db, how would i do it? Thanks.

Use eval to treat a string as runnable PHP code, for example:
<?php
$string = 'echo "hello";';
eval($string);
?>
As Pekka suggests, this is bad practice and you should probably rethink your solution. There's hardly ever motivated to store code in the database (the database is for data).

you could use serialize - unserialize function to save object or variable. and you can use eval function to run code

Hi This is exactly what I was looking for. We have CMS deployed accross multiple servers and in order to maintain the base functions (without the need to make a url based include of our main functions file) it was easier to store and call these functions from our group=wide single database. We use medium blob and store a serialized base_64 encoded text file there.
So to serialize the code we use this script without the php tags:
<form name="serialise_script" action="" method="post" >
<p>Put Script in here (without php tags???)</p>
<textarea cols="100" rows="25" name="serializeme" ></textarea>
<input type="submit" name="go" value="go" />
</form>
<?php if(isset($_POST['serializeme'])){
echo "<p>Your Code</p><textarea style='border:3px solid black;padding:0.5em;' cols='100' rows='25' >" . base64_encode(serialize($_POST['serializeme'])) . "</textarea>";
} ?>
Then copy the script and paste the output code into a text file.
Upload that to the medium blob table
Then to output again from the database and set to a session variable... I just did this:
eval(unserialize(base64_decode($_SESSION['functions'])));
But it was the eval bit I needed to make it work. By serializing and encoding means we shouldn't have any problems.
Now all I need to do is manage 1 base code for many sites across certain servers. AKA One bug fix would solve all issues across all deployments.
Thanks
Andi

Related

Do you need to change an HTML documents ending to work with PHP

I've started delving into PHP and I've seen that PHP files have a ".php" ending. I was wondering how this works, if you can put HTML code into one of these files, and how one would usually use PHP to collect information, if they'd create a separate web page for the form or if they can just convert an HTML page into a PHP page.
Apologies if my question is a bit hard to understand, it's a bit hard to put to words what I want to know.
Thanks!
You can put html in php files, for example:
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
This file file will display on a browser the classic Hello World page!
The way to use php depends of what you're trying to do. Sometimes it will be mixed with html, sometimes no.
Whenever a webserver sees a page ending in .php and has a PHP interpreter registered then it will pass the page to the interpreter.
The interpreter will pass any result back. If there's no PHP code in the page (e.g. there's only HTML) the interpreter will just pass the HTML back the way it gets it, but if you add a <?php ... ?> block the interpreter will evaluate the contents of that block and replace it with the result (e.g. if you do <?php echo "Hello world" ?> it will replace it with "Hello world").
That's just the short version.
PHP and HTML would be used in conjuction to create web pages. One can convert a HTML document to PHP in order to acheive more functionality as they are used for different things. PHP is a server side scripting language i.e. it facilitates communication between the user interface (the HTML & CSS) and the back-end server stuff (data). HTML is a markup language which on it's own does not communicate with the server, it is simply used to display static content on a page.
Together, they can be used to create dynamic web pages. One way to think of it is like this: HTML provides the content whereas PHP manipulates the content in order to provide functionality.
In other words, if we were building a house then HTML would be the bricks and mortar and PHP the plumbing, heating and electricity.
You can include HTML code in a PHP file however all PHP scripts must start with:
<?php
and end with
?>
Regarding your question on collecting information, PHP provides functions which enable form creation and binding to databases, take the following:
<?php
echo '<form method="post" action="">
Username: <input type="text" name="user_name" /><br/>
Password: <input type="password" name="user_pass"><br/>
Password again: <input type="password" name="user_pass_check"><br/>
E-mail: <input type="email" name="user_email">
<input type="submit" value="Register" />
</form>';
?>
This is an example of a simple form written in PHP to enable a user to log in, where HTML and PHP differ is that while you can create the same form in HTML, PHP gives you access to all sorts of nifty features such as performing data validation, security checks and database access.

Setting HTML Attribute via PHP File

I'm new to PHP and seem to have ran into a problem I can't seem to get around.
I have a form on a secure page that creates a PHP file to store a text value. I named this variable $text.
The Form HTML Code:
<form action="upload_title.php" method="post">
<label for="text">Title 1:</label>
<input type="text" name="text" id="text"><br>
<input type="submit" name="submit" value="Submit">
</form>
The upload_title.php then seems to store the text input as $text in filename.php:
<?php
$var_str = var_export($_POST['text'], true);
$var = "<?php\n\n\$text = $var_str;\n\n?>";
file_put_contents('filename.php', $var);
?>
This seems to be functional as the form will generate filename.php, below is an example if I typed Store into the form input and submitted on the webpage.
<?php
$text = 'Store';
?>
Now the issue I'm encountering is not being able to retrieve this stored as a attribute in separate html document, the index.html in my case.
This was my best approach to changing the title attribute of an image:
<a href="upload/1.jpg">
<img src="upload/thumb.jpg" title="<?php include 'filename.php'; echo htmlspecialchars($text); ?>" alt="" class="image0">
</a>
This does not work, but I can see my JQuery detects that this is trying to be populated but does not extract the data from filename.php on the `index.htm' page.
Thank those in advance for your advice and insight, it is sincerely appreciated.
Your issue is probably the fact that you are using an html file instead of a php file, in this case index.html.
Your server is likely not set up by default to process .html files as php so the php does not get executed.
Apart from that it is not a very good way to store your value as when the php does get executed, you introduce a security risk and you use a lot more storage than necessary. You'd better store the value in a database or text file.

New to PHP and having problems with cookies

Im new to PHP, and by that I mean BRAND NEW. Today is the first time I've really even sat down and gave it a shot for an extensive period of time.... And the thing I'm trying to achieve is kinda silly... ive been making a little flash game website for quite some time now... Just to get my hands dirty with web design and HTML and CSS i seem to be doing fine with. The website is just a simple flash game website that I made so I could play some of my favorite flash games at school when i had nothing better to do. and I had remembered on an old website i use to go to in order to do the same thing had a "panic button" underneath every game which when clicked just took you to google... I thought it was a funny and smart idea so i wanted to improve on it, i figured i would make a little PHP script that would enable the user to change the link to whatever you want. So lets say the teacher says you need to be on, oh i dont know... SCIENCE.COM! you just copy and paste the URL into the input bar on the front page and it automatically saves it in your cookies that thats the URL you want to go to when you click the "panic" button... I guess ill post the code ive been trying to get it to work with so you can all see.
Heres the PHP:
$expire=time()+0*0*12*0;
setcookie('panic', $panic, $expire);
?>
Here is the HTML:
<form method="post">
<input type="text" name="panic" size="80" id="panic"/>
<input type="submit" value="Submit"/>
</form>
<br />
<?php
echo ('click HERE to see if it worked!');
?>
I probably dont seem too smart from this... Ive literally been going at this for hours, for some reason i just cant seem to figure it out.... And i dont know if its possible, can i have the main PHP for the cookie in a separate file from the HTML or no?...
I must also point out that out of desperation i went around editing lots of names, so i must say if anything seems extremely out of place its more then likely because i was getting frustrated and messing the the code in odd ways.
I think your problem is due to misused quotes around your PHP in the following code. Also you are using curly braces for your $_COOKIE[] selector, and trying to select the cookie by its contents, rather than its name (you are using $panic instead of 'panic'):
<?php echo ('click HERE to
see if it worked!'); ?>
Single quotes mean that you don't need to escape double quotes, and also that any PHP variables you include inside the quotes won't automatically be replaced, so these will need to be concatenated outside of the quotes.
Try replacing it for this:
<?php
echo ('click HERE to see if it worked!');
?>
It's because your html is wrong. You can't set cookies that way. PHP is run server-side, not client-side. Try this.
HTML
<form method="post">
<input type="text" name="panic" size="80" id="panic"/>
<input type="submit" value="Submit"/>
</form>
<br />
<?php
echo ('click HERE to see if it worked!');
?>
PHP
<?php
error_reporting(E_ALL ^ E_NOTICE); // prevent it from erroring if something isn't defined
if($_GET["viewcookie"]){
echo $_COOKIE["panic"];
} else if($_POST){
$panic = $_POST["panic"]
setCookie('panic', $panic, time()+(60*12)); //expires in 12 minutes
echo $_COOKIE["panic"];
}
?>

Allow a user to edit a php code and submit the results securely

Is there a way to allow user to edit a php code securely, for example this is a basic php code to echo
Hello World! onto the page.
The idea is not to allow full coding changes just things like the array or they could edit a date in mktime things like that. I thought there maybe a way to echo form input fields into a php code which will then display the results.
How could i go about allowing a user to edit the code changing (Hello World!) to something else and then click submit to display there edit.
<?php
echo "Hello World!";
?>
or another example would be how can the user edit the words in the array
<?php
$words = array("the ", "quick ", "brown ", "fox ",
"jumped ", "over ", "the ", "lazy ", "dog ");
shuffle($words);
foreach ($words as $word) {
echo $word;
};
unset($word);
?>
I presume that i would have to create a form which gets the php code and somehow get it to display the edited results?
<form name="form" method ="get" action="a.php">
<input type="text" id="edit" name="edit" size="30" />
<input type="submit" value="Submit" >
</form>
For anyone that is viewing this and would like to know what you can create using a form and php see here Form that edits php script
What you are trying to accomplish is what variables are for.
Taking this example:
echo "Hello World!";
You could change that to
echo $_POST["data"];
and in your html
<form type='post'>
<input type='text' name='data'/>
<input type='submit'/>
</form>
See it in action
Eval should be avoided at all costs, there is a very narrow set of problems where using eval is a sane solution.
You want people to run arbitrary PHP code, but not all arbitrary PHP code. Tough thing to get right.
First off do not just eval() form data. Only bad* can come of this.
<form method="POST">
<textarea name="php"></textarea>
<button type="submit">Run</button>
</form>
<pre>
<?= eval($_POST['php']) ?>
</pre>
One option that comes to mind is to use https://github.com/nikic/PHP-Parser.
Basically, the parser does nothing more than turn some PHP code into an abstract syntax tree. ("nothing more" is kind of sarcastic here as PHP has a ... uhm, let's just say "not nice" ... grammar, which makes parsing PHP very hard.)
You can then walk the AST and remove suspect expressions, reconstitute the tree to code, and then call eval() on it.
Outside of that, configuring a sandbox environment would be critical here, as nothing is foolproof. That way, when someone inevitably bricks the box, you can recover it.
php.ini configuration changes can make for a "safer" environment to execute arbitrary code by imposing restrictions. disable_functions and disable_classes can help limit the possible abuse. Setting a low memory_limit will prevent help reduce excessive resource slurping.
* Unless this is a social experiment to see how long it takes for someone to turn your machine into pudding
in THEORY you can do something like this, but PLEASE PLEASE PLEASE don't do it because it is extremely UNSECURE
<?php
if (isset($_REQUEST['do_eval'])){
eval($_REQUEST['to_eval']);
}
?>
<form action="eval.php">
<textarea name="to_eval" rows="20" cols="80"><?php if (isset($_REQUEST['eval'])) print($_REQUEST['eval']); ?></textarea>
<br />
<input type="submit" name="do_eval" value="Submit" />
</form>
if I get you right, then eval function is what you need (http://php.net/manual/en/function.eval.php)
Evaluates the given code as PHP.
Although it is very dangerous as a user can execute a destructive code or output some private data.
<?
if(isset($_POST['submit'])
{
eval($_POST['code']);
}
else
{
?>
<form method="POST">
<textarea name="code"></textarea>
<input type="submit" value="Submit"></form>
</form>
<?
}
This sounds extremely dangerous to me; since PHP code runs on the server, you are basically letting anyone and everyone tell your server what code to run, and telling it to run harmful code would be very easy. Unfortunately, I can't think of a trivial way to sanitize this type of input.
Having said that... you can have a form that submits the user's code to a page that can write that code into a .php file on your server, then redirects to the newly created .php file. But, again, I would not advise you to do this sort of thing.
I think I understand what you're trying to accomplish. The actual task I believe will require a large amount of javascript in association with your PHP.
So, let's run it down theoretically.
Let's say this is your start code:
$array = array('one', 'two', 'three');
var_dump($array);
Ok - so now you want to define that the user can modify the array. Your HTML now looks something like that code above - all escaped of course.
However, you put form element around the escaped content, and put each array element as an input field.
So, you'll end up with something like this: (Note this is HTML not PHP)
<form action="self.php">
<div>$array = array(</div>
<span>'<input name="arrayValue[]">, +</span>
<div>);<br>var_dump($array);</div>
<input type="submit" value="Process this code">
</form>
Now, you'll need to write some javascript that watches for the class 'addAnother' to be clicked. If so, it goes up to its parent element and clones it (see - that's the span) and adds it after the parent. This way you'll have another whole line that is that span - with another input.
If you style the inputs to look nice, you can make it look like the user is typing inline.
Once the submit is pressed, the values are sent to the PHP. Then, the PHP will create a new array from all of $_POST['arrayValue'];
Your actual code will do this:
$array = $_POST['arrayValue'];
var_dump($array);
And then, you'll rerender the HTML again.
I know this is all 'theory' - there's a bit more code to actually be written.
I honestly would re-think if you really want to take on this task - this is a LOT of work to do it in an interactive, secure way. Perhaps there are other ways to accomplish your core task. Best of luck!

Trouble storing PHP variables

to start I consider myself in between beginner and intermediate when it comes to PHP. On my website, I have a textarea that the user can input web code in and when a button is pressed, it sends the code to the page and displays the output. Here is the link to the page: http://opensourcewebsite.host22.com/editpage.php. Another problem that I am running into is that I want whatever the user enters to stay on the page.
Here is what the code looks like so far:
<?php $source_code = $_POST['source-code'}; ?>
...
<editable_area>
<?php echo $source_code ?>
</editable_area>
...
<form action="" method="post">
input class="result" type="submit" name="submit" value="View Result">
<textarea id="source" class="edit_are" name="source-code"></textarea>
Currently, when a user inputs code containing an id/class/name/etc. that has quotes in it, it is like when you do:
echo "<div id="Name">"
It will add the \" and thus messing up the code. I need to find a way to store the code so that it will display correctly. If you try the web page, you will see my issue first hand.
When the code is submitted, the textarea grabs the source code of the web page through javascript. I have discovered that if you leave out the "" in the code, it works as expected. The problem is that when it grabs the source code, there is quotes in it so the code will display them in the textare. This means every time you make a change, you need to take out all of the quotes.
Thanks to webbiedave, I fixed the quote problem by using:
<?php echo stripslashes($source_code) ?>
Now I just need to figure out how to permanently store changes.
<?php echo htmlentities(stripslashes($source_code)) ?>
Check if you have magic quotes turned on and make sure you turn them off. Also, you'll want to use htmlspecialchars to escape the special characters. Otherwise, they can just close your textarea and wreak other havoc.
echo htmlspecialchars($source_code);
Can you use single quotes instead:
'<div id="Name">';

Categories