include php file containing function in a web page - php

I have a php file which contains php function. I have to receive its return value in a part of my web page. Where do I put the include? in the head or in the body? how can I call the function inside my web page?

You can include the php file wherever you want, as long as it is before you call the method contained in it. You call the function between <?php ?> tags. You can use echo to output it to the page.
So if you have myfunc.php that looks like this:
<?php
function myfunc() {
return 'asdf';
}
?>
Then in php that includes it you can do:
<?php
include('myfunc.php');
echo myfunc();
?>
You can also choose to put the include method anywhere above that makes sense. The very top of the file is a common choice.
Also note that if your php file contains functions, you should probably be using require_once instead of include. See: http://php.net/manual/en/function.require-once.php

You can't call php code from a html file. However, you could simply make your html web page into a php web page like this:
<?php
include("yourphpfunction.php");
?>
<html>
<head>...</head>
<body>
....
<!-- put php result here: -->
<?php echo myfunction(); ?>
... more html
</body>
</html>
and save it as .php instead of .html.
That's all the magic.
You can also wrap it all up in one statement:
<html>
<head>...</head>
<body>
....
<!-- put php result here: -->
<?php
include("yourphpfunction.php");
echo myfunction();
?>
... more html
</body>
</html>
as long as your file gets parsed as php.

you can put the include in the top of your html page like
<?php
include 'file.php';
?>
<html>
<head>
.....
and on your HTML, you can do something like:
<div>my stactic text <?php echo myFunction(); ?></div>

You should require (require_once) the file, before you reach the part where your returned output should be echoed.
required file.php:
<?php $test = "hello world"; return $test; ?>
include include.php:
<?php $output = require_once('file.php'); echo $ouput; ?>

You need a php webpage, you can't call a php function or include a php page in html file.
Assuming your webapge is php, You can include that file in the top of the page inside the tag. But be sure to include the file before the function is called.
require_once 'path/to/your/file';
or
include_once 'path/to/your/file';
Then you can call the function in your php file like:/
$test = functionInYourIncludedFile();
echo $test;
Hope this helps you :)

look below :
<?php
function doSomthing() {
return $var
}
?>
<html>
<?php echo doSomthing() ?>
</html>
or
<?php include('functionFile.php') ?>
<html>
<?php echo doSomthing() ?>
</html>

Related

Assign variable to php template

I usually use Smarty template engine, so i separate database quesries and other logic from HTML template files, then assign received in PHP variable into Smarty via their function $smarty->assign('variableName', 'variableValue'); then display correct template file with HTML markup, and then i can use within that template my assigned variables.
But how correctly it will be done with .php file tempaltes, without Smarty?
For example, i use that construction:
_handlers/Handler_Show.php
$arData = $db->getAll('SELECT .....');
include_once '_template/home.php';
_template/home.php
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
...
<?php foreach($arData as $item) { ?>
<h2><?=$item['title']?></h2>
<?php } ?>
...
</body>
</html>
It's work. But i heard that it's not the best idea to do that.
So is this approach correct? Or maybe there's other way to organize it?
Give me advice, pelase.
Including templates in such a manner like in your example is not best idea because of template code is executed in the same namespace in which it is included. In your case template has access to database connection and other variables which should be separated from view.
In order to avoid this you can create class Template:
Template.php
<?php
class Template
{
private $tplPath;
private $tplData = array();
public function __construct($tplPath)
{
$this->tplPath = $tplPath;
}
public function __set($varName, $value)
{
$this->tplData[$varName] = $value;
}
public function render()
{
extract($this->tplData);
ob_start();
require($this->tplPath);
return ob_get_clean();
}
}
_handlers/Handler_Show.php
<?php
// some code, including Template class file, connecting to db etc..
$tpl = new Template('_template/home.php');
$tpl->arData = $db->getAll('SELECT .....');
echo $tpl->render();
_template/home.php
<?php
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
...
<?php foreach($arData as $item): ?>
<h2><?=$item['title']?></h2>
<?php endforeach; ?>
...
</body>
</html>
As of now template hasn't access to global namespace. Of course it is still possible to use global keyword,
or access template object private data (using $this variable), but this is much better solution than
including templates directly.
You can look at existing template system source code, for example plates.

How to return the contents of a HTML file without executing the code?

I have two files, an HTML file which contains the layout and basic CSS for the email and a PHP file which actually sends the email. I was wondering if there was any way to require or include the HTML file as the message to be sent from the PHP script.
For example:
HTML
<h1>A title</h1>
PHP
mail("email", "subject", require('htmlfile'));
I have tried something like this but it just puts the contents of the HTML file into the flow of the PHP script. Is there any way to have the HTML file just return text which I can save to a variable or something?
Thanks in advance!
mail("email", "subject", file_get_contents('file_name.html'));
PHP documentation states: Also, it's possible to return values from included files. You can take the value of the include call as you would for a normal function.
It gives an example of how to do this, you would need to modify your code to fit your needs though.
return.php
<?php
$var = 'PHP';
return $var;
?>
noreturn.php
<?php
$var = 'PHP';
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1
?>
You can try this, it will work for sure.
Your PHP file:
"msg.php"
<?php
$message = "This is a sample message";
?>
Your HTML file with a mail() function:
"mail.php"
<?php
require ('msg.php');
mail("sample.yahoo.com", "sample subject", $message);
?>
<html>
<head>
<body>
<h1>A title</h1>
</body>
</head>
</html>

Echo dynamic content in the middle of a page based on various conditions defined in the head

I am trying to dynamically echo some predefined template ('template-file-for-output.php') filled with some data (from the $var array) on a specific place in a number of pages (as an example, the page 'page.php').
Basically my goal is to have a system, in which
I set up the logic (in the 'logic.php' file), the functions needed (in 'functions.php'), the template (in 'template-file-for-output.php')
with which my colleagues can create whatever page (just as in 'page.php' for the sake of the example) they want with their content and their HTML as they wish and only need to include the functions.php and logic.php files at the beginning of their file, and the echo statement to have the dynamic content where they want it to appear.
The problem I'm having is that when I test this example and try to achieve this in 'page.php', I always get the content before the custom HTML from the page. I suppose it has to do with output buffering and this include in the outputContent function, I tried other things but without success.
Here the contents of the files:
logic.php:
$submitOK = false;
if ($submitOK === true) {
/** No errors, output the error free content */
$output = outputContent($var);
} else {
/** Errors, output the content with errors */
$output = outputContent($var, $errors);
}
functions.php:
function outputContent($var, $errors = null)
{
extract($var);
ob_start();
include 'template-file-for-output.php';
$output = ob_get_contents();
ob_get_clean();
return $output;
}
template-file-for-output.php:
<p>Some content with tags and so on, filled in by some values of the $var array.</p>
<p>Example with the $example variable extracted from $var <?php echo $example; ?></p>
<p>Another variable also from $var <?php echo $anotherVariable; ?>
page.php:
<?php
include 'logic.php';
include 'functions.php';
?>
<!DOCTYPE html>
<html>
<head><title>A page of the site</title></head>
<body>
<p>Something interesting (hopefully).</p>
<?php echo $output; ?>
</body>
</html>
Change ob_get_contents to ob_get_clean, ob_get_contents gets the contents of the buffer but leaves it intact. Your Previous code got the buffer assigned it a variable then, flushed the buffer to output.
function outputContent($var, $errors = null)
{
extract($var);
ob_start();
include 'template-file-for-output.php';
$output = ob_get_clean();
return $output;
}
Setting aside the point that there are currently templating systems that have already solved this problem quite effectively ...
I would try not include the template file, but rather read the file with file_get_contents and then echo it out inside the output buffering section.
function outputContent($var, $errors = null)
{
extract($var);
ob_start();
echo file_get_contents('template-file-for-output.php');
$output = ob_get_clean();
return $output;
}

Arguments to PHP template functions

This is more of a style question. I have a template file header.php in which I define a PrintHeader() function.
Callers of this function can specify, via global variables, the title of the page and any Javascript scripts to include when printing the header (because surely not every page will have the same title or want to include the same scripts). I chose to use global variables rather than function arguments because the latter would require the interface to change when adding new arguments.
Is this considered "good" style, and is there a "better" way to do what I'm trying to do?
header.php (simplified)
<?php
function PrintHeader()
{
global $pageTitle, $scripts; // Set by the caller of this function
echo <<<HEADER
<html>
<head>
<title>$pageTitle</title>
HEADER;
if( !empty($scripts) )
{
foreach($scripts as $script)
{
echo " <script type=\"text/javascript\" src=\"$script.js\"></script>\n";
}
}
echo " </head>\n";
}
?>
index.php (simplified)
<?php
$pageTitle = 'Welcome';
$scripts = array('script1', 'script2');
require('header.php');
PrintHeader();
// Print the rest of the page
?>
is there a "better" way to do what I'm trying to do?
sure.
I see no point in defining and calling a function at all. as well as in using heredoc.
header.php (dramatically simplified):
<html>
<head>
<title><?=$pageTitle?></title>
<? if( !empty($scripts) ): ?>
<? foreach($scripts as $script): ?>
<script type="text/javascript" src="<?=$script?>.js"></script>
<? endforeach ?>
<? endif ?>
</head>
index.php:
<?php
$pageTitle = 'Welcome';
$scripts = array('script1', 'script2');
require('header.php');
?>
but still it's not the best way, as it seems you're not using a template where it most valuable - to output page contents itself.
So, I'd make it in three parts:
links.php (simplified):
<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA = getdata("SELECT * FROM links");
$pagetitle = "Links to friend sites";
//etc
//and then call a template:
$tpl = "links.tpl.php";
include "main.tpl.php";
?>
where main.tpl.php is your main site template, including common parts, like header, footer, menu etc:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
and finally links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
notice native HTML syntax, which is highlighted, readable and centralized in one place instead of being split between numerous functions and files
The point is in having separate template for the every PHP page as well as main site template for them all. With such setup you'll get a lot of advantages such as custom error pages, multiple representations of the same data (say, HTML, JSON or XML) by switching only templates without changing the code and many more
The use of global variables is certainly not advisable, and I question the necessity of using heredoc as you have - not that there is anything inherently wrong with heredoc, just that you seem to have rather arbitrarily utilized it in this sample template.
It is not elegant to use a return-value of a function as the output of each template - this defeats one of the purposes of templates which is re-usability.
Take a look at smarty, if not to directly use it (after all, why re-invent the wheel), at least to get an idea of how a rendering class is used to shuttle in the variables that a template needs without resorting to messy globals.
Here's a very quick overview of a way to do templating:
You have a template class that you can assign data to and then render a template.
Template.php:
class Template
{
protected $data = array();
public function assign($key, $value)
{
$this->data[$key] = $value;
}
public function render($file)
{
extract($this->data);
require $file;
}
}
You then have your template, header.php:
<html>
<head>
<title><?php echo $pageTitle; ?></title>
....
In index.php, you then use the template class to assign data and render your template.
$tpl = new Template;
$tpl->assign('pageTitle', 'My page title!');
$tpl->render('header.php');
This is just a simple example to demonstrate the idea, and could give you a good starting point.
While "better" may be in the eye of the beholder, I would suggest having some sort of functions that set the page bits rather than exposing raw variables. For instance, instead of doing $pageTitle = 'Welcome'; you could have set_page_title('Welcome');.
For JavaScript you could have a function that adds to the current script set -- rather than possibly replacing it all -- such as add_javascript($code);. This will allow a developer to set all of these without having to keep track of what the variable name was, and also without needing to global it as well if they want to set it from within a function.
This is an alternative using output buffering.
p/example_page/index.php is one of your pages:
<?php
ob_start() ?>
<h1>Example</h1>
<p>This is the page content</p>
<?php $main = ob_get_clean();
ob_start() ?>
<script defer src="js/example_page/example.js"></script>
<?php $script = ob_get_clean();
$title = 'Example page';
include 'templates/base.php';
templates/base.php is your reusable layout:
<!doctype html>
<html>
<head>
<script defer src="js/main.js"></script>
<?php echo $script ?>
<title><?php echo $title ?> - Example website</title>
</head>
<body>
<header>
<nav aria-label="Main menu"></nav>
</header>
<main><?php
echo $main;
?></main>
<footer>Example footer</footer>
</body>
</html>
Global variables are generally considered bad, and should be avoided if possible.
Rather than listing every variable in the interface, as you said things could change, pass a single array to the PrintHeader() functions:
<?php
function PrintHeader($opts=array()) {
if(!isset($opts['title'])) $opts['title'] = 'Default Title';
echo <<<HEADER
<html>
<head>
<title>$opts['title']</title>
HEADER;
if(!empty($opts['scripts'])) {
foreach($opts['scripts'] as $script) {
echo " <script type=\"text/javascript\" src=\"$script.js\"></script>\n";
}
}
echo " </head>\n";
}
$opts = array('title'=>'Welcome',
'scripts'=>array('script1', 'script2'));
require('header.php');
PrintHeader($opts);
?>
This way, you can add new capabilities in the function without breaking old code.

Is there any way to return HTML in a PHP function? (without building the return value as a string)

I have a PHP function that I'm using to output a standard block of HTML. It currently looks like this:
<?php function TestBlockHTML ($replStr) { ?>
<html>
<body><h1> <?php echo ($replStr) ?> </h1>
</html>
<?php } ?>
I want to return (rather than echo) the HTML inside the function. Is there any way to do this without building up the HTML (above) in a string?
You can use a heredoc, which supports variable interpolation, making it look fairly neat:
function TestBlockHTML ($replStr) {
return <<<HTML
<html>
<body><h1>{$replStr}</h1>
</body>
</html>
HTML;
}
Pay close attention to the warning in the manual though - the closing line must not contain any whitespace, so can't be indented.
Yes, there is: you can capture the echoed text using ob_start:
<?php function TestBlockHTML($replStr) {
ob_start(); ?>
<html>
<body><h1><?php echo($replStr) ?></h1>
</html>
<?php
return ob_get_clean();
} ?>
This may be a sketchy solution, and I'd appreciate anybody pointing out whether this is a bad idea, since it's not a standard use of functions. I've had some success getting HTML out of a PHP function without building the return value as a string with the following:
function noStrings() {
echo ''?>
<div>[Whatever HTML you want]</div>
<?php;
}
The just 'call' the function:
noStrings();
And it will output:
<div>[Whatever HTML you want]</div>
Using this method, you can also define PHP variables within the function and echo them out inside the HTML.
Create a template file and use a template engine to read/update the file. It will increase your code's maintainability in the future as well as separate display from logic.
An example using Smarty:
Template File
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>{$title}</title></head>
<body>{$string}</body>
</html>
Code
function TestBlockHTML(){
$smarty = new Smarty();
$smarty->assign('title', 'My Title');
$smarty->assign('string', $replStr);
return $smarty->render('template.tpl');
}
Another way to do is is to use file_get_contents() and have a template HTML page
TEMPLATE PAGE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>$title</title></head>
<body>$content</body>
</html>
PHP Function
function YOURFUNCTIONNAME($url){
$html_string = file_get_contents($url);
return $html_string;
}
If you don't want to have to rely on a third party tool you can use this technique:
function TestBlockHTML($replStr){
$template =
'<html>
<body>
<h1>$str</h1>
</body>
</html>';
return strtr($template, array( '$str' => $replStr));
}
Or you can just use this:
<?
function TestHtml() {
# PUT HERE YOU PHP CODE
?>
<!-- HTML HERE -->
<? } ?>
to get content from this function , use this :
<?= file_get_contents(TestHtml()); ?>
That's it :)
Template File
<h1>{title}</h1>
<div>{username}</div>
PHP
if (($text = file_get_contents("file.html")) === false) {
$text = "";
}
$text = str_replace("{title}", "Title Here", $text);
$text = str_replace("{username}", "Username Here", $text);
then you can echo $text as string

Categories