I'm using include(); to load certain parts of my page, but sometimes if I'm working on a specific area I want the include(); function to terminate somewhere within that included file, so I use return; and everything following that line will not be included when include(); is called on that file. I can't use die(); because sometimes I have other files needed to be included as well.
Now, I want to be able to control that return; function in terms of what other users see, for instance - I'd like to limit what types of users can see beyond that return; line within the included file. I want admin level users to be able to see beyond that point but not regular users. So I use some kind of if() { } statement to check the user type. Sometimes I want only myself to be able to view the content after the return; line, and I then add if($ip != $my_ip) return;.
The problem is that I have to manually write this stuff, but since I use it often I'd like to write a function that I can pass to what users I want to let bypass the return; part. So I setup a terminate(); function, something like this:
function terminate($param) {
// if statement
{
return;
}
}
But the return; line in that function only returns within that function, it doesn't have any effect on the file that called that function. So in other words, the return; line in my terminate(); function won't actually do the return; I need to stop the include(); function going beyond it.
So how do I stop the include(); command on my file going beyond a certain point with a function and have it not interrupt the remaining code after stopping an include();?
Edit: as a temp fix, I'm using this:
if(terminate($param)) return;
So after passing my parameters to the function if it returns true (stop the include();), it will return; on the file I'm including. So it works that way, I'm just wondering if it's possible to just have a terminate($param); command that will fire the return; command on the file that called that function without having to wrap it around in an if() statement?..
In general, most of the modern projects, which are trying to use clean templates with only HTML, that are obeying the MVC architecture, etc, are using conditions in their templates. There's nothing wrong in it. If you are template looks clean.
<div class="content">
<span class="subcontent"> some content </span>
<?php if ($app->UserController->hasPermissions($_SESSION['id'])): ?>
<span class="admincontent"> Admin Content </span>
<?php endif; ?>
</div>
This kind of code is considered OK. Your view DO have conditions and loops. You cannot avoid them. Also it does not look that clean if you have
<div class="content">
<span class="subcontent"> some content </span>
someFunction();
<span class="admincontent"> Admin Content </span>
</div>
Which will also hide all the content till the end of the file. And it's hard to manage it. It's not impossible still. You can use output buffer for that:
Let's say you have:
functions.php
<?php session_start(); $_SESSION['user_id'] = 1; //fictive session code ?>
<?php
function hasPermissions() {
if ($_SESSION['user_id'] != 1) {
ob_end_clean();
}
}
?>
<?php ob_start(); ?>
end.php
<?php $ob = ob_get_contents();?>
<?php ob_end_clean(); ?>
<?= $ob; ?>
Template.php
<?php include("functions.php"); ?>
<p>included content</p>
<?php hasPermissions(); ?>
<p> included content 2 </p>
<?php include("end.php"); ?>
so, if you are with session id = 1, and running Template.php file, the output will be:
included content
included content 2
Else it will output
included content
Related
I'm trying to use one header.php to process both my public pages and my admin pages using conditional statements. I can get this technique to work when I use an include, but I learned a different technique for including files using a function and now my conditional statements for admin and public are not working.
So this code is at the top of my header.php wrapped in php tag.
if (!isset($layout_context)) {
$layout_context = "public";
}
Then in my header tag I have sections of code like this
<?php if($layout_context == "public") { ?>
<header id="home">
<?php ; } elseif($layout_context == "admin") { ?>
<header id="cms-pages">
<?php ; } ?>
Then in all my pages I put this code at the top
<?php $layout_context = "public"; ?>
or
<?php $layout_context = "admin"; ?>
When I use this code:
<?php include("includes/layouts/header.php"); ?>
I can get those conditional public and admin codes to work, but when I try and use this technique to include my header.php
<?php include_layout_template('header-admin.php'); ?>
function lives in the functions.php in the includes folder.
function include_layout_template($template="") {
include(SITE_ROOT.DS.'includes'.DS.'layouts'.DS.$template);
}
I can't get the conditional code to work. Does anyone know why that might be?
Thank you :)
You state that after a standard include include("includes/layouts/header.php");, you are able to use $layout_context, but that after an include using a function include_layout_template('header-admin.php');, you are not.
This is to problems with variable scoping.
Your $layout_context is defined within the header.php file, outside of any function declaration.
In a file like this, if you include it at the global level, then the variables in it will be come global variables.
However, if you include it from within a function, then those variables become variables within that function.
Thus when you call include_layout_template(), the variables are created, but are only scoped within include_layout_template(). As soon as the function returns, those variables are no longer available.
The quick and dirty solution here is to define them as global within the header.php file. So add global $layout_context; to the top of the code in this file, and the same for any other variables declared within it.
That will probably get you up and running with the minimal work from where you are now.
However, global variables are a very blunt tool and generally considered very poor practice for a number of reasons. You would be much better off rewriting your config variables so that you can reference them from a function call or object. This way you can include them from wherever, any they will still be accessible in the same way.
Dont use == for string comparison. Always use strcmp() for string comparison.
Change
if($layout_context == "public")
to
if (strcmp($layout_context, "public") == 0)
{
//string is equal
}
I have a question, there is a way to update $error when his value change on external listPagPrinc.php?
<div id="statoPag">
<h3> Stato : <?php echo $error; ?> </h3>
</div>
<div class="headerCont">
<?php
include('procedure/listPagPrinc.php');
?>
</div>
Not as-is, no. Think of these HTML/PHP files like an office printer, once it prints out each line, you can't "go back" and print over it
In this example, all of the first 5 lines are run and effectively "set in stone" before anything is called in procedure/listPagPrinc.php.
If, and this is just speculation, you can't simply include procedure/listPagPrinc.php before you render $error because it also is printing additional HTML, you just need to encapsulate its code in functions as best as possible: One to set the value of $error, and a separate one to output the HTML you need.
You need to update the text content of the tag; you can do this with e.g. jQuery at runtime. This is the preferred way if some tags, and only those, change during the lifetime of the application page, and you do not wish to reload the whole page from scratch.
In this case, from listPagPrinc.php, you can output some Javascript code:
echo <<<JAVA1
<script>
alert("Ciao, mondo");
</script>
JAVA2;
or in your case using jQuery
echo <<<JAVA2
<script>
$('#statoPag h3').text("Errore!");
</script>
JAVA2;
Very likely the call will need to be inside a jQuery onDocumentReady function to be sure that it executes.
A better and faster way (and as #arkascha observed, nicer and more robust): you can generate the header from listpagPrinc.php or from a wrapper.
// file listPagPrincWrapper.php, replace your current file
// Ideally listPagPrinc could return a text value. In case it is
// printing it, as seems likely, we capture the output. This way
// we don't neet to modify the existing code.
ob_start();
include('procedure/listPagPrinc.php');
$lpp = ob_get_clean();
// At the end, we do the output part.
print <<<HTML
<div id="statoPag">
<h3> Stato : {$error}</h3>
</div>
<div class="headerCont">{$lpp}</div>
HTML;
I am relatively new to php and wordpress and I would like to know how I can render a php file without the include statement.
For example if I have two files plugin.php and component.php
plugin.php
<?php
add-shortcode('myshortcode', 'myshortcode-func');
function myshortcode-func()
// magic function that loads
$result = LOAD('component.php');
return $result;
}
?>
component.php
<div>
<img scr="<?php getimage() ?>" />
</div>
NB
I don't want to use include because I think it screws the rendering and insert the page in the flow when called.
Thanks for you help !
You can use an output buffer:
function myFunc(){
ob_start();
include('component.php');
return ob_get_clean();
}
How to:
$php = file_get_contents("component.php");
eval($php);
eval is very dangerous though and shouldn't be used in production.
If this is for production, I'd recommend using hooks/filters (see wordpress source code). This lets you execute blocks of code on the fly, but is more constrained.
I am working with levels of security with my app and i have written a function that simply checks - depending on it's session user id what kind of priviligies he/she has. It works fine but in some pages i want to output some information if the user is superuser, and forbid to output information if user is a guest.
I do it with such a syntax:
1. <? if admin('superuser', $_SESSION['user_id']) { ?>
2. <div></div>
3. <? } ?>
It works good but it's not elegant, and in case long code between curling brackets it messess with purity of my code.
Is there a way to "alias" a line 1 and 3 to some kind of shortcut, ie
1. <? admin_superuser ?>
2. <div></div>
3. <? admin_super_user_end ?>
Maybe you have some other ideas to perform such levels of security?
The idea came from ob_start() and ob_end() commands.
I am waiting for your ideas.
Kalreg.
you could simply set a bool at the beginning of the page:
$isSuperUser = admin('superuser', $_SESSION['user_id']);
Then, just do
<? if ($isSuperUser) { ?>
<div></div>
<? } ?>
If you don't like the $, you could define a constant:
define("SUPERUSER", admin('superuser', $_SESSION['user_id']));
Then, just do
<? if (SUPERUSER) { ?>
<div></div>
<? } ?>
Good thing about a constant is that it is global, and if using in a function, you wouldn't have to declare it global first, or pass it as an argument.
I would go with something like this. I think this totally acceptable.
To simplify it you just need a wrapper for your user.
<?php if ($user->isAdmin()): ?>
<div></div>
<?php endif; ?>
you can include another php file that contains the corresponding html / php code with the "include" function. i also recommend to use <?php instead of just <? due short open tag issues with xml and ini settings.
I have a small situaton here. I'm building a custom CMS for one of my websites.
Below is the code for the main index page:
<?php
require("includes/config.php");
include("includes/header.php");
if(empty($_GET['page'])) {
include('pages/home.php');
} else {
if(!empty($_GET['page'])){
$app = mysqli_real_escape_string($db,$_GET['page']);
$content = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM pages_content WHERE htmltitle = '$app'")) or die(mysqli_error($db));
$title = $content['title'];
$metakeywords = $content['htmlkeywords'];
$metadesc = $content['htmldesc'];
?>
<h1><?php echo $content['title']; ?></h1><hr /><br />
<div id="content"><?php echo $content['content']; ?></div>
<? } else { include('includes/error/404.php');} }
include('includes/footer.php'); ?>
The file, includes/header.php contains code to echo variables, such as, page title and meta stuff.
The issue is that when the include("includes/header.php"); is where it is, outside of the if conditions, it will not echo the varables, obviously, however, I can't put the include in the if condition otherwise, the home page, which does not require any url variables will show without these conditions.
What do I do?
You can't really write code like this for too long. It's ok to for start, but you will soon realize it's hard to maintain. The usual way is to split it into a few steps.
First check input and determine on which page are you
If you know you are on the homepage, include something like includes/templates/homepage.php
Otherwise try to load the page from the database
If it worked, include includes/templates/page.php
Otherwise include includes/templates/404.php
Each of the files in includes/templates will output the whole page, i.e. they all include the header, do something and include the footer. You can use for example Smarty templates instead of PHP files, which will make the approach obvious.
Once you have this, you can split the code even more. Instead of loading the page directly from index.php, include another file which defines a function like load_page($name) and returns the page details.
Then a few more changes and you realize you are using the MVC approach. :) The functions that load data from the database are your Models, the Smary templates are Views and the PHP files that put them together are Controllers.