How to access all include files in a directory in Codeigniter - php

I am using jquery datatable plugin which is in outside of my Codeigniter app. The datatable php editor uses namespaces.
And i have to import all editor class files inside the codeigniter controllers. So, i have to pull all files and classes inside to the "/assets/datatable/extensions/Editor/php" into my newly created controller file.
Controller file code,
// trying to import all files in this directory
$path = $_SERVER['DOCUMENT_ROOT'] . '/datatables/extensions/Editor/php';
//set_include_path(get_include_path() . PATH_SEPARATOR . $path);
ini_set('include_path', get_include_path() . PATH_SEPARATOR . $path);
Editor::inst($db, 'contactus', 'id')
->fields(
Field::inst('Position')
->validator('Validate::numeric', array('empty' => false)), Field::inst('Question')
->validator('Validate::notEmpty'), Field::inst('Answer')
->validator('Validate::notEmpty')
)
->process($_POST)
->json();
The both "set_include_path" and "ini_set" not working in my case. It returns the below error
Fatal error: Class 'Editor' not found in /var/www/html//application/controllers/ajax.php on line 50.
Please suggest for the same.

This always works for me:
require_once($path);
instead of ini_set(). Also make sure that the path is really correct. You can use a relative path (relative to index.php). So you get something like $path = './application/libraries/custom/autoload.php';.
(I can't post this as a comment)

Related

PHP __autoload() from lower directory

I a primary website and a site using a subdomain with the following directory structure
Primary website:
/home/mysite/public_html/
Subdomain:
/home/mysite/subdomain/
I would like my classes directory to be shared between the primary and subdomain. The classes reside here:
/home/mysite/public_html/classes/
I am trying to autoload the classes from a file in the subdomain's directory
/home/mysite/subdomain/includes/bootstrap.php
which contains this code:
$classdir = '/home/mysite/public_html/classes/';
function __autoload($class_name) {
var_dump($class_name);
require_once ($classdir.$class_name.'.php');
}
My issue is that the classes are not being loaded.
Please note this code works perfectly when used in a file located in the primary domain directory:
/home/mysite/public_html/includes/bootstrap.php
Including them individually works fine, such as:
require_once($classdir.'/class1.php');
require_once($classdir.'/class2.php');
However there are dozens of them and i would like to autoload them
Thank you for your time.
Fixed the issue with spl_autoload_register() as below
$classdir = '/home/mysite/public_html/classes/';
function autoLoader( $class_name ){
$path = $classdir . $class_name . '.php';
include_once( $path );
}
spl_autoload_register( 'autoLoader' );

How to select 2nd parent folder relative to the provided path?

In CodeIgniter, there are available defined filepath constants inside the /public/index.php.
There are following constants available:
BASEPATH returns C:/wamp/www/testci2_2.dev/system/
SELF returns index.php
SYSDIR returns system
FCPATH returns C:\wamp\www\testci2_2.dev\public\
Inside my controller /application/controllers/configurations.php within a function backup() method, I would like to make backup files write directly to the /sql/ folder which is located here: C:\wamp\www\testci2_2.dev\sql\
I tried to use var_dump(dirname(BASEPATH) . '/sql/'); which produces what I want, but I am not quite sure if it's the best way to do that, maybe there is smarter steps to get that path ?
How can I target that folder by using some of this constants ?
If it is not possible, is there any other CLEVER method so when one day I decide to move controllers into the subfolders or so, they will not loose the track from specified folders ?
You need to use pathinfo to extract the directory name from FCPATH prior to \public\
$path = pathinfo(FCPATH, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR . 'sql' . DIRECTORY_SEPARATOR;
echo $path; // C:\wamp\www\testci2_2.dev\sql\

Path issue with autoload function to get files for use in Ajax

So my project uses an MVC framework and I have a page with an Ajax script I run to get content from the server. When the PHP script is called in the Ajax script, I want to access the classes already in my library for use in the PHP script. To do this, I use what I call an ajaxBootstrap to call the appropriate function that then instantiates the objects needed for that specific Ajax script.
To load those classes from my library I have an autoload function in my ajaxBootstrap so I don't need to use a bunch of require and include statements. My problem is those files aren't being loaded due to a path issue with the autoload function. When I use a require statement with the same path, the classes load with no problems, its only when I try to load them using the autoload function that I get an 500 internal server error.
Here is my ajaxBootstrap file:
// This file routes Ajax requests made in JS files and instantiates a specific object to carry out the actions needed for that particular Ajax operation
// Autoload any classes that are required
function autoLoad($classToLoad)
{
if(file_exists('../library/' . $classToLoad . 'class.php')) // File in the library folder
{
require('../library/' . $classToLoad . '.class.php');
}
else if(file_exists('../../app/models/' . $classToLoad . 'class.php')) // File in the models folder
{
require('../../app/models/' . $classToLoad . '.class.php');
}
}
spl_autoload_register('autoLoad');
// Determine which function to call based on the url that's listed in the Ajax request
switch($_GET['action'])
{
case 'pageOne':
pageOne();
break;
case 'pageTwo':
pageTwo();
break;
}
function pageOne()
{
$test = new Test();
$test->funcThatReturnStuff();
}
function pageTwo()
{
$test2 = new Test2();
$test2->funcThatReturnStuff();
}
Like I mentioned eariler, if I use a require statement such as:
require('../library/Test.class.php');
$test = new Test();
$test->funcThatReturnStuff();
The class loads and works just fine. But using the same path in the autoloader function throws an error. The really odd thing is if I put an else if statement in the autoloader that loads a class from the folder where my ajaxBootstrap is it also works fine too...
I know I could just use the require statements and be done with the problem but I want to be able to scale the project and not need to use loads of require statements in the future. BTW, I use '../' to get from where my ajaxBootstrap file is to my other folders.
Also, to add to my previous post, I've tried replacing the ../ with absolute paths using define('ROOT', dirname(__FILE__) . '/') and also define('ROOT', $_SERVER['DOCUMENT_ROOT'] . '/path/to/folder/') neither of which worked and still gave me the internal server error in Firebug. In addition, I haven't received any errors in my error log either.
Nevermind... Even after staring at my code for the past few hours I somehow missed the missing period in two of my file paths. I hate coding sometimes... Thank you to anyone who took time to read this.

How to write or open a php array without evaluating or expanding magic constant __DIR__

I have a config file that is a php array named config.php.
return array(
'template_dir' => __DIR__ '/configs/templates.php'
)
Then whenever I want to use this config file I would just include config.php. Its also really easy to write a config file in this way.
file_put_contents($config, 'return ' . var_export($data, true));
But I would like to be able to write the magic constant DIR to the config file without it expanding. So far I have not been able to come up with a way to do this. I have tried everything to writing a recursiveArrayReplace method to remove the entire path and trying to replace it with
__DIR__
but it always comes up as
'__DIR__ . /configs/template.php'
Which in that case will not expand when its ran.
How can I write
__DIR__ to an array in a file or how ever else without the quotes so that it looks like,
array('template_dir' => __DIR__ . '/configs/templates.php');
This is not possible, because var_export() prints variables, not expressions.
It would be better to write all your paths as relative directories instead and canonicalize to a full working path after fetching the data.
You could also consider returning an object:
class Config
{
private $paths = array(
'image_path' => '/configs/template.php',
);
public function __get($key)
{
return __DIR__ . $this->paths[$key];
}
}
return new Config;
Alternatively, you'd have to generate the PHP code yourself.
Instead of replacing the path with __DIR__, you need to replace the starting apostrophe as well.
E.g. if the path were /foo/bar then you'd want to do this replacement:
"'/foo/bar" to "__DIR__ . '"
Before:
'/foo/bar/configs/template.php'
After:
__DIR__ . '/configs/template.php'
What about write the config directly by:
$data = <<<EOT
return array('template_dir' => __DIR__ . '/configs/templates.php');
EOT;
file_put_contents($config, $data);

Implementing a 100% portable php application

I am seeking a way of allowing my PHP applications to be perfectly portable. My problem is, although I am utilizing relative path to include PHP classes, I always face issues when I try to deploy me application in a new environment.
For example, I have implemented an application under Ubuntu and it just run perfectly. However, when I moved it to a shared hosting running Centos, I had to modify all the include statements.
So, I am asking about the best way to include classes, considering having multiple folders which contain various classes that are dependent on another multiple classes in different levels of the folder hierarchy.
just keep one "main" folder.
In your index.php (for ex.) configure the "main" folder location and either use that as the 'base' for includes (I suppose you hard-code the include/require path?)
Else use the 'base' within the autoload functionality.
Now you are able to move the 'main' folder around and all you need to do is update just one line of code in your index.php
It is still a manual update. True that. You can also ofc. use something like glob() and search for you "mainlib.php" file (for ex.) and 'cache' that folders location to use it in the next calls?
This for example is how I do it:
<?php
/**
* cfg.php
*
* Main config file
*
* #package Public
*/
// Compatibility
$version = '5.2.3';//restricted by htmlentities()' 4th parameter
if(version_compare(PHP_VERSION, $version, '<')) {
die('Required PHP version is ' . $version . ', current is ' . PHP_VERSION);
}
// Environment
define('DEVELOPMENT', in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')));
define('PRIVATE_DIR', DEVELOPMENT ? 'private' . DIRECTORY_SEPARATOR : '..'.DIRECTORY_SEPARATOR.'private_html'.DIRECTORY_SEPARATOR.'tickets');
define('APPLICATION_LINK','application_red'.DIRECTORY_SEPARATOR);
define('LIBRARY_LINK','library'.DIRECTORY_SEPARATOR);
define("MEM_START",memory_get_usage(true));
// Behavior
if(DEVELOPMENT) {
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);//report all errors
}
else {
ini_set('display_errors', 'Off');
error_reporting(0);
}
// Timezone
date_default_timezone_set('Europe/Amsterdam');
// Constants
define('ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR);
define('APP', ROOT . '..'.DIRECTORY_SEPARATOR.PRIVATE_DIR.''.APPLICATION_LINK);
define('LIB', ROOT . '..'.DIRECTORY_SEPARATOR.PRIVATE_DIR.''.LIBRARY_LINK);
define('CACHE', APP.'cache'.DIRECTORY_SEPARATOR);
index.php/utest.php:
<?php
include("cfg.php");
// Start library
require_once LIB.'Library.php';
$library = new Library();
//etc.......
You don't need to make reference to a hardwired folder at all. In my current project I do this:
public static function getProjectRoot()
{
return realpath(
dirname( __FILE__ ) . DIRECTORY_SEPARATOR . '..' .
DIRECTORY_SEPARATOR . '..'
);
}
The class in which this features is two folder levels inside the project - hence the two .. operators to traverse up the directory structure. Since that location will never change in relation to the project root, this doesn't need changing, and I don't ever need to hardwire any paths.
Edit: in relation to include/require statements, use an autoloader, and (apart from a couple of bootstrap files) you don't generally need to use includes/requires at all.

Categories