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.
Related
I'm currently doing a beginner course in coding, mainly focusing on PHP and in one exercise we're changing our code from including a template through normal namespacing to instead including it via a function so that we can use output buffering. To make it work we are using extract() and although I understand how extract works, I struggle to see why we need to use it to make include work. Before running it via the function, we didn't need to send in or extract new variables. Is someone able to explain the reasons behind this?
Here's what the function looks like:
const TEMPLATE_EXTENSION = '.phtml';
const TEMPLATE_FOLDER = 'templates/';
const TEMPLATE_PREFIX = 'cart_view_';
function display($template, $variables, $extension = TEMPLATE_EXTENSION) {
extract($variables);
ob_start();
include TEMPLATE_FOLDER . TEMPLATE_PREFIX . $template . $extension;
return ob_get_clean();
}
Here's how we call it:
<?php echo display('user', ['users' => $users, 'cart' => $cart]); ?>
<?php echo display('item', ['new_item' => $new_item]); ?>
<?php echo display('items', ['cart' => $cart]); ?>
And here's what's in the templates we're including:
<h2>New Item</h2>
<p><?php printf($new_item['name']);?> is $<?php printf($new_item['price']);?></p>
<h2>User: <?php printf($cart['user']); ?></h2>
<p>ID: <?php printf($users[$cart['user']]['id']); ?></p>
<p>Email: <?php printf($users[$cart['user']]['email']); ?></p>
<h2>Cart</h2>
<?php foreach ($cart['items'] as $item) {
printf("<p>%s is $%d</p>\n", $item['name'], $item['price']);
} ?>
The variables are definied in another file which is already included in the index.
Previously before using the function to buffer, all we needed was this:
<?php include 'templates/cart_view_user.phtml'; ?>
<?php include 'templates/cart_view_item.phtml'; ?>
<?php include 'templates/cart_view_items.phtml'; ?>
Functions do have their own variable scope. So when you created the display() function, it doesn't see what variables are available outside of it. See more on Variable Scopes in PHP. You are using extract() in order to convert an array into variables in the scope where you are calling it from eg: in the function.
Your first solution was probably something like this (I'm making up the variables):
$users = [];
$cart = [];
// you are including the template in the same scope as the variables are defined, aka it will "see"/have access to those variables
include 'templates/cart_view_user.phtml';
Now you have refactored your code and moved the including logic in a function. This function has its own local scope.
$users = [];
$cart = [];
function display($template, $variables, $extension = TEMPLATE_EXTENSION) {
// you don't have access to $users and $cart here as those are defined in the global scope
extract($variables); // <-- after this call you will have new variables created in the local function scope based on your $variables array
ob_start();
include TEMPLATE_FOLDER . TEMPLATE_PREFIX . $template . $extension;
return ob_get_clean();
}
So now you would have two options if you know what variables you want to make available inside the function you could use the global keyword, but I would discourage using it, it could lead to weird bugs when you don't understand why your variables being changed (ps later you will move onto using classes and you won't have the headache of global variables).
// you can drop $variables from the function signature
function display($template, $extension = TEMPLATE_EXTENSION) {
global $users, $cart, $new_item;
// no extract needed, but please try not using global, it can lead to weird bugs
ob_start();
include TEMPLATE_FOLDER . TEMPLATE_PREFIX . $template . $extension;
return ob_get_clean();
}
Or you can use the extract to create variables in the function's scope so when you include the files they will have access to those variables. On thing to note here that extract will use the array keys as the variable names it is creating. That's why you are passing in display('user', ['users' => $users, 'cart' => $cart]); after this call, extract will create a $users and a $cart variable inside the function call. If you would call it with different array keys, like: display('user', ['u' => $users, 'c' => $cart]); the included file would complain that it can't find the variables $users and $cart.
I hope this helped, feel free to ask more if I wasn't clear anywhere.
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.
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!";
My php script includes another en.php file which contains the required english strings. This same page also calls a html page which uses the file and formats it using the contents of the en.php file.
I have a function in this script which references variables defined in the included script but I am getting error messages of the variable not being found. If I reference the variable outside the function, the variable is accessed correctly. Why can I not access these variables inside the function?
en.php
<?php
$lang_yes = 'Yes';
$lang_no = 'No';
?>
example.php
<?php
include_once('addons/assq/lang/en.php');
echo $lang_yes;
$q1 = convertToYesOrNoString(0);
echo $q1;
function convertToYesOrNoString($value){
//include_once('addons/assq/lang/en.php');
if ($value == 0){
return $lang_no;
}else if ($value == 1){
return $lang_yes;
}else{
return "---";
}
}
?>
My output is as follows:
Yes
Undefined variable: lang_no in example.php on the line in the function
I tried including the en.php directly into the function but that did not work either. How can I access these variables inside my function while including the file as implemented above?
You can either define it as a constant, pass it as an argument or declare it as a global within the function:
function convertToYesOrNoString($value){
global $lang_no, $lang_yes;
//...
}
That's a scope issue. That variable $lang_no will not be accessed under that function , you need to pass that as a parameter instead to the function definition.
function convertToYesOrNoString($value,$lang_no){ //<--- Like this.
Since you have mentioned that you have a lot of parameters .. you can write a turnaround like this...
Your en.php
<?php
//Map all those variables inside an array as key-value pair. as shown
$varArray=array('lang_yes'=>'Yes','lang_no'=>'No');
Some test.php
<?php
include('en.php');
function convertToYesOrNoString($varArray)
{
extract($varArray);
echo $lang_yes; // "prints" Yes
echo $lang_no; // "prints" No
}
convertToYesOrNoString($varArray);
This is what I have.
$filename= asql($_GET['filename']);
$fullfile = "xml/".$filename;
function delete_book_id($ids){
$data = simplexml_load_file($fullfile);
$data_count = count($data->item);
for($i = 0; $i < $data_count; $i++)
{
//basically what you want to remove
if(($data->item[$i]->id == $ids))
{
unset($data->item[$i]);
}
}
file_put_contents($fullfile, $data->saveXML());
}
lets say $fullfile is xml/name.xml and the file exists in our folder. Where the variable is called in the function it should work right?
If I replace the variable in the function with xml/name.xml it will work, but using the variable causes the page to break and not reload nor will it remove the line it is supposed to unset. Will the function not accept variables, or am I missing something here?
I have also tried using "xml/".$filename in place of the variable in the function. No luck there either.
$fullfile is defined outside of the function. It's undefined inside of it. Use global $fullfile; within function or define it there.