TransWikia.com

PHP. How to read a file, if it is writing without a problem with "a+", but is not readable with "r"?

Stack Overflow Asked on January 13, 2021

I have two scripts: one of them writes the value of a variable to a file. In another script, I try to read it. It is written without problems, but it is not readable.
Here I write to a file:

$peer_id=2000000001;
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"a+");
fwrite($file, $peer_id);
fclose($file);

Here I read the file:

$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt"; 
$file = fopen($fileLocation,"r");
if(file_exists($fileLocation)){
        // Result is TRUE
}
if(is_readable ($file)){
      // Result is FALSE
}
// an empty variables, because the file is not readable
$peer_id = fread($file);
$peer_id = fileread($file);
$peer_id = file_get_contents($file);
fclose($file);

The code runs on "sprinthost" hosting, if that makes a difference. There are suspicions that this is because of that hosting.

One Answer

file_get_contents in short runs the fopen, fread, and fclose. You don't use a pointer with it. You should just use:

$peer_id = file_get_contents($fileLocation);

That is the same for is_readable:

if(is_readable($fileLocation)){
    // Result is FALSE
}

So full code should be something like:

$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
if(file_exists($fileLocation) && is_readable($fileLocation)) {
     $peer_id = file_get_contents($fileLocation);
} else {
    echo 'Error message about file being inaccessible here';
}

The file_get_contents has an inverse function for writing; https://www.php.net/manual/en/function.file-put-contents.php. Use that with the append constant and you should have the same functionality your first code block had:

file_put_contents($fileLocation, $peer_id, FILE_APPEND | LOCK_EX);

Correct answer by user3783243 on January 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP