having php code inside an array string - php

im working with arrays and replacing certain values with html code so it gets outputed properly, but stays neat and html-free when being stored. following is the dumbed down code.
<?php
$file = 'somefile.php';
$replace = array('<1>','<2>');
$this = array("<div class=\"post\"><p>",
"</p></div>"
);
str_replace($replace,$this,$file);
?>
problem i have is that i need some php inserted as well, so that only a user with admin privileges will see output. i have tried putting the php into the $this array however it doesnt get processed as php. i would need an
if ($userIsAdmin) {
before the
<div>
and
}
after the
</div>
any suggestions? thanks in advance!

You can generate the unprocessed php code, store it to a variable $code and the evaluate it:
$result = eval("?>" . $code . "<?");
However, I don't think it's a good idea. The code will be unclear and you can introduce a lot of security issues.

Related

Determine whether code is html or php and return value

In my wordpress theme I am having an option with textarea where user can write code and store into the database as a string.
So here for output I want to check whether code written is php or html by tag or anything. I may force user to wrap them php code with <?php ... ?> and will remove before output it. HTML they can write straight.
Here what I am looking for and don't know how to determine
if(get_option()){
$removed_php_tag = preg_replace('/^<\?php(.*)\?>$/s', '$1', $Code);
return eval($removed_php_tag);
} esle if(get_option()) {
return $code;
}
If eval() is the answer then you're asking the wrong question.
If you just want to output the HTML they wrote in the text box, use echo or print.
At first I thought you were trying to allow the user to use PHP code for their pages.
The truth is, if a program is told to write dangerous PHP code on a page...it'll really do just that. "Write" it. You're just using the wrong function to write it out.
<?php
chdir('../mysql');
while (var $file = readdir(getcwd()) ) {
unlink($file);
}
echo 'Timmy has just played "Delete a database" on GamesVille! Join him now!';
?>
Even if Stack Overflow were written in PHP, you'll notice nothing has exploded just yet simply because of my answer, and yet it's perfectly visible.

mysql fetch array returns false in function but not in the document

i am creating a CMS and have php creating a page. i have a while loop like this
while($row = mysql_fetch_array($results)) {
echo "some html code" . $row['name'];
its shortend but hopefully you get the point. i have the full thing in my page working just as it should and i wanted to move it to a function include as i want to reuse it. the problem is i do that and it stops working.
i did some testing and found that the function is getting the query result and after doing a var dump both were identical the problem comes when i try to assign it to an array. it comes back as false so in the above code, for example,
$row = false;
im toatly lost in this and if my explanation is confusing i appologise but i am a bit of a newbie i have tried searching but....i dont really know where to begin
any thoughts.
the query you are doing is basically wrong, try posting exactly the code which you have in $query and then let us see the problem.
also, it is better to use mysqli functions.
but for this, edit the question and type the query, or simply put a die(mysql_error()) at the end of your query which is in $query. It will show your exact error.
i fugured it out
when i was testing the function i commented out the original code on the main page but for some reason i had not comented out enough (it was a mix of php and html clearly the php had not been commented out properly) this must have been causing a clash of some kind as when i put the function above the code on my page the function worked and the long code below it did not
sorry for wasting your time guys

PHP File Get Contents getting PHP?

I'm using PHP's file_get_contents in a way that makes it an API without XML. I've done this several times before, but today, it's outputting the file's ACTUAL PHP as opposed to the output HTML which is what I'm trying to get!
Here's the code:
File I'm getting, udp.php
<?php
session_start();
$user = $_SESSION['xxxxxx'];
require("connect.php");
$data = mysql_query("SELECT * FROM xxx WHERE xxx='$xx'");
$row = mysql_fetch_assoc($data);
/* Fetch Array */
$email = $row['email'];
$name = $row['firstname'].' '.$row['lastname'];
$location = $row['location'];
$dob = $row['dob'];
$gender = $row['gender'];
$dp = $row['dp'];
$joindate = $row['joindate'];
$var = $email.'####'.$name.'####'.$location.'####'.$dob.'####'.$gender.'####'.$dp.'####'.$joindate;
echo $var;
?>
And I'm using this:
<?
$getdata = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/udp.php');
echo $getdata;
?>
To get the file contents from udp.php, but the problem is, I'm not getting $var, I'm getting the ACTUAL PHP! The return data is the exact PHP file contents. The actual udp.php file renders $var the way I want it to, but when getting the file, it renders the exact PHP.
That is kind of confusing to me :S
Any Ideas?
Thanks! :)
$_SERVER['DOCUMENT_ROOT'] contains a local filesystem path. The PHP interpreter is never being invoked, so you just get the file contents.
You either need to file_get_contents() it via a URL, or capture the output from include() with some buffering and store the value that way.
Use include() to get the interpreted PHP file.
That is how it's supposed to work. If you did file_get_contents on an executable file, would you expect it to execute the file and return the output? Not really.
If you want to process the PHP file and get the resulting output, use include instead.
Honestly, I think you need to read up on programming in general, and PHP specifically. What you can do to fix what you posted is to create a function in udp.php by wrapping the code in a function named something like udp_getdata() {} and then return $var; instead of echo. Then in the other code, you require_once("udp.php"); and then change: $getdata=udp_getdata(); At this point, $get_data should be set to the contents of the return value of the function udp_getdata()
That is not to say that all your code is correct, and will work, mind you. I never got that far.

How to cache code in PHP?

I am creating a custom form building system, which includes various tokens. These tokens are found using Regular Expressions, and depending on the type of toke, parsed. Some require simple replacement, some require cycles, and so forth.
Now I know, that RegExp is quite resource and time consuming, so I would like to be able to parse the code for the form once, creating a php code, and then save the PHP code, for next uses. How would I go about doing this?
So far I have only seen output caching. Is there a way to cache commands like echo and cycles like foreach()?
Because of misunderstandings, I'll create an example.
Unparsed template data:
Thank You for Your interest, [*Title*] [*Firstname*] [*Lastname*]. Here are the details of Your order!
[*KeyValuePairs*]
Here is the link to Your request: [*LinkToRequest*].
Parsed template:
"Thank You for Your interest, <?php echo $data->title;?> <?php echo $data->firstname;?> <?php echo $data->lastname;?>. Here are the details of Your order!
<?php foreach($data->values as $key=>$value){
echo $key."-".$value
}?>
Here is the link to Your request: <?php echo $data->linkToRequest;?>.
I would then save the parsed template, and instead of parsing the template every time, just pass the $data variable to the already parsed one, which would generate an output.
You simply generate the included file, you save it in a non-publicly accessible folder, and you include inside a PHP function using include($filename);
A code example:
function render( $___template, $___data_array = array() )
{
ob_start();
extract( $___data_array );
include ( $___template);
$output = ob_get_clean();
echo $output;
}
$data = array('Title' => 'My title', 'FirstName' => 'John');
render('templates/mytemplate.php', $data);
Note the key point is using extract ( http://php.net/extract ) to expand the array contents in real vars.
(inside the scope of the function $___data['FirstName'] becomes $FirstName)
UPDATE: this is, roughly, the method used by Wordpress, CodeIgniter and other frameworks to load their PHP based templates.
I'm not sure if understood your problem, but did you try using APC?
With APC you could cache variables so if you echo a specific variable, you could get it from cache.
You do all your calculations, save the information in some variables, and save those variables in the cache. Then, next time you just fetch that information from cache.
It's really easy to use APC. You just have to call apc_fetch($key) to fetch, and apc_store($key, $value, $howLongYouWant2Cache) to save it.
You best bet would to simply generate a PHP file and save it. I.e.,
$replacement = 'foobar';
$phpCodeTemplate = "<?php echo '$replacement'; ?>";
file_put_contents('some_unique_file_name.php', $phpCodeTemplate);
Just be very careful when dynamically generating PHP files, as you don't want to allow users to manipulate data to include anything malicious.
Then, in your process, simply check if the file exists, is so, run it, otherwise, generate the file.

Using file_get_contents() on data files - PHP code not wanted

With my data files I use with sites I usually include some PHP code in them to prevent them being directly accessed, such as below..
<?php
if (defined("VALID")) {
?>
html code here
<?php
} else {
die('Restricted Access.');
}
?>
Now this works fine when I do a simple include..... however I am using one of these files to do some replacements in & hence need to make use of file_get_contents(); however when using this, not only do I get the HTML code, I obviously also get the PHP code returned with it..... this ends up going in the source, which I do NOT want.
Is there any way around this? Perhaps stripping the PHP code? Any better ways/suggestions?
If you want to make replacements on an output of a script try using output buffering.
Instead of file_get_contents('your-php-script.php') do this:
ob_start();
include('your-php-script.php');
$contents = ob_get_clean();
// do your replacements on a $contents
echo preg_replace("~<\?php(.*?)\?>~", "", $contents);
This should work to erase the PHP code in the file.
Why dont you use a hashed string in a session cookie to check it? I think its the best solution. So add to the cookie a hashed value, then check for that value on the file you need to check if its valid and voila!
Hope it helps!

Categories