Is it possible to include a file using a function in PHP? I've already tried something but the file is not included in the script.
I'm using this function :
function run($entry_point){
if(!empty($entry_point)){
if(file_exists('assets/controllers/'.$entry_point.'.php'))
include 'assets/controllers/'.$entry_point.'.php';
else
include 'assets/controllers/home.php';
}
}
My problem its that with this kind of function the index won't include the $entry_point file.
Index.php code:
session_start();
run($_GET['location']);
Thanks!
First of all: your function works for me. Make sure that the names of the folders are correct and turn on error reporting (error_reporting(E_ALL); ini_set("display_errors", 1);).
There are different ways to include files dynamically into your script.
Common frameworks use stuff like (a bit modified for your case):
function includeScript($path = 'assets/controllers/',$file = 'home'){
require $path . $file . '.php';
}
If you're including classes, consider using an autoloader:
function my_autoloader($class) {
include 'assets/controllers/' . $class . '.php';
}
spl_autoload_register('my_autoloader');
What this would do is, that whenever you want to use a class that is not defined, it would automatically look for a file named like the class in the assets/controllers/ folder. E.g:
// the autoloader would look for assets/controllers/Class1.php
$obj = new Class1();
Autoloader will be the ideal candidate for this. However, your function looks fine to me.
Can you make following amendments to the script ?
Turn on error reporting and also display the errors. Refer to Mark's answer for details.
Add __ DIR __ constant before 'assets. So the line will become :
if(file_exists(__ DIR __.'/assets/controllers/'.$entry_point.'.php'))
include __ DIR __.'/assets/controllers/'.$entry_point.'.php';
else
include __ DIR __.'/assets/controllers/home.php';
P.S. : Please use braces for conditional logic. It makes code more readable.
Related
I got a problem with php and OOP.
I tried to create a object and inside the object I tried to load data from mysql.
My files are build like this.
HTML
|_ php
|__ objects
|_ content
In object folder is the object file "Event". The object created in a script in php folder and the whole script is called from a html file in content.
My Problem is, that i use the object from different locations. And the include_once method wont work.
event.php:
<?php
include_once(ROOT.'php/db.inc.php');
class Pb1_event
{
public $ev1_id;
// do something
}
I also tried it with include_once('./../db.inc.php');.
How should I include it ? Is it a good way to include it in this file or should I include it anywhere else ?
Firstly what I would do is use either __DIR__, or better is $_SERVER['DOCUMENT_ROOT'] for absolute pathing. These are constants that will refer to your server web root. Assuming it refers to the root directory you have given to us, you would do:
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/db.inc.php';
But to gain a better understanding, you should echo it and see how your directory paths. Also, for the "best practices" you should use autoloading, you can read more about it here:
http://php.net/manual/en/language.oop5.autoload.php
Define an autoload function and have it call the file you need, for example, if you need a class called DB your function might look something like this:
function __autoload($class) {
if ($class == 'DB') {
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/db.inc.php';
}
}
Use __FILE__ or __DIR__ magic constants:
include_once(dirname(__FILE__) . '/../db.inc.php');
include_once(__DIR__ . '/../db.inc.php');
My suggestion would be to register an autoloader in the beginning of your scripts using spl_autoload_register():
spl_autoload_register(function ($className) {
include 'path/to/php/objects/' . $className . '.php';
});
When you want to instantiate an object, where ever you are, you just need to do:
$myclass = new MyClass();
The autoloader will load the correct class. All you need to think about is to call the files in "objects" the same as your classes. Example:
class Pb1_event {
}
filename: path/to/php/objects/Pb1_event.php
you can try this for your warning:
include_once($_SERVER["DOCUMENT_ROOT"].'/php/db.inc.php');
I have built a PHP video upload library aimed to be used in different frameworks .
## HERE ##.
But i want to make it optimized like , i dodnt want to include or make\
require or require_once call in class and also i want the configuration class to be available to all class i have at run time ... without explicitly calling or making require once.
How can i do that , most php project use bootstrap class /file to do that , and some body pls help me.
I would suggest to make a way to have an auto_load.php file and this file would contain the files required to include, and then you can include this auto_load.php into the entry point file / class to your library to load all the necessary files for your library to work. It is the same idea as how composer work and it is efficient.
You can take a look into psr-4 standards in loading classes.
http://www.php-fig.org/psr/psr-1/
require_once is the same as require except PHP will check if the file has already been included, and if so, not include (require) it again, refer to http://php.net/manual/en/function.require-once.php
You can create an autoload function . This way you will only load the required library.
A basic autoload function looks like this:
define('PATH_LIBRARY', '/some/path/lib/');
function myautoload($class_name){
// you can do string manipulation to build the filename, for example
$filename = strtolower($class_name);
$filename = str_replace('_', '/', $filename);
$filename = ucwords($filename);
$filepath = PATH_LIBRARY.$filename.'.php';
if (file_exists($filepath))
{
require_once($path);
return true;
}
}
spl_autoload_register('myautoload');
Edit that code has to be added at the beginning of your code (usually in a file included at the top of your index.php ), so all instruction after will benefit of it. You can improve it by checking different directory (for example if the class name starts with "controller", or "model", change the path to the appropriate directory)
Let's say I've got two files class.php and page.php
class.php
<?php
class IUarts {
function __construct() {
$this->data = get_data('mydata');
}
}
?>
That's a very rudamentary example, but let's say I want to use:
$vars = new IUarts();
print($vars->data);
in my page.php file; how do I go about doing that? If I do include(LIB.'/class.php'); it yells at me and gives me Fatal error: Cannot redeclare class IUarts in /dir/class.php on line 4
You can use include/include_once or require/require_once
require_once('class.php');
Alternatively, use autoloading
by adding to page.php
<?php
function my_autoloader($class) {
include 'classes/' . $class . '.class.php';
}
spl_autoload_register('my_autoloader');
$vars = new IUarts();
print($vars->data);
?>
It also works adding that __autoload function in a lib that you include on every file like utils.php.
There is also this post that has a nice and different approach.
Efficient PHP auto-loading and naming strategies
In this case, it appears that you've already included the file somewhere. But for class files, you should really "include" them using require_once to avoid that sort of thing; it won't include the file if it already has been. (And you should usually use require[_once], not include[_once], the difference being that require will cause a fatal error if the file doesn't exist, instead of just issuing a warning.)
Use include_once instead.
This error means that you have already included this file.
include_once(LIB.'/class.php');
use
require_once(__DIR__.'/_path/_of/_filename.php');
This will also help in importing files in from different folders.
Try extends method to inherit the classes in that file and reuse the functions
Use include("class.classname.php");
And class should use <?php //code ?> not <? //code ?>
I have a user authentication system that I am currently writing. Problem is, I don't want to have to include class x,y,z,etc for every page that I want to use that class for. For example, here is the index page:
///////// I would like to not have to include all these files everytime////////
include_once '../privateFiles/includes/config/config.php';
include_once CLASSES.'\GeneratePage.php';
include_once DB.'\Db.php';
include_once HELPERS.'\HelperLibraryUser.php'; //calls on user class
//////////////////////////////////////////////////////////////////////////////
$html = new GeneratePage();
$helper = new HelperLibraryUser("username","password","email");
$html->addHeader('Home Page','');
$html->addBody('homePage',
'<p>This is the main body of the page</p>'.
$helper->getUserEmail().'<br/>'.
$helper->doesUserExists());
$html->addFooter("Copyright goes here");
echo $html->getPage();
As you can see, there are a few files that I need to include on every page, and the more classes I add, the more files I will have to include. How do I avoid this?
You can define an autoload function, e.g.:
function __autoload($f) { require_once "/pathtoclassdirectory/$f.php"; }
This way, when php encounters a reference to a class it doesn't know about, it automatically looks for a file with the same name as that class and loads it.
You could obviously add some logic here if you need to put different classes in different directories...
Make a file called common.php and put these include statements as well as any other functions/code that you need in every file (such as database connection code, etc) in this file. Then at the top of each file simply do this:
<?
require_once('common.php');
This will include all your files without having to include them seperately.
It is highly recommended not to use the __autoload() function any more as this feature has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged.. Now the spl_autoload_register() function is what you should consider.
<?php
function my_autoloader($class) {
include 'classes/' . $class . '.class.php';
}
spl_autoload_register('my_autoloader');
// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.class.php';
});
?>
I am trying to convert several php scripts to use the __autoload function. Right now I can use the include and require functions like this:
require_once('path/to/script.php');
But inside of the __autoload function, I can't use the line above. I have to use this:
require_once('absolute/path/to/script.php');
Why does it seem as though the __autoload function doesn't use the include path I have specified in php.ini?
Don't use __autoload... It has a few drawbacks (including limiting yourself to one per execution). Use instead spl_autoload_register if you're on 5.2+.
So what I typically do, is have a class:
class AutoLoader {
protected static $paths = array(
PATH_TO_LIBRARIES,
);
public static function addPath($path) {
$path = realpath($path);
if ($path) {
self::$paths[] = $path;
}
}
public static function load($class) {
$classPath = $class; // Do whatever logic here
foreach (self::$paths as $path) {
if (is_file($path . $classPath)) {
require_once $path . $classPath;
return;
}
}
}
}
spl_autoload_register(array('AutoLoader', 'load'));
That way, if you add a library set, you can just "add it" to your paths by calling AutoLoader::AddPath($path);. This makes testing with your autoloader a LOT easier (IMHO).
One other note. Don't throw exceptions from the autoload class unless absolutely necessary. The reason is that you can install multiple autoloaders, so if you don't know how to load the file, another one may exist to load it. But if you throw an exception, it'll skip the other one...
Personally, I don't ever like to use relative paths with includes. Especially with multiple include directories (like pear), it makes it very difficult to know exactly which file is being imported when you see require 'foo/bar.php';. I prefer to define the absolute path in the beginning of the file set define('PATH_ROOT', dirname(__FILE__));, and then define all my other useful paths off of that directory (PATH_LIBRARIES, PATH_TEMPLATES, etc...). That way, everything is absolutely defined... And no need to deal with relative paths (like the issue you're having now)...
I suspect your __autoload() function is in a separate file then the code which calls it. The path to the included files will be relative to the file which the __autoload() function declaration resides.
It seems like . is not in your include path. So add it use:
set_include_path('.' . PATH_SEPARATOR . get_include_path());
Now PHP should look relative to the executed scripts directory, too. (Executed script here is something like index.php, not autoload.php.
But why don't use simply use a normal relative path like ./path/to/class.php?
Not sure without seeing the whole set-up. My autoload function is within my global functions file, and looks like this:
function __autoload($class) {
if (file_exists("includes/{$class}.php")) {
require_once("includes/{$class}.php");
}
/**
* Add any additional directories to search in within an else if statement here
*/
else {
// handle error gracefully
}
}
I use a relative path because the script is included in my index.php file and all HTTP requests are passed through it.