Similar questions have been asked before, but after following several working examples closely I cannot get this to work for me.
I am trying to access the variable $nameValues that was declared in insert-name.php
insert-name.php is the first script that runs:
error_reporting(-1);
$nameValues = "'".implode("', '", array_values($nameArray))."'";
print_r($nameValues); // returns the expected variable
and insert-answer.php is the second script to run:
error_reporting(-1);
require "insert-name.php";
if (isset($nameValues)) {
print_r("nameValues variable:" . $nameValues);
} else {
echo "variable nameValues does not exist";
}
//returns nameValues variable:'' indicating that $nameValues exists but is empty
Both .php files are stored in the same folder on my webserver. I've tried using both require and include statements. I successfully use a require statement to connect to my database in both scripts, not sure why it is not working for insert-name.php.
Edit:
No errors are reported.
If statement returns "nameValues variable:'' " indicates that $nameValues variable exists but is empty.
I also tried replacing require "insert-name.php"; with require __DIR__."/insert-name.php"; which returned "variable nameValues does not exist" from the if statement.
Because neither gave a fatal error bothrequire statements successfully accessed the insert-name.php file, but I don't know why one method thinks $nameValues doesn't exist and the other thinks $nameValues is empty.
There is no problem accessing the variables from another file like you have provided they are in the same scope (one is not inside a function etc.). In your case it looks like it is just a case of how you are calling print_r()
When you do print_r('nameValues variable:" . $nameValues) you are converting $nameValues into a string.
Try something like this to dump your $nameValues:
error_reporting(-1);
require "insert-name.php";
if (isset($nameValues)) {
echo "nameValues variable: ";
print_r($nameValues);
} else {
echo "variable nameValues does not exist";
}
As you said:
returns nameValues variable:''
There was one detail I overlooked, the quotation marks at the end. When you echo a string in PHP it only prints the content (there are no quotations printed, unless they are in the string).
Effectively this all just means that $nameArray is empty, so check the script that generates this. Also, because of how implode() works, array_values() is completely redundant here.
As simple way to test this is echo count($nameArray);. If the output is "0" the array is empty.
Related
I'm running into a strange problem where $_REQUEST is not showing the value of a parameter I am explicitly passing e.g.
http://example.com/strange.php?parName=1234
strange.php:
<?php
$foo = $_REQUEST['parName'] ;
echo $foo ;
?>
I have looked in the Inspector and the Network tab actually shows the correct query string parameter.
I have carried out some tests.
in test.html:
link
in request.php:
$foo = $_REQUEST['parName'];
echo $foo ;
I have also tried:
$foo = $_GET['parName'];
echo $foo ;
Both of which work.
Therefore thinking about the strange issue you are encountering, you will need carry out various checks:
Is the query string getting passed? See $_SERVER["QUERY_STRING"]
Check the request method $_SERVER["REQUEST_METHOD"]
Check to see if the parName variable isset
if(isset($_GET['parName'] )) {
$foo = $_GET['parName'];
echo $foo ;
}
else { "echo query string not received";
}
Check your error log to see what Apache is saying?
What data is actually contained in the parName variable?
var_dump($_REQUEST['parName'])
Once you've run all these tests, and the issue is still not resolved, please post your results so we can consider other possible paths to solving this problem.
I have an extremely oversimplified logger function:
<?php
class Logger {
public function __construct($logFile) {
$this->logFile = $logFile;
}
public function log($message) {
$message = date('c') . $message;
file_put_contents($this->logFile, $message, FILE_APPEND | LOCK_EX);
echo "it ran ";
}
}
Calling it like this
$logger = new Logger('log.txt');
$logger->log("message");
echo "called the method";
causes the message to be written to the file exactly 3 times, instead of 1.
The code is outside of any loop, which is confirmed by echo statements, which get printed only once.
Also, if I simply run file_put_contents() function on place where I'd call the log method, it works fine and writes the content just once. So it might have something to do with my class, but no clue what.
EDIT: #Tommy: here is the log file content:
2014-09-26T07:24:51-04:00message2014-09-26T07:24:54-04:00message2014-09-26T07:24:54-04:00message
EDIT 2: I tried using die() function after calling the method, and then it did write the message just once. So I kept moving the die() through the code, and it starts writing the message 3 times after this exact line:
if (isset($_POST['create_account'])) {
die;
Since there's a die below it, it shouldn't even matter what's in further code, right?
Wonder if it might be some sort of php bug, this is very stange. If I put the die() above this line, it will work fine and write the message just once.
There's a fairly good chance that your code does a redirect or reload somewhere. This causes a new request to start, which wipes away the original echo but does not remove the one written to file. As a result it looks like it was echo'd once and written thrice. But really, it was echo'd thrice as well, just the other copies have been removed.
If you want to see what's going on, print part of the stack-trace into the log-file along with the message. You can see exactly on which line the message is created and during which function call.
The main issue as per my experience is the index.php is being called twice. So, to fix:
change the file name
fix the index.php such that favicon.ico is missing!
Here is the code I have been struggling for several hours:
if ((require $_SESSION['ROOT_PATH'] . '/templates/core/menu_js.php') == 'OK') {
echo 'OK';
} else {
echo 'KO';
}
If I understand the PHP documentation on the "require" directive correctly, the "KO" should never be written because, if the require doesn't work, an error is raised.
In my case, the "KO" is always displayed even with error tunning :
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
Note that the same require (or include) works perfectly in other pages of the site.
EDIT
The if structure has been added after watching the documentation.
At first, I had a single line :
require $_SESSION['ROOT_PATH'] . '/templates/core/menu_js.php';
As I checked that this line was not working, I added the if.
By the way. Required page (when it works) adds a script tag to calling page that I never see on this unique page. On any other page where this require is used, the script appears on output.
So my question should be "if the output of the required php file is not displayed, why is there no error raised ?"
According to the documentation
Successful includes, unless overridden by the included file, return 1... Also, it's possible to return values from included files. You can take the value of the include call as you would for a normal function.
So your file isn't returning 'OK'. It's returning either 1 (for success) or a custom value.
require is a language construct, not a standard function. By using require you're already indicating the code should fail if the file isn't found. Most likely you do not need to check the return value.
This only works the way you expect if menu_js.php contains return 'OK';. Otherwise the require works just fine, but the returned value is not "OK", which is why your "KO" condition is triggered. require doesn't return 'OK'. If the require does not work, the program is halted immediately, your false condition will never be hit the way you think it will.
There are some mistakes here:
According to the PHP documentation:
require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error.
A fatal error will stop your script execution.
require returns what the included file returns:
// a.php
return 'test';
// b.php
$result = require 'a.php';
echo $result; // will display 'test'
So, don't test the return value of require! Use is_file(), then if true, require that file!
You cannot use require in if
Use this
if(file_exists($_SESSION['ROOT_PATH'] . '/templates/core/menu_js.php'))
{
echo 'OK';
} else {
echo 'KO';
}
While it's true that the require will not return anything, making the conditional always return 'KO' since the left hand value in the parenthesis will never equal 'OK', you can check to see if the file has failed by setting the display_errors ini value in this script temporarily On.
Since you have your error reporting set to catch this, your display_errors is probably off, therefore not showing you this. Set it for this script like this:
ini_set('display_errors', 'on');
When I'm developing websites, I use a very (very) simple system of creating pages:
//$_page is, of course, declared above the loop, just as $needed_modules is.
foreach ($needed_modules as $part)
{
global $_page;
if (file_exists($part)) {
$_page . file_get_contents($part);
} else {
//404
}
}
echo $_page;
Now, the problem is that file_get_contents doesn't return anything: not false, not a string, nada (and the file is not empty).
Execution does go inside the if and $part (which corresponds to a filename with relative path) isn't just set, but it actually points to the file.
Why is it that $_page is empty (as opposed to being set, isset($_page) actually evaluates to TRUE)?
Edit: Error-reporting is on full throttle on my server, and the logs show nothing out of the ordinary.
You are not saving the return value of file_get_contents:
$_page . file_get_contents($part);
I think you meant to say:
$_page .= file_get_contents($part);
You're not doing anything with the returned value. Try this:
$_page .= file_get_contents($part);
The problem
The following code produces this error from the line "print $readerStatus" -
Undefined index: readerStatus
Code
<?php
//Get Cookie Value
if (isset($_COOKIE['readerStatus'])) {
$readerStatus=$_COOKIE['readerStatus'];
} Else {
$readerStatus="Not Set";}
echo "The value of Cookie readerStatus is " . $_COOKIE['readerStatus'];
print $readerStatus;
?>
Background
The goal is simply that if a cookie is set I want to pass the value into a Javascript. My strategy is as follows:
Get the value from the cookie
Set a variable to the value of the cookie
Then use a php echo inside of the Javascript to transfer the value.
It works as expected but Eclipse is giving me the error and so I assume there is something wrong with the above code.
I'd appreciate any pointers on possible sources of the problem.
Thanks
Is this working?
<?php
//Get Cookie Value
if (isset($_COOKIE['readerStatus'])) {
$readerStatus=$_COOKIE['readerStatus'];
} else {
$readerStatus="Not Set";
}
echo ("The value of Cookie readerStatus is ".$readerStatus);
print ($readerStatus);
?>
This is a warning, not an error. However, you can skip the error by using array_key_exists. Generally, I'm not a fan of isset for this kind of checking.
if (array_key_exists('readerStatus', $_COOKIE))
{
$readerStatus=$_COOKIE['readerStatus'];
}
else
{
$readerStatus='Not Set';
}
echo 'The value of Cookie readerStatus is '. $readerStatus;
Some IDEs are less forgiving than the PHP parser itself. That being said, do you get any errors or notices when running the code? Variables in PHP are implicitly declared, so the undefined index message is simply a NOTICE (that can be ignored) regarding the accessing of an array element without it existing first.
If you check it exists prior to accessing it like this, you shouldn't have a problem.
$readerStatus = isset($_COOIKE['readerStatus']) ? $_COOIKE['readerStatus'] : '';