PHP variable var_dump = NULL?

5.5k views Asked by At

I have a PHP script that calls the function fileRead2 function from the file fileRead2.php.

The function below reads username.txt (Which display's the username).

vim fileRead2.php

<?php
function fileRead2() {
    global $fh, $line;    
    $fh = fopen('username.txt','r');
    while ($line = fgets($fh)) {
        // <... Do your work with the line ...>
        echo($line);
    }
    fclose($fh);
}
?>

If I run the linux command cat on the linux filesystem it show's 'tjones' (the username.)

I run the below in a script.

<?php
// Read the Username
require_once('fileread2.php');

$userName = fileRead2();
echo $userName;
var_dump($userName);
>?

It echo's $userName that display's 'tjones' however var_dump show's its output as NULL.

Is there any reason why var_dump shows the $userName variable as NULL, when it should be string 'tjones'?

The reason I ask is because I need the variable $userName; for other parts of code and because it's NULL nothing else is working, and I have no idea why?

2

There are 2 answers

2
VKK On BEST ANSWER

You'd need to modify fileRead2.php to use return instead of echo:

<?php

function fileRead2() {

global $fh, $line;    

$fh = fopen('username.txt','r');

$lineReturn = "";

while ($line = fgets($fh)) {
  // <... Do your work with the line ...>
  $lineReturn = $line;
}
fclose($fh);

return $lineReturn;

}

?>

echo is used to send information to the standard output - what this means is that if you run a php script in the terminal and use echo, it's going to be sent to the terminal (assuming you don't redirect the standard output elsewhere); if you're using the php script to generate web content, it will output the information to the browser (this is a simplification).

Return on the other hand is used inside functions to send information to blocks of code outside of the function. So in your case, you want the function fileRead2 to read from the username.txt file, and then return the first line (username) so that you can set a variable that's outside of the function. In order to do this you have to use return.

As another note, if you're not doing any additional "work" on the line beyond setting the $line variable to the fgets output and the username is on the first line of the username.txt file, then you don't need a while loop. Instead you can just do $line = fgets($fh);, and then of course close the file and return the $line variable.

0
LF-DevJourney On

You function fileRead2() have not a return clause, so it return type void. And the var_dump()'s return type is also void.

so

$userName is null, so echo $userName output nothing.

var_dump($username) will output the NULL.

echo var_dump($userName) output nothing.

And in your code the readfile2 just add return $line; will return false