Why is my conditional statement not working? - php

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
}

Related

Include Dynamically Named Files

I'm just curious how I can include a PHP file that doesn't have a static name like home.php, or contacts.php?
I want to have it so when I click on a link it includes the name of the page I was sent to.
So, I click on "Contacts", instead of my code being:
<?php include "contacts.php"; ?>
It's:
<?php include "somekindofcodetohavethisdynamic.php"; ?>
Is there a way to do this?
There should be some logic that returns the dynamic stuff, right? Put that into a function:
function getDynamicName($page) {
// Magic happens here.
}
And, get it stored in some variable. And include it in the normal way.
$contactPage = getDynamicName("contact");
include "{$contactPage}.php";
If you are very lazy, you can do this as well:
include getDynamicName("contact") . ".php";

PHP- can't see class member after include

ok i have an index.php as so:
<?php
require 'php/stdlib.php';
$site->page->render();
foreach($page as $var => $value) {
echo $var ." is ". $value." <br/>";
}
?>
the obj creation for site and page is in the stdlib file and is obviously working cuz
the -for each- loop prints out:
name is welcome
headers is inc/index_h.php
footers is inc/index_f.php
contents is inc/welcome.php
It show that the object is created.
I also did a var dump with proper results
here is site---page---render:
public function render_page(){
$this->page->render();
}
here is page---render:
public function render(){
include $this->headers;
include $this->contents;
include $this->footers;
}
however the result of the script is the following:
Undefined variable:
and also
Trying to get property of non-object:
both errors point to my $page object that i used in the include file for the page header:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $page->name; ?></title>
<script src="/scripts/jquery.js"></script>
</head>
<body>
The errors actually print out in the html title tag not on the screen meaning i have to use View Source on my browser to see it
How do i get the $page object to be visible when using an include
Im usually pretty good about finding answers myself but this thing has me stumped for two days now.(I have learned alot about many other things while searching for answer tho so I guess not all is lost) If anyone could help me I would greatly appreciate it.
Probably should have added that the page and site object are instantiated in stdlib.php with the following
$site = new csite();
site_ini($site);
$page = new cpage("welcome");
$site->setPage($page);
When you use PHP's build-in include function, the contents of the included file are executed in the same scope as the call to include. Therefore, you really want to call $this in the included files, as their code is executed as-though it were actually written inside the render() method, and you will note that no $page variable was declared in that method.
On the other-hand, it may make more syntactic sense to set $page = $this prior to the first include.
I up-voted for you because, while the title does not suggest it, you are actually highlighting an important aspect of the PHP include and require functions: the way they pass scope.
For more information about this topic, have a close read of the PHP.net documentation on the function:
http://www.php.net/manual/en/function.include.php
Edit: To clarify why one example works, and another does not, it is because $page, from the include, has the same scope as your foreach, but is not declared inside the render.
Do not pull it in as a global, however. As syntactically you want to render the page you call render on, so: $this

PHP use function as return;?

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

Where exactly do I put a SESSION_START? [duplicate]

This question already has answers here:
When do I have to declare session_start();?
(2 answers)
Closed 9 years ago.
So I'm starting my own website and I have the login file pretty much made. I just need to figure out where to put the session_start to keep the user logged in. Where exactly do I put the session_start? Do I put it right in the login file? Or where do I put it?
Thanks for the help
Put it after your PHP start tag <?php ... like this
<?php
session_start();
//... your code....
//more code....
Read more on sessions from the PHP Manual. Here
Note : Also keep in mind, you need to call session_start(); on each and every page if you are making use of session variables.
Put it right after the start tag, or else headers will have been send, and the session, AFAIK, has to be the first header sent
<?php
session_start();
//session code here
?>
Right after <?php tag.
Be sure that there is NO output before this function (even a space symbol or so).
You want to put session_start(); at the top of your page before any other code. However, if you are using includes to make your life easier, it's best to put it at the very top of a file that is included in all files. For instance, when I make a website, I put all of my header code and footer code in separate files and include them in the other files. I also have a functions file that is included in every other page of the website. So for my index file, it may look something like this:
<?php include_once("includes/header.php"); ?>
<div id="content">
Website Content
</div>
<? include_once("includes/footer.php"); ?>
Then, my header file would start like:
<?php include_once("includes/functions.php"); ?>
<!doctype html>
<html>
<body>
Then at the top of my functions file:
<?php session_start();
[functions]
?>
In this way, the functions files' code gets ran first, therefore the session start code is the very first thing hit. Why? You cannot have any type of output to the browser before starting a session.
it's better to have a separate file other than your login to do some common stuffs.
i think your login file will be generally handling user verification and validation thing. so don't include that file on every page.
have one more file that
includes all required files
keeps all your analytic scripts
initializes global variables
and this file you can start with <?php session_start(); ?>
session_start() needs to go in every page/file that refers to $_SESSION (obviously the login page is included).
Because you should only be calling it once, I tend to write a lazy_session_start() method (and tend to put it in an include file):
/**
* Lazily calls session_start (to prevent warnings).
*/
function lazy_session_start() {
if (!isset($_SESSION) || !is_array($_SESSION)) {
session_start();
}
}
It could be called like so (before you need to use $_SESSION):
<?php
//you must either declare "lazy_session_start" function
//or import the file containing the function definition.
require_once('lazy_session_start.php'); //or something.
lazy_session_start();
//... you may now use the $_SESSION array.

Having includes with variables in two places at once

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.

Categories