PHP require_once not working in my code - php

this is probably a basic question about php, but I can't figure out how to solve it.
Well, I have a file called globals.php
<?php
$DATA = array(
'first' => 'LOL',
'second' => 'Whatever'
);
?>
And I also have another file (omg.php) with the following function:
<?php
require_once('globals.php');
function print_text_omg($selector = 0){
global $DATA; //added this line of code. NOW IT WORKS
$var = '';
if($selector == 0){
$var = '';
}else{
$var = 'Hi. ';
}
//$DATA is a variable from globals.php that is supposed to be declared in require_once('globals.php');
//$var is a variable inside the function print_text_omg
//I am trying to concatenate string $var with the string $DATA['first']
$finaltext = $var.$DATA['first'];
echo $finaltext;
}
?>
Then, in main.php I have this:
<?php
include('omg.php');
print_text_omg();
print_text_omg(1);
?>
This should print something like:
//LOL
//Hi. LOL
Instead, I have this warning:
Notice: Undefined variable: DATA in ...
Which is the part of $finaltext = $var.$DATA['first'];
UPDATE
Thanks to user Casimir et Hippolyte' suggestion, I've edited my function and it works now. Added the line that worked for me.

It doesn't work because $DATA isn't in the scope of your function.
To make $DATA available inside your function, you must pass it as a parameter to the function or define $DATA as a global variable.
The problem isn't related to require_once.
http://php.net/manual/en/language.variables.scope.php

The error is correct, first I can't find where did you declare $var (maybe it should be an object of some class?) and also $var doesn't contain the $DATA array, and for last, . operator in php is for concatenate strings, for object navigation is -> operator

You haven't declared the variable $var, plus . is php's concatenation operator. Try changing your code to this
$finaltext = $DATA['first'];

Related

How to dynamically set the argument to $_GET or $_POST?

I'm writing a function in php to check, if all arguments are set. This is for preventing the program to crash when a argument isn't set.
Unfortunately I get this error:
Notice: Undefined variable: _POST
The code running is the following:
# check for the right arguments
function checkArguments($type, $arg_array) {
# $type is either 'GET' or 'POST'
# $arg_array is an array with all the arguments names
foreach($arg_array as $arg) {
print(${"_" . $type}["name"]);
$type = "_" . $type;
if(!isset($$type[$arg])) {
$missing[] = $arg;
}
}
}
HI I will assume you wanted a variable variable, I try to avoid them as they are very hard to read in code. It also breaks ( or doesn't work in ) most IDE editors.
One thing I just saw that is relevant.
http://php.net/manual/en/language.variables.variable.php
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.
The $_POST would be counted among the "Superglobal" as is $_GET
You could assign them to a temporary variable and use that.
$arr = $_GET;
if ($type == "POST") $arr = $_POST;

PHP scope issue within while loop

Trying to teach myself php and I am struggling with what I think is a scoping issue?
I have a query, while loop, if/else and a function.
I would like to echo the results of the function get_patronapi_data($id) within my while loop.
My code so far is as follows (stripped for legibility);
$stmt = $conn->prepare("SELECT... ..."); //QUERY here ...
if( $stmt->num_rows > 0 )
{
while ($stmt->fetch()) {
if (SomethingIsTrue){
echo get_patronapi_data($id);
}
else {
echo $somethingElse;
}
}//end while
}//end if
define("APISERVER", "http://mydomain:4500");
function get_patronapi_data($id) {
$apiurl = "APISERVER" . "/PATRONAPI/$id/dump";//line 135
$api_contents = get_api_contents($apiurl);
$api_array_lines = explode("\n", $api_contents);
foreach($api_array_lines as $line){
if(strpos($line, "EXP DATE") !== false){
$data = explode("=", $line);
return $data[1];
}//end if
}//end foreach
}//end function
function get_api_contents($apiurl) {
$api_contents = file_get_contents($apiurl);//line 154
$api_contents = trim(strip_tags($api_contents));
return $api_contents;
}//end function
echo get_patronapi_data($id); // this works and echoes $data on screen
Whenever I echo get_patronapi_data($id); outside of the functions I successfully see the data on screen. However when I echo get_patronapi_data($id); within the loop I receive the following errors;
Notice: Use of undefined constant APISERVER - assumed 'APISERVER' in
C:\xampp...search_1.php on line 135
Warning: file_get_contents(APISERVER/PATRONAPI/3047468/dump): failed
to open stream: No such file or directory in C:\xampp...search_1.php
on line 154
I'm sure I am doing something very silly however any help is appreciated.
Putting some of my comments to an answer.
You need to remove the quotes from:
$apiurl = "APISERVER" . "/PATRONAPI/$id/dump";
^ ^ <<< remove those
since that's treated as a string literal, rather than a constant.
It is declared in:
define("APISERVER", "http://mydomain:4500");
Reference:
http://php.net/manual/en/function.constant.php
Then your connection is out of scope and should be used inside your function(s).
I.e.:
function get_patronapi_data($conn, $id)
and do that for all your functions requiring a connection for them.
You will need to make sure that all folders/files have proper permissions to be written to.
The missing link is the statement:
$data = get_patronapi_data($id);
you should put before echo $data;.
It calls the function get_patronapi_data() passing the value of variable $id as argument and stores the values the function returns in the variable $data.
The variable $data you echo() is not the same as the one used by the function. They use the same name but they are different (I hope you don't use the keyword global in the function).
Read more about functions in the PHP documentation.
The updated (fragment of) code looks like:
if (SomethingIsTrue) {
$data = get_patronapi_data($id);
echo $data;
} else {
echo $somethingElse;
}
If you don't do further processing on the value returned by the function, you can, as well, remove the temporary variable $data from the code fragment above and just use:
if (SomethingIsTrue) {
echo get_patronapi_data($id);
} else {
echo $somethingElse;
}
Assuming you want to print the data from the get_patronapi_data() every iteration in the while loop, you need to actually call the method instead of using $data. Right now you're trying to print something called $data, though you never set a value to it. The $data you return in the function cannot be used outside of that function, so it does not exist in the while loop.
What you could do in your while loop is $data = get_patronapi_data();, and then echo $data. However, you can just echo get_patronapi_data(); first.
If you only want to call your function once, you need to set a variable before you start your while loop (i.e. $variable = get_patronapi_data()), and then use that variable in your while loop (i.e. echo $variable);
I'm not sure I fully understand your question. What happens if you just put
echo get_patronapi_data($id);
in the loop instead of
echo $data;
? As written, you're not calling the function in the loop.

Use variable variables with superglobal arrays

I wonder if is possible to read dynamically superglobal variables, I would like to do something like that:
<?php
$n = 'GET';
$var = '$_'.$n.'[\'something\']'; // pour lire $_GET['something']
echo $var;
//Or
$n = 'POST';
$var = '$_'.$n.'[\'something\']'; // pour lire $_POST['something']
echo $var;
?>
This code don't work as I want, but I would like to know if is workable in PHP?
You can't use variable variables with superglobals, functions or class methods and not with $this.
And a quote from the manual (It's right before the user comments if you search it):
Warning:
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.
Thank you is exactelly what I search
But we can't use that into function please?
$n = '_GET';
// don't work => Undefined variable: _GET
function f($n) {
echo ${$n}['a'];
}
f($n);
//work fine
echo ${$n}['a'];

php variable to call specific function

How would I call a php function from a variable.
For example:
$variable = functionname;
so when calling $variable this will return functionname();
I have tried the following:
$variablereturn = $variable."(sometext)";
print $variablereturn;
and
print $variable."(". print $variabletext. ");";
neither seem to work.
Just use the following:
$variable = 'function_name';
$variable('your_argument');
Documentation

PHP store function in array

i want to store function in array
send the array to another page
then execute it
i already read Can you store a function in a PHP array but still don't know what to do
here's what i try
control.php (it start here)
<?php
function getFirstFunction(){ echo "first function executed"; }
$data = array();
$data[0] = getFirstFunction();
$data[1] = function(){ echo "second function executed"; };
$data[2] = function(){ require_once "additional.php"; };
$data[3] = "my string";
header('Location: view.php?data='.$data);
?>
additional.php
<?php echo "additional included" ?>
view.php
<?php
if( isset($_GET['data']) ){
foreach( $_GET['data'] as $temp ){
if( is_callable($temp) ){
$temp;
}else{
"its not a function";
}
}
}
?>
my error =
Warning: Invalid argument supplied for foreach() in D:\Workspace\Web\latihanns\php\get\view.php on line 4
EDIT
thanks for notify that this code its dangerous.i'm not use this code in real live. i just try to learn store function in array then call it. then i just curious how if i call it on another page. i just simply curious... i make my code look clear and simple here because i afraid if i wrote complicated code, no one will be here or my post will closed as too localized...
If you want to pass anything than string into URL, only option is convert it to string form which is reversible to original types. PHP offers function called serialize() which converts anything to string. After that, you can call unserialize() to convert string back to original data. So you have to change one line in control.php to this:
header('Location: view.php?data='.serialize($data));
In file view.php you have to change one line to this:
foreach( unserialize($_GET['data']) as $temp ){
But you have to fix more things than this. If you have callable variable, you can't invoke function with $variable, but with $variable(). It is good to mention, that in PHP does not matter if you have real function (anonymous function, Closure etc.) in variable, or if variable is simple string with name of exists function.
However you have even another bug in control.php. Code $data[0] = getFirstFunction(); will not pass function getFirstFunction an make it callable, it just calls the function and put its return value to variable. You can define getFirstFunction as anonymouse function like function in $data[1] or just pass it as string like $data[0] = 'getFirstFunction' which will work.
At the end - as anyone mentioned here - IT IS VERY DANGEROUS ans you shouldn't use this on public server.

Categories