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>
Related
I am trying to turn an existing website in an API, in order to do that I need to return some content as HTML inside a JSON. The problem I am having is that I can't find a way to make templating work.
I tried to do this
class TestController
{
public function get() {
$adapter = new Adapter();
$data = 'some data';
$html = include $_SERVER['DOCUMENT_ROOT'] . 'template.php';
$result = [
'html' => $html
];
return json_encode($result);
}
template.php:
<div>
<br/><?= $data ?><br/>
</div>
but it is returning the HTML alongside the JSON and of course html = 1 because include returns 1 on success, like this:
<div>
<br/>some data<br/>
</div>
{'html':1}
Is there a way for me to get the content from the included file without using a return statement inside the template?
Your problem is that using include essentially treats your template.php file as a single giant "echo" because there is no value returned inside template.php
You could change the template.php file to return a HTML string, and it would achieve what you want, but this is a nightmare to look at and manage.
return '<div>
<br/>' . $data . '<br/>
</div>';
An alternative, is to "capture" the output of the included file. Its a lot nicer on your template.php file and achieves the same thing. The output buffer functions essentially capture any information "echoed" - you need to be careful using this and the placement of your session_start however as it can catch you off guard depending on how your application is bootstrapped.
This is done by using three ob_ functions the main one being ob_get_contents which will be the contents of template.php in the example below.
http://php.net/manual/en/function.ob-get-contents.php
ob_start();
include $_SERVER['DOCUMENT_ROOT'] . 'template.php';
$html = ob_get_contents();
ob_end_clean();
This was your template files stay nice and clean, and the contents are all captured for returning in your json format.
you can use ob_start like this
ob_start();
include 'path_to_your_file.php';
$result= ob_get_contents();
ob_end_clean();
I am trying to add a dynamic variable into include function in php
Here is the code I am trying to do but didn't work
$theme = "1";
include("s-include/themes/starecom-theme".$theme."/index.php");
$theme data is 1/2/3
and I want to include folder no 1/2/3 into include
its didn't give any error only blank page view.
actual url : s-include/themes/starecom-theme1/index.php but theme1/2/3 changed dynamically from the database which selected
Please help me to solved this issue
Thanks to All
If you get 1/2/3 from data-base and you have to include each file (seperated with /) then try below code. It will explode your data then include each file.
$theme = "1/2/3";
$theme_array = explode("/", $theme);
foreach ($theme_array as $key => $value) {
include("s-include/themes/starecom-theme".$value."/index.php");
}
Is there anyway to access variables of one php file into another?
- I am trying to validate a form. I need to access variables from the validationConditions.php file in form.php file.
I have tried creating sessions but they are error prone.
I am using the latest version of dreamweaver.
Is it possible to use $_POST to achieve the results?
Any example will be welcome...
Thanks a lot in advance.
The easiest would be to use session variables. In the first page you could set the values like this
session_start();
$_SESSION['myvar'] = 'My Data';
Then in the second page you can retrieve the data like this...
session_start();
$myvar = $_SESSION['myvar'];
Which in turn sets $myvar to "My Data"
You can read a php file with another php file. Assume that we have 2 php files.
new.php
<?php
$a="something";
?>
serach.php ---> search in new.php
<?php
// What to look for
$search = '$a'; //WE are searching $a
$lines = file('new.php'); // in new.php
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo $line;
}
?>
Something like that. You have to edit this file.
A somehow devious solution:
ob_start();
$request = array(
"_id"=>"0815",
"user"=>"john",
"email"=>"john#dunbar.com",
"phone"=>NULL
); // Don't know. Just how u need your request to look like.
include('validationConditions.php');
$response = getValidationConditions($request); // Function in 'validationConditions.php' that responds an array or a JSON
$out = ob_get_clean();
echo json_encode($out);
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
I have a standard config file: $variable = 'value';, but at the last moment came up to use the web interface to configure it. So what is the best way to read the file, find the value of variables and then resave the file again?
At the moment I have 2 ideas:
1) RegExp
2) Keep somewhere array example
Store all config values in an associative array like so:
$config = array(
'variable' => 'value'
);
For the web interface, you can easily loop over the entire array:
foreach($config as $key=>$value) { ... }
After making changes, loop over the array and write it back to the file. (You really should be using a DB for this, though).
When you include the file, you can either use it like this:
include('config.php');
echo $config['variable']
// or
extract($config);
echo $variable;
Note: If you extract, it will overwrite any variables by the same name you might have defined before extracting.
PS - To make it easier to read and write to and from a file, I would just use json encoding to serialize the array.
Use a db
If your config is user defined - it would be better to store the config in a database. Otherwise you have this "novel" problem to solve but also potentially introduce security problems. I.e. for any one user to be able to edit your config files - they must be writeable to the webserver user. That opens the door to injecting malicious code into this file from a web exploit - or simply someone with direct access to your server (shared host?) finding this writeable file and updating it to their liking (e.g. putting "<?php header('Location: my site'); die;" in it).
One config variable
If you must manage it with a config file, include the file to read it, and var_export the variables to write it. That's easiest to do if there is only one config variable, that is an array. e.g.:
function writeConfig($config = array()) {
$arrayAsString = var_export($config, true);
$string = "<?php\n";
$string .= "\$config = $arrayAsString;\n";
file_put_contents('config.php', $string);
}
Allow partial updates
If you are changing only some variables - just include the config file before rewriting it:
function writeConfig($edits = array()) {
require 'config.php';
$edits += $config;
$arrayAsString = var_export($edits, true);
$string = "<?php\n";
$string .= "\$config = $arrayAsString;\n";
file_put_contents('config.php', $string);
}
Multiple config variables
If you have more than one variable in your config file, make use of get defined vars and loop on them to write the file back:
function writeConfig($_name = '', $_value) {
require 'config.php';
$$_name = $_value; // This is a variable variable
unset($_name, $_value);
$string = "<?php\n";
foreach(get_defined_vars() as $name => $value) {
$valueAsString = var_export($value, true);
$string .= "\$$name = $valueAsString;\n";
file_put_contents('config.php', $string);
}
}
The above code makes use of variable variables, to overwrite once of the variables in the config file. Each of these last two examples can easily be adapted to update multiple variables at the same time.