I want to keep my paypal script in a different directory than my application directory. With that said here is my problem. When I use a path with the include statement, it doesnt find the page. I am calling the include file from "mysite.com/cart/pp_express/processed.php"
This doesnt work
include (__DIR__ . "/mywebite.com/cart/cart.php");
This does not work
$file = "mysite.com/cart/cart.php";
include($file);
This workes
$file = "cart.php";
include($file);
So then I created a function with the include statement to send only the file name in a variable. This works.
$deleted_flag = "no";
$file = "cart.php";
function includeFile($file, $deleted_flag) {
include($file);
}
includeFile($file, $deleted_flag);
Then I created a function with the include statement to send the entire path in a variable. It doesnt work. The following is the one I need to have working
$deleted_flag = "no";
$file = "mysite.com/cart/cart.php";
function includeFile1($file, $deleted_flag) {
include($file);
}
includeFile1($file, $deleted_flag);
__DIR__ points to the folder in which the file calling __DIR__ is located.
Let's say you have the following structure:
/var/www/html/index.php
/classes/class.php
/cart/cart.php
In index.php, __DIR__ will be /var/www/html. In class.php, __DIR__ will be /var/www/html/classes.
So, to include cart.php from index.php, you'd need to write:
include(__DIR__ . '/cart/cart.php');
To include cart.php from class.php, you'd need to write:
include(__DIR__ . '/../cart/cart.php');
Related
When I use require_once or include_once to include a file it does not work, while when I use require or include it works fine.
public function ParseURL() {
require_once (APP_PATH . "config/config.php");
$this->url_as_parts = explode('/', $this->url);
$class = isset($this->url_as_parts[0]) ? $this->url_as_parts[0] : $config['default_controller'];
$method = isset($this->url_as_parts[1]) ? $this->url_as_parts[1] : "index";
$parms = isset($this->url_as_parts[2]) ? $this->url_as_parts[2] : "";
if (!class_exists($class)) {
trigger_error("The class {$class} not exists <br/>");
exit;
}
$controller = Object::get($class);
if (!method_exists($controller, $method)) {
header('HTTP/1.0 404 Not Found');
include(SYSTEM_PATH . "languages/" . $config['system_language'] . "/errors/404_not_found.html");
exit;
}
if (empty($parms)) {
$controller->{$method}();
} else {
$parms_array = array_slice($this->url_as_parts, 2);
call_user_func_array(array($controller, $method), $parms_array);
}
}
The following line does not produce an error and the path is correct
require_once (APP_PATH . "config/config.php"); but I cant access $config['system_language'] which is inside the file config.php.
Note that when I change the require_once to require or include, everything is OK.
As comes from require_once description - file required only once
Any other require_once of this file will not work.
And you obviously run you function ParseURL more than once. So, your require_once not working on second and consecutive calls.
So, you can use just require or, as I see this is part of a class, create, for example, a wrapper method which will assign config data to your class variable. I.e:
public function getConfig()
{
$this->config = require_once('FILE');
}
In this case your config file should return array or object of config variables.
Can it be that something else includes config/config.php, and then redefines/overwrites the variable $config?
The difference between require_once() and is regular counterparts (include() etc) is that require_once() only includes (and executes, if applicable) something if it hasn't been included before.
This might be because you are already loading config/config.php somewhere before in your code.
Calling require_once(APP_PATH . "config/config.php"); checks that the file config.php already is included and hence does not include it inside that function.
That is the reason your function does not have access to $config variable.
Hope that helps.
Can I set it as a global variable like:
<?php
$GLOBALS['dbconnect'] = require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR.'/location/file.php');
$short = $GLOBALS['dbconnect'];
function someFunction() {
echo $short;
}
?>
I am using a database connection file twice, once outside of a function, and once inside a function. The query inside the function can't run because the credentials, servername, db, etc.. are not defined.
I'm not sure how this works?
When I place the require_once file inside the brackets, nothing happens, page is white.
This is the first example from link
<?php
function __autoload($class_name) {
include $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
If you don't want to use an auto loader for whatever reason you can do the following. Have a file called config.php at the root of your project and have it contain this code.
<?php
// Replaced the \ which appear on localhost to / so it works online.
define("BASE_DIR", str_replace("\\", "/", __DIR__));
$files = [
BASE_DIR . "/path/to/my/file.php"
];
function loadFiles()
{
foreach ($files as $file) {
require_once $file;
}
}
?>
Then in your other files include the config file and call loadFiles. This is essentially an autoloader but sometimes it can be hard to grasp so you can use this.
I keep getting:
failed to open Stream: No such file or directory " Path " on line 2
When I try to run this php file from the command line.
require_once 'modules/Reports/ScheduledReports.php'
VTScheduledReport::runScheduledReports($adb);
I have checked to see if the file is there and there is a class called class VTScheduledReport in ScheduledReports.php and the function runScheduledReports. Is there. The function looks like this:
public static function runScheduledReports($adb) {
require_once 'modules/com_vtiger_workflow/VTWorkflowUtils.php';
$util = new VTWorkflowUtils();
$adminUser = $util->adminUser();
global $currentModule, $current_language;
if(empty($currentModule)) $currentModule = 'Reports';
if(empty($current_language)) $current_language = 'en_us';
$scheduledReports = self::getScheduledReports($adb, $adminUser);
foreach($scheduledReports as $scheduledReport) {
$scheduledReport->sendEmail();
$scheduledReport->updateNextTriggerTime();
}
$util->revertUser();
}
Anyone have any idea why this won't run?
change
require_once 'modules/com_vtiger_workflow/VTWorkflowUtils.php';
to
require_once (dirname(__FILE__) . '/modules/com_vtiger_workflow/VTWorkflowUtils.php');
if your include file path is relative to the script. dirname(__FILE__) return the full path of the file from where it is called.
for the ScheduledReports.php you can use the following
require_once (dirname(__FILE__) . '/modules/Reports/ScheduledReports.php');
Sometime I have to use include_once and include it depend how the page are accessed. For example:
sales.php
include("class/pdoDatabase.php");
include("class/ClassExample.php");
$obj = new ClassExample();
$obj->getNewItem(1);
ClassExample.php
include_once("class/pdoDatabase.php");
class ClassExample {
public function getNewItem($id) { .. }
public function addNew($id) { .. }
}
// Accessing this file directly via Ajax request
if (isset($_POST['AddNew'])) {
$obj = new ClassExample ();
$obj->addNew($_POST['id']);
}
}
If you access to sales.php which will then load include("class/ClassExample.php");, however I have to use include_once in the ClassExample.php because pdoDatabase.php might be already loaded in sales.php.
If you access the file directly to ClassExample.php with POST query, it mean it will have to load the file and create an object.
Problem:
Problem is when you access to ClassExample.php directly - it could not find class/pdoDatabase.php . It work fine when sales.php load class/pdoDatabase.php file
This is not a problem with include_once and include difference. This is a problem with relative paths. Include always uses paths relative to called php file. You have this file structure:
sales.php
[class]
- pdoDatabase.php
- ClassExample.php
when you call sales.php everything is ok, but when you call ClassExample.php it's trying to find class/class/pdoDatabase.php which don't exist.
Change include line in your ClassExample.php
include_once(dirname(__FILE__)."/pdoDatabase.php");
and use the same pattern everywhere.
You are doing it wrong.
Instead of manually loading each class file, you should be using autoloader, that you initialize in bootstrap stage of your application. Something along the lines of:
$root = __DIR__;
spl_autoload_register(function( $className ) use ( $root ){
$className = str_replace( '\\', '/', $className );
$filepath = $root . '/' . strtolower( $className ) . '.php';
if ( !file_exists($filepath) )
{
return false;
}
require $filepath;
return true;
});
To learn more about this, please read about spl_autoload_register() in the manual.
I want to get the name of the file that includes another file from inside the included file.
I know there is the __FILE__ magic constant, but that doesn't help, since it returns the name of the included file, not the including one.
Is there any way to do this? Or is it impossible due to the way PHP is interpreted?
So this question is pretty old, but I was looking for the answer and after leaving here unsatisfied, I came across $_SERVER['SCRIPT_FILENAME']; Of course this works if the php file doing the including is a web page.
This gives you the full path of the "including file" on the server. eg /var/www/index.php. so if you want just the filename, eg index.php, you will need to use basename() eg
basename($_SERVER['SCRIPT_FILENAME']);
So, if in your index.php you have the following line:
<?php include("./somephp.php"); ?>
and in somephp.php you have
echo "this is the file that included me: " . basename($_SERVER['SCRIPT_FILENAME']);
you will get
this is the file that included me: index.php
output to the browser. This also works if the user is accessing your file without explicitly including the filename in the url, eg www.example.com instead of www.example.com/index.php.
Solution
Knowing that the functions used to include files are include, include_once, require and require_once, also knowing that they are reserved words in PHP, meaning that it will not be possible to declare user functions with the same name, and based on wedgwood's idea of using debug_backtrace you can actually work out from what file the include was called.
What we are going to do is iterate over the backtrace untill we find the most recent call to any of the four include functions, and the the file where it was called. The following code demostrate the technique:
function GetIncludingFile()
{
$file = false;
$backtrace = debug_backtrace();
$include_functions = array('include', 'include_once', 'require', 'require_once');
for ($index = 0; $index < count($backtrace); $index++)
{
$function = $backtrace[$index]['function'];
if (in_array($function, $include_functions))
{
$file = $backtrace[$index]['file'];
break;
}
}
return $file;
}
The above code will return the absolute path of the file where the last include happened, if there hasn't been any include it will return false. Note that the file may has been include from a file that was included from another file, the above function only works for the deepest include.
With a simple modification, you can also get the last included file:
function GetIncludedFile()
{
$file = false;
$backtrace = debug_backtrace();
$include_functions = array('include', 'include_once', 'require', 'require_once');
for ($index = 0; $index < count($backtrace); $index++)
{
$function = $backtrace[$index]['function'];
if (in_array($function, $include_functions))
{
$file = $backtrace[$index - 1]['file'];
break;
}
}
return $file;
}
Observations
Note that __FILE__ is not the included file, but the current file. For example:
file A.php:
<?php
function callme()
{
echo __FILE__;
}
?>
file B.php:
<?php
include('A.php');
callme();
?>
file index.php:
<?php
include('B.php');
?>
In the above example, in the context of the file B.php the included file is B.php (and the including file is index.php) but the output of the function callme is the path of A.php because __FILE__ is in A.php.
Also note that $_SERVER['SCRIPT_FILENAME'] will give the the absolute path to the script requested by the client. If $_SERVER['SCRIPT_FILENAME'] == __FILE__ it means that the current file is the requested one, and therefore there probably hasn't been any includes...
The above method checks if the current file is the requested one, but not if it hasn't been included (below is an example of how the requested file can be included). An actual solution to check if there has not been any inclusions could be to check count(get_included_files()) == 1.
The requested file can be an included file in the following way:
file x.php
<?php
$var = 'something';
include('index.php');
?>
file index.php
<?php
if (!isset($var))
{
include('x.php');
exit;
}
echo 'something';
?>
In the above example, the file index.php will include x.php, then x.php will include index.php back, afterwards index.php outputs "something" and returns control to x.php, x.php returns control to index.php and it reaches exit;
This shows that even if index.php was the requested script, it was also included from another script.
I can't find the easy way to cover this.
But If the including one is really important to you, you could hack it with some global variable and your own include function.
e.g.
<?php
$g_including_files = array();
function my_include($file) {
$bt = debug_backtrace();
global $g_including_files;
$g_including_files[basename($file)] = $bt[0]['file'];
return include($file);
}
May that be helpful for you :)
This is actually just a special case of what PHP templating engines do. Consider having this function:
function ScopedInclude($file, $params = array())
{
extract($params);
include $file;
}
Then A.php can include C.php like this:
<?php
// A.php
ScopedInclude('C.php', array('includerFile' => __FILE__));
Additionally, B.php can include C.php the same way without trouble.
<?php
// B.php
ScopedInclude('C.php', array('includerFile' => __FILE__));
C.php can know its includer by looking in the $params array.
<?php
// C.php
echo $includerFile;