PHP access variable from included file - php

have a file like so:
<?php
require_once "properties.php";
$GLOBALS["to_home"] = "../sfair";
echo tohome () . "index.php";
?>
And properties.php:
<?php
function tohome()
{
if(isset($GLOBALS['to_home']))
{
return $GLOBALS['to_home'] . "/";
}
else
{
return "';
}
}
Which should give me ../stair/index.php.
But instead gives me index.php.
How can I make the included file be able to access the variables of the including files?
note: I found another answer ("unable to access global variable from included file" but it did not work.

Can't you send the $GLOBALS["to_home"] with the Function call? That's what functions are for...
echo tohome($GLOBALS["to_home"]) . "index.php";
Of course you will have to change the function contents, but I guess you will get the idea.

Related

Get directory of the file which included another file in PHP

I got two files:
get_path.php:
function get_path() {
echo basename(__FILE__);
}
main.php
require("get_path.php");
get_path();
// This echos out "get_path.php", however i want it to echo out main.php
Does somebody know how to achieve this?
Thank you very much in advance!
Assuming that your function is as stated in the get_path.php file you can rewrite your function like this:
function get_path() {
$included_files = get_included_files();
foreach($included_files as $k=>$value){
if($value===__FILE__) return basename($included_files[$k-1]);
}
}
I use return but you can use echo and just after break; this return the file which directly include get_path.php but if you want the first level path.I mean the first file which include all the other files you can use :
function getFirstLevelPath(){
$included_files = get_included_files();
return basename($included_files[0]);
}
the output of your main will be now
:
main.php

'require' work but 'require_once' doesn't work

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.

require_once the same file multiple time?

I have a config file that contain credential information to connect to an API
I include my config file in 2 functions in 2 different file
In the first called function, I have my credential variables but when I call my second function, my credential variables are empty.
index.php
<?php
require_once("./connector/hot/hotelbeds/book.php");
if($_REQUEST['connector'] == 'hotelbeds')
{
require_once("connector/hot/hotelbeds/validate.php");
validate_hotelbeds($_REQUEST);
}
$booking_output = book_hotelbeds($_REQUEST);
?>
validate.php
<?php
function validate_hotelbeds($results)
{
$account = $results['header']['account'];
include_once("./connector/hot/hotelbeds/account_config/$account/config.php");
// $url contain my url
$validate = curl_get($url , $results);
}
?>
book.php
<?php
function book_hotelbeds($results)
{
$account = $results['header']['account'];
include_once("./connector/hot/hotelbeds/account_config/$account/config.php");
// $url is empty
$book = curl_get($url , $results);
}
?>
config.php
<?php
$url = "http://www.websitelink.com";
?>
The first time you require it, the variables will be introduced.
When you require it again from inside a function, the file has already been required so it is ignored.
The variables are outside the scope of the function at this point, so if you have to you would need to access them by declaring them as global.
Perhaps a better idea would be do declare those variables as constants instead, which means they will be available within the function scopes:
$myVariable = 'hello';
define('MY_CONSTANT', 'world');
echo 'Global scope: ', $myVariable, MY_CONSTANT, PHP_EOL; // helloworld
function myFunction()
{
echo 'Function scope: ', $myVariable, MY_CONSTANT, PHP_EOL; // world
}
function myGlobalFunction()
{
global $myVariable;
echo 'Function scope using global: ', $myVariable, MY_CONSTANT, PHP_EOL; // helloworld
}
Example.
Put your include_once("./connector/hot/hotelbeds/account_config/$account/config.php"); into index instead. Then if you wanted to use the var $url you would need a line above stating that you want that global var: global $url;.
Also I suggest changing $url name and change it to constant like: const API_URL = 'website_url'
Functions require_once and include_once include file only on time for one call of script. Because you include files book.php and validate.php in index.php then PHP include config.php only one time.
You can include config.php in index.php and use global directive inside your function.
Or you can just use functions include and require. These functions include one file to script many times - on each call.

Include PHP file with parameter

newbie in PHP here, sorry for troubling you.
I want to ask something, if I want to include a php page, can I use parameter to define the page which I'll be calling?
Let's say I have to include a title part in my template page. Every page has different title which will be represented as an image. So,
is it possible for me to call something <?php #include('title.php',<image title>); ?> inside my template.php?
so the include will return title page with specific image to represent the title.
thank you guys.
An included page will see all the variables for the current scope.
$title = 'image title';
include('title.php');
Then in your title.php file that variable is there.
echo '<h1>'.$title.'</h1>';
It's recommended to check if the variable isset() before using it. Like this.
if(isset($title))
{
echo '<h1>'.$title.'</h1>';
}
else
{
// handle an error
}
EDIT:
Alternatively, if you want to use a function call approach. It's best to make the function specific to activity being performed by the included file.
function do_title($title)
{
include('title.php'); // note: $title will be a local variable
}
Not sure if this is what you're looking for, but you can create a function to include the file and pass a variable.
function includeFile($file, $param) {
echo $param;
include_once($file);
}
includeFile('title.php', "title");
In your included file, you could do this:
<?php
return function($title) {
do_title_things($title);
do_other_things();
};
function do_title_things($title) {
// ...
}
function do_other_things() {
// ...
}
Then, you could pass the parameter as such:
$callback = include('myfile.php');
$callback('new title');
Another more commonly used pattern is to make a new scope for variables to be passed in:
function include_with_vars($file, $params) {
extract($params);
include($file);
}
include_with_vars('myfile.php', array(
'title' => 'my title'
));
The included page will already have access to those variables defined prior to the include. If you require include specific variables, I suggest defining those variables on the page to be included

Undefined variable error on a variable inside an included file

I'm including this file to collect one of its variables. File path is correct and i don't get file include errors. But when i try to print a variable inside that file it gives undefined variable error. Following is the code.
include_once($path . "folder/file.php");
echo($code);
There is a php class. inside the class there is a login function . Within that function I'm including another file assume it's funtions.php.
functions.php has above code in it.
Inside functions.php file i include this file which contains the variable i'm looking for (assume it's test.php).
test.php looks like this (inside php tags)
$code="something";
$another_variable="something else";
so now like i said before when i include this inside functions.php and print $code it why does it gives an undefined error?
Full code
function log($user, $pass) {
global $config;
$this->get_available_accounts();
if (isset($this->Users_obj[$user])) {
if ($this->Users_obj[$user]->userName == $user && $this->Users_obj[$user]->passWord == $pass) {
delete_cache_full();
$_SESSION['username'] = $user;
$_SESSION['log'] = true;
$_SESSION['usergroup']=$this->Users_obj[$user]->level;
$this->set_permission_session($_SESSION['usergroup']);
include_once $config->path . 'config.php';
$newUpdate2=showUpdates2();
if(!empty($newUpdate2)){
$_SESSION['updateremindlater']=$newUpdate2['date'];
}
//file
include_once $config->path . 'functions.php';
$func = new UserFuncs();
$func->validate();
include_once $config->path . 'view/ViewDashboard.php';
return true;
}
}
thats the function im including this file into. include_once $config->$path . 'functions.php'; includes functions.php file
functions.php looks like this
include_once($path. "folder/config.php");
echo($code);
and config.php looks like
$code = "ERGERW2342HV3453WERWEER";
$host_name = "SERV345WERFDGDDFGDGF";
$return_code = "DFGDFSDGFS";
$vurl = "YUIYUJHGJ";
$next_val ="AWERFDFVDV";
$val_exp = "NMGHJGJGH";
Help much appreciated!
Just guessing that you've included config.php somewhere else before, and that it's not being included again due to include_once. Therefore the variables are not created in the scope you're including it in the second time.
This could be a problem with variable scope, where you are trying t access the variable from somewhere (e.g. a function) where it is not available to that particular object (you did mention that you included the file within a class).
I agree with deceze and hakre, it's very hard to answer this question without seeing your code.

Categories