To be like Codeigniter and get that view partial with vanilla PHP? - php

Just wondering if anyone can point me in the right track to imitating the following Codeigniter method with pure PHP:
$string = $this->load->view('myfile', $data, true); // where $data is an array of info to "fill in" the html on the page
I've started with trying to use fopen, but i can't quite seem to figure out the part of sending data to the file before making it the string variable that i want to eventually send to the "master template".
At current, I'm stumped. I've been looking over their _ci_load method which feeds the above code, but it dives into more CI libs and the whole point of this is to make the "easiest pur php" way. If anyone has any advice, tips, tutorial links, anything I can't already find with Google

When I need something to quickly return part of a template, I use this.
function view($file,$data) {
extract($data);
ob_start();
if (is_file($file)) {
include($file);
}
$return = ob_get_clean();
return $return;
}
You should make sure to secure the contents of $file. Otherwise, anyone can load any file they want and inject it with the data they want. I normally use this only when I'm defining $file by hand, nothing dynamic.

I would recommend you look into using the ob_start(), ob_get_contents(), and ob_end_clean() functions.

Related

Looking for a PHP Template Engine similar to the phpBB3.0 Template System

There are so many template engines out there. However, I am looking for something simple, fast and easy like the the phpBB3.0 Template System. Something simple like
$template->set_filenames(array(
'body' => 'your_template_file.html'
));
With similar templates using {L_SOME_VARIABLE} like output. I do not want to install phpbb because of the overhead. I need it to be simple but smart enough to where if I want to output json it will recognize when the last attribute is done not to output the leading ';'
I will be using it to output data in json, xml, txt, AOML and others pointing to its respective template, depending on the choice the user makes for desired data input.
I have looked at things like Smarty, but it seems a little much for me and there doesn't seem to be any easy json solutions.
If anyone has any simple solutions please let me know. I am unable to find this exact question on here.
PHP itself is a template engine (currently you can do much much more using it, but basically it is template engine) - IMHO creating and using template engines inside template engine is a little bit silly ;)
What I would suggest is just something like this:
function renderTemplate($_file_, $_args_ = null, $_return_ = false) {
if (is_array($_args_)) {
extract($_args_, EXTR_SKIP);
}
if ($_return_) {
ob_start();
ob_implicit_flush(false);
require('/mypath/to/templates/'.$_file_.'.php');
return ob_get_clean();
} else {
require('/mypath/to/templates/'.$_file_.'.php');
}
}

How can I save a template and download it from the database using smarty template engine

I'm having a hard time saving my template to a database and download the contents to view using Smarty.
I followed the tutorial on Smarty.net on how to make a custom retrieve type.
My original method was save the tpl markup to the db then download it and pass it as a variable to a smarty assigned variable and in my text.pl do something like {$source}
but this parses it as a string and smarty won't compile it.
the tutorial on smarty website didn't help and just leaves me with more questions...
this is what i tried based on the tutorial
function db_get_template($tpl_name, &$tpl_source, &$s)
{
$tpl_name = "index.tpl";
$tpl_source = nl2br($defaults->get_default_theme('theme_data'));
return true;
}
function db_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty)
{
$tpl_timestamp = (int)time();
//$tpl_timestamp = (int)$defaults->get_default_theme('modified_on');
return true;
}
function db_get_secure($tpl_name, &$smarty)
{
// assume all templates are secure
return true;
}
function db_get_trusted($tpl_name, &$smarty)
{
// not used for templates
}
$s->registerResource("db", array(
"db_get_template",
"db_get_secure",
"db_get_trusted"
));
$s->display("db:index.tpl");
i'm not sure where db:index.tpl is being pulled from. I don't know where the markup is suppose to be loaded into...
I feel dirty even suggesting this, but:
Here's a more relevant manual page than the page you were referencing.
In particular, pay attention to the string: prefix to the "filename" passed in the display method call. You can simply pull the template data out of your database (a horrible idea, IMNSHO) and pass it to Smarty that way. No need to build your own custom resource thing unless you really want to do it that way.
I, for one, would urge you to keep it as stupid, ugly and obvious as possible, as to remind yourself about how much of a horrible, no-good idea this is. I'd like to remind you that Smarty compiles to PHP, and placing Smarty code in the database is an effective gateway to arbitrary code execution, a severe security vulnerability.

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!

PHP macro / inline functions (to avoid variables to go out of scope)

I have the following dilemma. I have a complex CMS, and this CMS is to be themed by a graphic designer. The templates are plain HTML, with several nested inclusions. I'd like to make it easier for the designer to locate the file to be modified, by looking at the HTML of the page.
What I thought in the first place was to build something stupid like this:
function customInclude($what) {
print("<!-- Including $what -->");
include($what);
print("<!-- End of $what -->");
}
but, guess what? Variables obviously come out of scope in the included file :-) I can't declare them as global or as parameters, as I don't know how they are called and how many are there.
Is there any possibility to implement some kind of "macro expansion" in PHP? An alternative way to call it: I'd like to modify each call of the modify function, in an aspect-oriented style.
I have thought about eval(), is it the only way? Will it have a big impact on performance?
I know this is an old question, but I stumbled upon it and it reminds me of something I used to do it too.
how about if you create the function using a very weird variable?
<?php
function customInclude($___what___) {
echo '<!-- Including '.$___what___.' -->';
include($what);
echo '<!-- End of '.$___what___.' -->';
}
?>
I usually suggest to add a possible variable to display those tags only when necessary, you do not want other people to know...
<?php
function __printIncludeInfo($info, $dump = false){
//print only if the URL contains the parameter ?pii
//You can modify it to print only if coming from a certain IP
if(isset($_GET['pii'])){
if($dump){
var_dump($info);
} else {
echo $info;
}
}
}
function customInclude($___what___) {
__printIncludeInfo('<!-- Including '.$___what___.' -->');
include($what);
__printIncludeInfo('<!-- End of '.$___what___.' -->');
}
?>
in this way you can use the function to print any other information that you need
Not sure if I entirely understand the question, but if you're just trying to make life easier for the designer by showing them the underlying filename of the included file, then you can probably just use this within the template files:
echo '<!-- Start of '.__FILE__.' -->';
....content...
echo '<!-- End of '.__FILE__.' -->';
__FILE__ is just one of several Magic Constants.
Also there's the get_included_files() function that returns an array of all the included files, which might be of use (you could output a list of all the included files with 'tpl' in their name for example).
This is my 100% harcoded solution to custom include problem. It's about using a global var to point the next include filename and then include my custom proxy-include-file (wich replace your custom proxy-include-function)
1 - Add this code to a global include (wherever your customInclude function is defined)
$GLOBALS['next_include'] = "";
$GLOBALS['next_include_is_once'] = false;
function next_include($include_file) {
$GLOBALS['next_include_is_once'] = false;
$GLOBALS['next_include'] = $include_file;
}
function next_include_once($include_file) {
$GLOBALS['next_include_is_once'] = true;
$GLOBALS['next_include'] = $include_file;
}
2 - Create some include proxy-include-file, by example "debug_include.php"
<?php
if(empty($GLOBALS['next_include'])) die("Includes Problem");
// Pre-include code
// ....
if($GLOBALS['next_include_is_once']) {
include_once($GLOBALS['next_include']);
} else {
include($GLOBALS['next_include']);
}
// Post-include code
// ....
$GLOBALS['next_include'] = "";
3 - Perform a search and replace in all your files: (except debug_include.php)
search: 'include((.*));' as a reg.exp
replace with: '{next_include($1);include('debug_include.php');}'
and
search: 'include_once((.*)); as a reg.exp
replace with: '{next_include_once($1);include('debug_include.php');}'
Maybe you should need another search-and-replaces if you have some non-standard includes like
include (.... include (.... include (....
I think you can find some better search-and-replace patterns, but I'm not a regular expression user so I did it the hard way.
You should definitely use objects, namespaces and MVC model. Otherwise there is no pure and clean solution to your problem. And please, don't use eval, it's evil.

Scraping Library for PHP - phpQuery?

I'm looking for a PHP library that allows me to scrap webpages and takes care about all the cookies and prefilling the forms with the default values, that's what annoys me the most.
I'm tired of having to match every single input element with xpath and I would love if something better existed. I've come across phpQuery but the manual isn't much clear and I can't find out how to make POST requests.
Can someone help me? Thanks.
#Jonathan Fingland:
In the example provided by the manual for browserGet() we have:
require_once('phpQuery/phpQuery.php');
phpQuery::browserGet('http://google.com/', 'success1');
function success1($browser)
{
$browser->WebBrowser('success2')
->find('input[name=q]')->val('search phrase')
->parents('form')
->submit();
}
function success2($browser)
{
echo $browser;
}
I suppose all the other fields are scrapped and send back in the GET request, I want to do the same with the phpQuery::browserPost() method but I don't know how to do it. The form I'm trying to scrape has a input token and I would love if phpQuery could be smart enough to scrape the token and just let me change the other fields (in this case username and password), submiting via POST everything.
PS: Rest assured, this is not going to be used for spamming.
See http://code.google.com/p/phpquery/wiki/Ajax and in particular:
phpQuery::post($url, $data, $callback, $type)
and
# data Object, String which defines the data parameter as being either an Object or a String. POST requests should be possible using query string format, e.g.:
$data = "username=Jon&password=123456";
$url = "http://www.mysite.com/login.php";
phpQuery::post($url, $data, $callback, $type)
as phpQuery is a jQuery port the method signature is the same (the docs link directly to the jquery site -- http://docs.jquery.com/Ajax/jQuery.post)
Edit
Two things:
There is also a phpQuery::browserPost function which might meet your needs better.
However, also note that the success2 callback is only called on the submit() or click() methods so you can fill in all of the form fields prior to that.
e.g.
require_once('phpQuery/phpQuery.php');
phpQuery::browserGet('http://www.mysite.com/login.php', 'success1');
function success1($browser) {
$handle = $browser
->WebBrowser('success2');
$handle
->find('input[name=username]')
->val('Jon');
$handle
->find('input[name=password]')
->val('123456');
->parents('form')
->submit();
}
function success2($browser) {
print $browser;
}
(Note that this has not been tested, but should work)
I've used SimpleTest's ScriptableBrowser for such stuff in the past. It's part of the SimpleTest testing framework, but you can use it stand-alone.
I would use a dedicated library for parsing HTML files and a dedicated library for processing HTTP requests. Using the same library for both seems like a bad idea, IMO.
For processing HTTP requests, check out eg. Httpful, Unirest, Requests or Guzzle. Guzzle is especially popular these days, but in the end, whichever library works best for you is still a matter of personal taste.
For parsing HTML files I would recommend a library that I wrote myself : DOM-Query. It allows you to (1) load an HTML file and then (2) select or change parts of your HTML pretty much the same way you'd do it if you'd be using jQuery in a frontend app.

Categories