PHP - Executing PHP from a string - php

This one is a bit of a weird one. Ive created a function designed to select a template and either include it or parse the %0, %1,%3 etc. variables. This is the current function:
if(!fopen($tf,"r")){
$this->template("error",array("404"));
}
$th = fopen($tf,"r");
$t = fread($th, filesize($tf) );
$i=0;
for($i;$i<count($params);$i++){
$i2 = '%' . $i;
$t = str_replace($i2,$params[$i],$t);
}
echo $t . "\n";
fclose($th);
Where $th is the relative directory to my template file. My issue is, I need to execute the PHP inside of these files whilst at the same tme being able to replace the string variables %0 %1 etc.
How could I go about attempting this?

Like I said in my comment I think a template engine like Smarty would probably serve you better but here's how I'd do it with output buffering rather than eval()
Something like this
ob_start();
include "your_template_file.php";
$contents = ob_get_contents(); // will contain the output of the PHP in the file
ob_end_clean();
// process your str_replace() variables out of $contents

Related

php scraper scripts need to be changed

this script harvests links out of a seed url and only prints them in command shell (or browser) rather than saving elsewhere. I want the script to store any outputs in .txt file within the folder where the script resides. I need suggestions what could be the efficient way to do that. Please give me hints.
<?php
# Initialization
include("LIB_http.php"); // http library
include("LIB_parse.php"); // parse library
include("LIB_resolve_addresses.php"); // address resolution library
include("LIB_exclusion_list.php"); // list of excluded keywords
include("LIB_simple_spider.php"); // spider routines used by this app.
set_time_limit(3600); // Don't let PHP timeout
$SEED_URL = "http://www.schrenk.com"; // First URL spider downloads
$MAX_PENETRATION = 1; // Set spider penetration depth
$FETCH_DELAY = 1; // Wait one second between page fetches
$ALLOW_OFFISTE = false; // Don't allow spider to roam from the SEED_URL's domain
$spider_array = array();
# Get links from $SEED_URL
echo "Harvesting Seed URL \n";
$temp_link_array = harvest_links($SEED_URL);
$spider_array = archive_links($spider_array, 0, $temp_link_array);
# Spider links in remaining penetration levels
for($penetration_level=1; $penetration_level<=$MAX_PENETRATION; $penetration_level++)
{
$previous_level = $penetration_level - 1;
for($xx=0; $xx<count($spider_array[$previous_level]); $xx++)
{
unset($temp_link_array);
$temp_link_array = harvest_links($spider_array[$previous_level][$xx]);
echo "Level=$penetration_level, xx=$xx of ".count($spider_array[$previous_level])." <br>\n";
$spider_array = archive_links($spider_array, $penetration_level, $temp_link_array);
}
}
?>
Use file_put_contents PHP function with enable append file flag.
$file = 'file_name.txt';
file_put_contents($file, $text_to_write_to_file, FILE_APPEND);
Ref: http://www.php.net/manual/en/function.file-put-contents.php
I would recommend first creating a variable to store the output in the script. So at the top (under the $spider_array=array() ) add:
$output = "";
The change all the lines with echo to be $output .=
This will store all the content sent to the screen or the browser into the $output variable.
Now at the bottom of the script, after everything has been scraped and the spider is finished, save the output to a file:
$filename = date('Y_m_d_H_i_s') . '.txt';
$filepath = dirname(__FILE__);
file_put_contents($filepath . '/' . $filename, $output);
This should save the output in a file within the same folder as the script with a date/time file name. (This code was written using examples from php.net, exact implementation may need a bit of debugging, but this should get you close enough.

Including a php file with includes into a smarty template

I want to include my header into a script that uses smarty templates. From searching this site, I am partially there, but not quite:
{include file='/home/username/public_html/header.php'}
This successfully includes the image in the header, but neither of two includes the header contains. One of the includes is a php file, and the other is html (my bootstrap nav bar). I seems from my searches that I need to make a plugin, which according to one post is "easy", but I can't find an example of how to accomplish this?
based on codefreaks inststructions, here's what I did. I'm sure the instructions are correct, I'm just not interpreting them correctly, as this isn't displaying anything.
Here are the three files, with their paths in relation to the public_html directory, and what I added to them. Everything is exactly as I put it: no words here are placeholders.
file 1
sitewide/myheader.php
<?
ob_start();
--- I didn't change the original content here --
$output = ob_get_contents();
ob_end_clean(); ?>
File 2
newscript/includes/page_header.php
$smarty = new Smarty();
require "/home/username/public_html/sitewide/myheader.php";
$smarty->assign('myheader', $output);
$smarty->display('../themes/default/template/header.tpl');
File 3
newscript/themes/default/template/header.tpl
{$myheader}
I dont think you can include your php file in smarty.
As samrty is a template engine,
PHP pages executes first, then it sends the data to your smarty page.
Solution : Pass all data needed from php page to smarty, and include html page, with smarty variables.
After getting feedback from you and testing myself, I figured out you might not have set up smarty properly. Follow instructions at http://www.smarty.net/quick_install to install it properly. My final directory structure after setting up properly looks like:
Once you have it set it up properly this is code I used in files:
index.php
<?php
echo "hello";
require_once "libs/Smarty.class.php";
$smarty = new Smarty();
$smarty->setTemplateDir('smarty/templates');
$smarty->setCompileDir('smarty/templates_c');
$smarty->setCacheDir('smarty/cache');
$smarty->setConfigDir('smarty/configs');
require "header.php";
$smarty->assign('header', $output);
$smarty->testInstall();
$smarty->display('smarty.tpl');
echo "hello";
?>
header.php:
<?php
ob_start();
?>
hello honey bunny
<?php
$output = ob_get_contents();
ob_end_clean();
?>
Put smarty.tpl in templates folder!
{$header}hellos
I am trying to do a very similar thing except all I want is some global PHP constants that I have defined in a stand alone constants.php file using define.
I want those same said constants in my smarty templates so I've been trying to include constants.php in the smarty template but this is better a better way to do this:
In constants.php
$_CONSTANT['TBL'] = TRUE;
$_CONSTANT['FLD'] = FALSE;
$_CONSTANT['DB_READ_SUCCESS'] = 1;
$_CONSTANT['DB_WRITE_SUCCESS'] = 1;
$_CONSTANT['DB_WRITE_ERROR_UNKNOWN'] = -100;
//*** Copy the $_CONSTANT array to PHP define() to make global PHP constants
foreach($_CONSTANT as $key => $value) {
define($key, $value);
}
Then in my smarty set up function I do this:
foreach ($_CONSTANT as $key => $value) {
Smarty->assign($key, $value);
}
And really I think variable (or constant) values is all you really want in your Smarty templates to keep your view layer separate from your model and controller layers.
Post Script:
In fact you can use this technique to pass your PHP constants, using Smarty, to JavaScript allowing you to declare you constants in one place for three different environments: PHP, Smarty, and JavaScript.
Here's how:
Call the following from your smarty set up function:
public function AssignJSConstants($values) {
$js = '';
foreach ($values as $key => $value) {
if ($key != 'CR') {
if (is_string($value)) {
$js = $js.$key.' = "'.$value.'";';
} else {
$js = $js.$key.' = '.$value.';';
}
$js = $js.CR.' ';
}
}
$this->Smarty->assign('JavaScriptConstants', $js);
}
And then declare the following in your smarty template:
<script>
//php constants that exported to JavaScript
{$JavaScriptConstants}
</script>
Which will give you this in your HTML:
<script>
//php constants that exported to JavaScript
TBL = 1;
FLD = 0;
DB_READ_SUCCESS = 1;
DB_READ_ERROR_UNKNOWN = -10;
DB_WRITE_SUCCESS = 1;
DB_WRITE_ERROR_UNKNOWN = -100;
</script>

Parse array from php file

The .php file contains code like:
<?php
return array(
// commments...
'some_item' => 'abc',
// commments...
'some_other_item' => array(1, 2, 3),
...
);
What's the best way to "parse" this file somehow from within my PHP application, and be able to update data in it, without breaking formatting, code etc. ?
$content = require($file); will get the file's content (beware of relative paths and requirevs include semantics).
file_put_contents($file, '<?php return ' . var_export($content, true) . ';'); will write the content back to the file, but formatting will change. If you really need to keep the formatting, you could look into PHP Beautifier. It's not a perfect solution though.
simply include() the file:
$my_array = include 'myarray.php';
See example #4 at http://php.net/manual/en/function.include.php and http://php.net/manual/en/function.return.php
The best way is to include it; yes, include returns a value!
$data = include 'someData.php';
Assuming that your array has only two items
<?php
$myArray=include 'data.php';
$myArray[count($myArray)]='Item-3';
echo $myArray[2]; // Item-3
?>
Are you trying to load filenames which are contained in an array? If so:
$array_of_files = array('header.php','database.php','../inc/other_stuff.php');
foreach($array_of_files as $file)
{
include $file;
}

run php script and return data as a string

My php script needs to load contents from another file and then replace certain commands. Using the following code works on static pages:
$pageName = 'pages/' . $_REQUEST['url'] . '.php';
$pageContents = file_get_contents($pageName);
$IDCODE = $_SESSION['IDCODE'];
$sql = "SELECT * FROM members WHERE IDCODE = '$IDCODE'";
$qry = mysql_query($sql);
$OK = $qry ? true : false;
$arr = mysql_fetch_array($qry);
foreach ($arr AS $key => $val) {
$pageContents = str_replace('{' . $key . '}', $val, $pageContents);
}
however, what if the file to be processed was dynamic? IE it populates some text from the mysql database.
Will file_get_contents run the file or just read whats in it as a string?
If you run the link to the file via a webserver, it will be processed. If you link it directly, you will get the exact contents of the file.
Rather messy code.
$pageName = 'pages/' . $_REQUEST['url'] . '.php';
$pageContents = file_get_contents($pageName);
local file inclusion vulnerability here.
$OK = $qry ? true : false;
Why? Anywere you use the value of $OK you could equally use $qry. And you never use $OK again in the code shown.
There's no error checking, no comments in the code.
what if the file to be processed was dynamic?
WTF? Do you mean you want to re-process the output as PHP? Then you could 'eval($pageContents);' but beware of code injection vulnerabilities.
Or you want to apply your script to the output of a PHP scrpt? Then just pass the URL as the argument to file_get_contents() e.g.
file_get_contents('http://localhost/path/'
. basename($_REQUEST['url'] . '.php');
But really the invocation should be controlled better than this. Both are messy solutions - a templating solution should be just that. Go have a long hard look at (e.g.) smarty

Caching HTML output with PHP

I would like to create a cache for my php pages on my site. I did find too many solutions but what I want is a script which can generate an HTML page from my database ex:
I have a page for categories which grabs all the categories from the DB, so the script should be able to generate an HTML page of the sort: my-categories.html. then if I choose a category I should get a my-x-category.html page and so on and so forth for other categories and sub categories.
I can see that some web sites have got URLs like: wwww.the-web-site.com/the-page-ex.html
even though they are dynamic.
thanks a lot for help
check ob_start() function
ob_start();
echo 'some_output';
$content = ob_get_contents();
ob_end_clean();
echo 'Content generated :'.$content;
You can get URLs like that using URL rewriting. Eg: for apache, see mod_rewrite
http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html
You don't actually need to be creating the files. You could create the files, but its more complicated as you need to decide when to update them if the data changes.
In my opinion this is the best solution. I use this for cache JSON file for my Android App. It can be simply use in other PHP files.
It's optimize file size from ~1mb to ~163kb (gzip).
Create cache folder in your directory
Then Create cache_start.php file and paste this code
<?php
header("HTTP/1.1 200 OK");
//header("Content-Type: application/json");
header("Content-Encoding: gzip");
$cache_filename = basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'];
$cache_filename = "./cache/".md5($cache_filename);
$cache_limit_in_mins = 60 * 60; // It's one hour
if (file_exists($cache_filename))
{
$secs_in_min = 60;
$diff_in_secs = (time() - ($secs_in_min * $cache_limit_in_mins)) - filemtime($cache_filename);
if ( $diff_in_secs < 0 )
{
print file_get_contents($cache_filename);
exit();
}
}
ob_start("ob_gzhandler");
?>
Create cache_end.php and paste this code
<?php
$content = ob_get_contents();
ob_end_clean();
$file = fopen ( $cache_filename, 'w' );
fwrite ( $file, $content );
fclose ( $file );
echo gzencode($content);
?>
Then create for example index.php (file which you want to cache)
<?php
include "cache_start.php";
echo "Hello Compress Cache World!";
include "cache_end.php";
?>
Manual caching (creating the HTML and saving it to a file) may not be the most efficient way, but if you want to go down that path I recommend the following (ripped from a simple test app I wrote to do this):
$cache_filename = basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'];
$cache_limit_in_mins = 60 * 32; // this forms 32hrs
// check if we have a cached file already
if ( file_exists($cache_filename) )
{
$secs_in_min = 60;
$diff_in_secs = (time() - ($secs_in_min * $cache_limit_in_mins)) - filemtime($cache_filename);
// check if the cached file is older than our limit
if ( $diff_in_secs < 0 )
{
// it isn't, so display it to the user and stop
print file_get_contents($cache_filename);
exit();
}
}
// create an array to hold your HTML output, this is where you generate your HTML
$output = array();
$output[] = '<table>';
$output[] = '<tr>';
// etc
// Save the output as manual cache
$file = fopen ( $cache_filename, 'w' );
fwrite ( $file, implode($output,'') );
fclose ( $file );
print implode($output,'');
I use APC for all my PHP caching (on an Apache server)
If you're not opposed to frameworks, try using the Zend Frameworks's Zend_Cache. It's pretty flexible, and (unlike some of the framework modules) easy to implement.
Can use Cache_lite from PEAR:
Details here
http://mahtonu.wordpress.com/2009/09/25/cache-php-output-for-high-traffic-websites-pear-cache_lite/
I was thinking from the point of load on the database, and charges for data bandwidth and speed of loading. I have some pages which are unlikely to change in years, (I know it is easy to use a CMS system based on a database ). Unlike in US, here the cost of bandwidth can be high. Anybody has any views on that, whether to create htmal pages or dynamic (php, asp.net)
Links to the pages would be stored on a database anyway.

Categories