I'm trying to make a function for including pages.
In fact For the beginning I used to work with a long code that checked for all pages:
if (isset($_GET]['p']) && $_GET['p']=='something') {include 'something.php'};
Now I work with more than 600 pages and this code is too long and I would like to simplify it.
Sometimes I do have pages that are note entitled like they are used, for example home will correspond to accueil.php etc.
So I've done an array in which I listed all exceptions:
like that:
$paramListepages = array(
'corbeille' => array(
'libelle' => 'corbeille',
'page' => 'php/trash.php'
),
'nouveaumessage' => array(
'libelle' => 'nouveaumessage',
'page' => 'php/envoyer.php'
),
etc...
In this array I have about 20 pages.
Now I've tried to create a function for including pages so here is my code:
function getPage($var)
{
if (isset($var)) {
$key = array_search($var, $paramListepages);
if ($key == false()) {
include('php/'.$var.'.php');
} else {
}
}
}
I do not understand why the first part does not work.
I first of all check if the var does exist in the array, if not I include the page corresponding to the var.
I do still do not know how to do the second part, but for now the first one does not work.
I have no message error, even if in my ubunto I activated the displaying of all errors.
In the main page index.php I call the function getPage($_GET['p'])
Any kind of help will be much appreciated.
I'd suggest accessing the entries in your array directly:
function getPage($var) {
if (empty($var))
// no page specified => default page
inlude('index.php')
elseif (array_key_exists($var,$paramListepages))
// page found => include it!
include (sprintf('php/%s.php', $paramListepages[$var]['page']));
else
// page not found => default page
inlude ('index.php')
}
Related
I need to load a view into a view within CodeIgniter, but cant seem to get it to work.
I have a loop. I need to place that loop within multiple views (same data different pages). So I have the loop by itself, as a view, to receive the array from the controller and display the data.
But the issue is the array is not available to the second view, its empty
The second view loads fine, but the array $due_check_data is empty
SO, I've tried many things, but according to the docs I can do something like this:
Controller:
// gather data for view
$view_data = array(
'loop' => $this->load->view('checks/include/due_checks_table', $due_check_data, TRUE),
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests'
);
$this->load->view('checks/due_checks',$view_data);
But the array variable $due_check_data is empty
I'm just getting this error, saying the variable is empty?
Message: Undefined variable: due_check_data
You are passing the $view_data array to your view. Then, in your view, you can access only the variables contained in $view_data:
$loop
$check_cats
$page_title
There is no variable due_check_data in the view.
EDIT
The first view is contained in the variable $loop, so you can just print it in the second view (checks/due_checks):
echo $loop;
If you really want to have the $due_check_data array in the second view, why don't you simply pass it?
$view_data = array(
'loop' => $this->load->view('checks/include/due_checks_table', $due_check_data, TRUE),
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests',
'due_check_data' => $due_check_data
);
$this->load->view('checks/due_checks',$view_data);
Controller seems has no error. Check out some notices yourself:
<?=$due_check_data?>
This only available in PHP >= 5.4
<? echo $due_check_data; ?>
This only available when you enable short open tag in php.ini file but not recommended
You are missing <?php. Should be something like this
<?php echo $due_check_data; ?>
OK, i managed to solve this by declaring the variables globally, so they are available to all views.
// gather data for view
$view_data = array(
'due_check_data' => $combined_checks,
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests'
);
$this->load->vars($view_data);
$this->load->view('checks/due_checks');
I am currently working on some upgrades of a small personal framework that uses MVC.
The way it works currently is that when Init.php is included in a certain file, instead of looking for a variable, it gets the text content of the file (The actual source code) and just "cuts out" the variables. I believe it's heavily unorthodox and honestly, just bad.
A fellow developer also worked on a framework that also used MVC and was able to do what I was wanting to do the correct way.
<?php
require 'Init.php';
$page['id'] = 'index';
$page['name'] = 'Home';
That's what both of our files look like, however, if I was to let's say, use a variable instead of a string on the $page['name'] element, the title of the page would literally be the variable name (Imagine "Sitename - $variable")
I've been for about 2 days looking for an answer, and I found one promising one that was basically using require_once and ob_get_contents, however, I do not wish to use require_once.
How could I do what my fellow developer has done?
Edit
Here's my current attempt at getting the array, it only works when using require_once.
/************* CONTENT PARSING **************/
global $page;
$buffer = explode('/', $_SERVER['PHP_SELF']);
$filename = $buffer[count($buffer) - 1]; // index.php in our case
var_dump($page); // Dumps NULL
ob_start();
include($filename);
echo $page['id']; // Echoes nothing
echo ob_get_contents(); // Echoes nothing
echo $page['id']; // Dumps nothing
ob_flush(); // Returns nothing
var_dump($page); // Dumps nothing
EDIT 2
Here's the way files are included and variables are declared
config.php and pageTpl.php are included in Init.php
config.php contains the $page array and is included before pageTpl.php
index.php includes Init.php
In a few words, the value that I want to assign to the id and name element of the $page array can only be accessed if you're on index.php, I would like it for the developer to access the variable globally. (Where Init.php is included)
I attempted to run a var_extract($page) on each of those files and the results were as follows:
config.php (Where the $page array is declared):
array ( 'id' => '', 'name' => '', ),
Init.php (Where config.php is included):
array ( 'id' => '', 'name' => '', ),
index.php (Where the values are changed):
array ( 'id' => 'index', 'name' => 'Test', )
pageTpl.php (File included in Init.php, attempts to access the $page array):
NULL
Okay, so after going around the documentation a few times and reading over the code of a few frameworks I noticed that the only way to get the final value of all those variables was using the PHP register_shutdown_function that is the function that is called after script execution finishes, this means that all variables are processed, calculated and can therefore all be accessed from that function as long as they are global.
Example:
index.php
<?
require 'Init.php';
$page['id'] = 'index';
$page['name'] = 'Home';
Then, on Init.php we do all the complicated frameworky-stuff, but we also include the kernel, that will contain the shutdown function
Init.php
<?
require 'inc/kernel.php';
new Kernel;
Now, the kernel, of course
kernel.php
<?
class Kernel
{
public function __construct()
{
register_shutdown_function('Kernel::Shutdown'); // Registers shutdown callback
spl_autoload_register('Kernel::LoadMod'); // Not exactly sure why is this function necessary, but it is. All I know is that it tries to files of called classes that weren't included
}
static function Shutdown()
{
global $page;
var_dump($page); // Will print what we defined in the $page array
Module::LoadTpl($page); // We pass the $page array to the tpl module that will do the rest
}
}
module.php
class Module
{
static function LoadTpl($page)
{
var_dump($page); // Will also print $page, but now we're not confined to kernel.php
}
}
Then, from the Module class you can pass the $page array to other classes/files.
When you define an array, with indexes, you need to do it in a specific way.
config.php:
<?php
$page = array('id' => "", 'name' => "");
var_export($page);
?>
This will create array called $page, with an index of id & name that have values of nothing.
Now in your index.php, you can assign values:
<html>
<body>
<pre>
<?php
include 'Init.php';
$page['id'] = basename($_SERVER['PHP_SELF']);
$page['name'] = 'Home';
var_export($page);
?>
</pre>
</body>
</html>
This should result in a page that shows:
array ( 'id' => '', 'name' => '', )
array ( 'id' => 'index.php', 'name' => 'Home', )
I'm running into some difficulty in using the added componenet requirelogin.php . This is the component that I've added
<?php
class RequireLogin extends CBehavior
{
public function attach($owner)
{
$owner->attachEventHandler('onBeginRequest', array($this, 'handleBeginRequest'));
}
public function handleBeginRequest($event)
{
if (Yii::app()->user->isGuest && !in_array($_GET['r'],array('site/login', 'site/index'))) {
Yii::app()->user->loginRequired();
}
}
}
?>
Note how 'site/index' is allowed in this as a page that I can visit.
Now, in my main.php I added the following
'behaviors' => array(
'onBeginRequest' => array(
'class' => 'application.components.RequireLogin'
)
),
Now, these two force me to go to site/login everytime - even though I have done as other stackoverflow answers have told me to and added
// sets the default controller action as the index page
'defaultController' => 'site/index',
Could anyone explain why this hasn't made my start page site/index?
_____________ ADDITION
I've also figured out that when I am going to the base action (i.e. mywebsite.com) it is NOT going to site/index. rather it is directly redirecting to site/login. This, however, does not occur, when I comment out the behaviors .
So, thank you darkheir for all of your work on this.
Ultimately, what happened was the $_GET['r] in the base path was simply '' because r was not point to anything in particular. As a result, when ever I looked in_array($_GET['r']) what I was getting in the very bae path was in_array('', array('site/login', 'site/account')) Now, unfortunately, '' is neither site/login or site/account so the page redirected using
Yii::app()->user->loginRequired();
The fix to this problem was
public function handleBeginRequest($event)
{
// note that '' is now one of the options in the array
if (Yii::app()->user->isGuest && !in_array($_GET['r'],array('site/login', 'site/index', '' ))) {
Yii::app()->user->loginRequired();
}
}
I met some trouble with a function.
In fact I would like to include all my pages, but the thing is that not all pages are named like the param $_GET['page'] for example if I call index.php?p=accueil it will redirect to php/home.php
an other example if I call index.php?p=message it will redirect transparently to message.php
For all exceptions I've generated an array like that:
<?php
$paramListepages = array(
'corbeille' => array(
'libelle' => 'corbeille',
'page' => 'php/trash.php'
),
'nouveaumessage' => array(
'libelle' => 'nouveaumessage',
'page' => 'php/envoyer.php'
)
);
?>
This array contain many sub_arrays As you can see the 2 firsts of this one.
For calling pages I've done a function like that:
function getPage($var) {
if (!isset($var)){
//Aucune page spécifiée => default page
inlude('php/accueil.php');
}
elseif (array_key_exists($var,$paramListepages)){
// page trouvée => on l'inclut!
include ('php/accueil.php');
}
else{
// page espectant la structure, non trouvée dans l'array => on l'inclut directement
include('php/'.$var.'.php');
}
}
actualy it seems to recognise the if condition and the else.
But when I ask for a page in the array, there is a blank page It seems to not be able to read the correct value expected.
I have white empty pages with no mistake or message error.
In my Ubuntu I've activated the error_reporting(E_ALL);
Any kind of help will be much appreciated
So basically this?
elseif (array_key_exists($var,$paramListepages)){
include ($paramListepages[$var]['page']);
}
I am modifying an already contributed drupal module (Inline Ajax Search) to handle searching of a specific content type with some search filters (i.e. when searching for help documentation, you filter out your search results by selecting for which product and version of the product you want help with).
I have modified the module some what to handle all the search filters.
I also added in similar functionality from the standard core search module to handle the presenting of the search form and search results on the actual search page ( not the block form ).
The problem is that when i submit the form, i discovered that I'd lose all my post data on that submit because somewhere, and i don't know where, drupal is either redirecting me or something else is happening that is causing me to lose everything in the $_POST array.
here's the hook_menu() implementation:
<?php
function inline_ajax_search_menu() {
$items = array();
$items['search/inline_ajax_search'] = array(
'title' => t('Learning Center Search'),
'description' => t(''),
'page callback' => 'inline_ajax_search_view',
'access arguments' => array('search with inline_ajax_search'),
'type' => MENU_LOCAL_TASK,
'file' => 'inline_ajax_search.pages.inc',
);
}
?>
the page callback is defined as such (very similar to the core search module's search_view function):
<?php
function inline_ajax_search_view() {
drupal_add_css(drupal_get_path('module', 'inline_ajax_search') . '/css/inline_ajax_search.css', 'module', 'all', FALSE );
if (isset($_POST['form_id'])) {
$keys = $_POST['keys'];
// Only perform search if there is non-whitespace search term:
$results = '';
if(trim($keys)) {
require_once( drupal_get_path( 'module', 'inline_ajax_search' ) . '/includes/inline_ajax_search.inc' );
// Collect the search results:
$results = _inline_ajax_search($keys, inline_ajax_search_get_filters(), "page" );
if ($results) {
$results = theme('box', t('Search results'), $results);
}
else {
$results = theme('box', t('Your search yielded no results'), inline_ajax_search_help('inline_ajax_search#noresults', drupal_help_arg()));
}
}
// Construct the search form.
$output = drupal_get_form('inline_ajax_search_search_form', inline_ajax_search_build_filters( variable_get( 'inline_ajax_search_filters', array() ) ) );
$output .= $results;
return $output;
}
return drupal_get_form('inline_ajax_search_search_form', inline_ajax_search_build_filters( variable_get( 'inline_ajax_search_filters', array() ) ) );
}
?>
from my understanding, things should work like this: A user goes to www.mysite.com/search/inline_ajax_search and drupal will process the path given in my url and provide me with a page that holds the themed form for my search module. When i submit the form, whose action is the same url (www.mysite.com/search/inline_ajax_search), then we go thru the same function calls, but we now have data in the $_POST array and one of them is indeed $_POST['form_id'] which is the name of the form "inline_ajax_search_search_form". so we should be able to enter into that if block and put out the search results.
but that's not what happens...somewhere from when i submit the form and get my results and theme it all up, i get redirected some how and lose all my post data.
if anybody can help me, it'd make me so happy lol.
drupal_get_form actually wipes out the $_POST array and so that's why I lose all my post data.
according to this: http://drupal.org/node/748830 $_POST should really be ignored when doing things in drupal. It's better to find a way around using it. One way is the way described in the link, making ur form data persist using the $_SESSION array. I'm sure there are various other and better ways to do this, but yeah, drupal_get_form was the culprit here...