Perhaps I'm going about this the wrong way, but I have a Configuration file that I'm trying to pass through a parameter, the reason I'm doing this is because I'm experimenting with what I call a ("Core"/"Client") structure, probably not the correct name, but basically whatever I edit on the "Core" is updated to all of the "Client" subdomains, which will respectively call code such as
include '/path/to/core/index.php';
generateIndex($Param, $Param);
So, Basically, here's what I have, on the "Clients" side I have a Configuration file, called "Configuration.php" this holds all of the static variables pertaining to the Clients database. Example below:
<?php
$SQL_HOST = "";
$SQL_DATBASE = "";
$SQL_ACCOUNT_TABLE = "";
$SQL_DATA_TABLE = "";
$SQL_REWARDS_TABLE = "";
$SQL_USERNAME = "";
$SQL_PASSWORD = "";
?>
So, Basically, I'm trying to do this,
generateIndex($SQLConnection, $Configuration);
However, It's not allowing me to do so and presenting me with this error.
Notice: Undefined variable: Configuration in /opt/lampp/htdocs/client/index.php on line 16
Respectively, Line 16 is the line above containing "generateIndex"
Now, on the "Core" side what I'm trying to do is the following to get data.
function generateIndex($SQLConnection, $SQLConfig) {
...
$SQLConfig->TBL_NAME
...
}
Which I don't know if it throws an error yet, because I can't pass $Configuation to the function.
Your can user return context for get variable from file.
As example:
File db_config.php:
<?php
return array(
'NAME' => 'foo_bar',
'USER' => 'qwerty',
'PASS' => '12345',
// Any parameters
);
You another file with include configuration:
<?php
// Code here...
$dbConfig = include 'db_config';
// Code here
If file have a return statement, then your can get this values with = operator and include file.
Read the file before putting it in the function.
generateIndex($SQLConnection, file("configuration.php"));
file 1:
function test() {
global $Configuration;
echo $Configuration
}
file 2 (perhaps config)
$Configuration = "Hi!";
Related
I have a function that does something (and it is included in my files php).
That function should require a php file passing parameters, but it fails and I'm not able to go ahead...
following the initial code of the function:
<?php
function write_pdf($orientation, $initrow, $rowsperpage)
{
ob_start();
require "./mypage.php?orient=$orientation&init=$initrow&nrrows=$rowsperpage";
$html = ob_get_clean();
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
...
...
the "mypage.php" returns the errors:
Notice:Undefined variable: orientation in
C:\wamp\www\htdocs\site\mypage.php on line 8
Notice:Undefined variable: initrow in
C:\wamp\www\htdocs\site\mypage.php on line 8
Notice:Undefined variable: rowsperpage in
C:\wamp\www\htdocs\site\mypage.php on line 8
is there a way to do something like that?
thanks!
You don't need to pass the parameters, as when you require the file is like its code where inside the function, so any variable defined in the function before the require, it will exists and be defined as well in your required file. So, you can directly use inside your required file the variables $orientation, $initrow, $rowsperpage.
Another way, quite ugly, is to add those vars to $_GET before require the file, assuming you're expecting to get them from $_GET:
$_GET['orient'] = $orientation;
$_GET['init'] = $initrow;
$_GET['nrrows'] = $rowsperpage;
require './mypage.php';
And my recommended way is to encapsulate your included file code in a function, so you can call it passing params. Even make a class, if included code is large and can be sliced in methods.
you can do so.
to_include.php
<?php
$orient = isset($_GET["orient"]) ? $_GET["orient"] : "portrait";
$init = isset($_GET["init"]) ? $_GET["init"] : 1;
echo "<pre>";
var_dump(
[
"orient"=>$orient,
"init"=>$init
]
);
echo "</pre>";
main.php
<?php
function include_get_params($file) {
$main = explode('?', $file);
$parts = explode('&', $main[1]);
foreach($parts as $part) {
parse_str($part, $output);
foreach ($output as $key => $value) {
$_GET[$key] = $value;
}
}
include($main[0]);
}
include_get_params("to_include.php?orient=landscape&init=100");
The method include_get_params, first separates the main part of the string, separates the file from the parameters, through the ?
After that he sets the parameters into pieces and puts all of this within the $_GET
In to_include, we retrieved the parameters from the $_GET
I hope I helped you.
I would like to create a multiple language website but I have a problem!
I will explain it to you with an example:
lang-en.php
<?php
$lang = [];
$lang['hello'] = "Wellcome $userName to our website!";
?>
index.php
<?php
$useName = "Amir";
require_once("lang-en.php");
echo $lang['hello'];
?>
Now, I would like to see this output in my page:
Welcome Amir to our website!
How can i do this?
It might be smart to make it a bit more complicated, to look to the future. If you remove the implementation part to a separate class, you can have your actual usage and the implementation of the translation separate. If you plan to use gettext (po/mo files) later, you can switch easier.
A simple, but untested, example would be
class translate{
private $translations = [
'hello' => "Wellcome %s to our website!",
]
public function trans($key, $value)
{
return sprintf($this->translations[$key], $value);
}
}
Mind you, this is a quick example, and probably needs some work -> for instance, it presumes always a single variable, etc etc. But the idea is that you create class with an internal implementation, and a function that you call. If you can keep the function call's footprint the same, you can change the working of your translation system!
You'll call this like so
$trans = new Translate();
echo $trans->trans('hello', 'Amir');
(again, I typed this in the answer box, no check for syntax, testing etc has been done, so this is probably not a copy-paste ready class, but it is about the idea)
edit: as requested, a bit more example. Again, not tested, probably some syntax errors etc, but to help you with the idea:
class translate{
private $translations = [
'hello' => array('test' =>"Welcome %s to our website!", 'vars' => 1),
'greet' => array('test' =>"I'd like to say $s to %s ", 'vars' => 2),
]
public function trans($key, array $values)
{
// no translation
if(!isset($this->translations[$key])){
return false; // or exception if you want
}
// translation needs more (or less) variables
if($this->translations[$key][vars] !== count($values)){
return false; // or exception if you want
}
// note: now using vsprintf
return vsprintf($this->translations[$key], $values);
}
}
Make a function one in lang-en.php
<?php
function lang($username)
{
$lang['hello'] = $username;
echo $lang['hello'];
}
?>
In index.php call that function
<?php
require_once("lang-en.php");
lang('arun');
?>
you nearly had it
langen.php
<?php
//declare array
$lang = array();
$templang['hello1'] = "Wellcome ";
$templang['hello2'] = " to our website!";
//add new item in array
array_push($lang,$templang);
?>
index.php
<?php
$useName = "Amir";
require_once("langen.php");
//it is first entry of array row so [0] is 0
echo $lang[0]['hello1'];
echo $userName;
echo $lang[0]['hello2'];
//out is welcome amir to our website
?>
this is a easy way too see how to pass variables a little long way but i didn't want to combine so that you can see how it works you can also do some reading about sessions for passing variables between pages that is not included
Amir Agha,
When you call another .php file by include or require php acts as if the contents of the included file is inserted in the same line and the same scope (except for classes and functions) so your code in the view of php interpreter looks like this:
<?php
$userName = "Amir";
$lang = [];
$lang['hello'] = "Wellcome $userName to our website!";
echo $lang['hello'];
?>
So this code must display:
Wellcome Amir to our website!
But why it doesn't work? Simply because you wrote $useName instead of $userName in your index.php file.
p.s.: Other answers made it very complicated. only change $useName to $userName
I want to access a method from an external class, within another file.
I have an external class, let's say:
external/file.php
class ExternalClass {
private $myClient;
const CONSTANT = 'some/path';
public function _constructor($myClient) {
$this->myClient = $myClient;
}
public function getSome($information) { // Need to access this function
$data = new StdObject();
$data->information = $information;
$result = $this->myClient->post(
self::CONSTANT,
$data
);
return($result['code'] == 200 ? json_decode($result['body']) : false);
}
public static function instance($SETTINGS) {
return new ExternalClass(new MyClient($SETTINGS['externalclass']['host']));
}
}
... I would like to reference this class in another file.
internal/file.php
include_once('external/file.php');
$externalClassInstance = ExternalClass::instance($SETTINGS); // line 3
$externalClass = new ExternalClass(); // line 4
$externalClassGetSome = $externalClass->getSome($information); // line 5
The problem is, I'm not sure if I'm correctly referencing the external methods inside the internal file.
Is "Line 3" even necessary?
Also, the addition of Line 5 code breaks any code after it.
Firstly I don't know why you would need line 3.
Secondly you seem to have the answer right there
include_once('external/file.php');
$externalClass = new ExternalClass(); // line 4
$externalClassGetSome = $externalClass->getSome($information);
try to change from
include_once('external/file.php');
to
include_once('../external/file.php');
becauase its in external directory and your file is in internal directory.
I have a php file that contains an array.
//config.php
return [
'name' => 'XXXX',
'phone' => '000',
'email' => 'YYYY',
...
];
now i want to override config.php file and change email values to ZZZZ from another php file like index.php
If XXXX is going to be a placeholder, you could do:
$file_contents = file_get_contents("path/to/file");
$new_file_contents = str_replace("XXXX","ZZZZ", $file_contents);
file_put_contents("path/to/file", $new_file_contents);
PHP files are not supposed to be changed on-the-fly like this. It is technically possible, but that does not mean you should do it.
A decent solution that does not go around changing your code nilly-willy would be to create another file that modifies the configuration file and then returns it again:
// config-filtered.php
$config = include 'config.php';
$config['email'] = 'ZZZZ'; // Or = $_SESSION['user_email']; for example
return $config;
// index.php
$config = include 'config-filtered.php';
echo "Hello {$config['name']}, your email is {$config['email']}";
I have this index.php file
# Loading configurations.
loadConfiguration('database');
loadConfiguration('site');
# Initializing the database connection.
$db = new database($c['db']['host'], $c['db']['username'], $c['db']['password'], $c['db']['name']);
unset($c['db']['password']);
And loadConfiguration() is set as follow:
function loadConfiguration($string) { require(path.'config/'.$string.'.con.php'); }
I checked that database.con.php and site.con.php are into the config/ folder.
And the only error i get is a Notice: Undefined variable: c in the following line
$db = new database($c['db']['host'], $c['db']['username'], $c['db']['password'], $c['db']['name']);
Here's the database.con.php
# Ignore.
if (!defined('APP_ON')) { die('Feel the rain...'); }
$c['db']['host'] = 'localhost';
$c['db']['username'] = 'root';
$c['db']['password'] = '';
$c['db']['name'] = 'name';
Here's the site.con.php
# Ignore.
if (!defined('APP_ON')) { die('Feel the rain...'); }
/* Site informations */
$c['site']['name'] = 'Namek';
$c['site']['mail'] = 'mail#whocares.com';
$c['site']['enable-email'] = false;
$c['site']['debug-mode'] = true;
What am i doing wrong?
The required code is executed within the function, so $c is a local variable and not accessible in global scope.
You may either use some fancy design pattern to make $c global (e.g. use a Registry (R::$c, R::get('c'), an Environment ($this->env->c), ...) or you could change your configuration loader function to return the name of the file and require outside of it:
require_once configFile('database');
function configFile($name) {
return path . 'config/' . $name . '.con.php';
}
Please don't use global variable according security purpose. you can set your variable in registry variable and then access it.