Jump to content

Rewriting script that uses fopen()


locoputo

Recommended Posts

I have this section in a script of mine:

 

@$info= fopen('/home/myuser/info.txt','r');
if (!$info) {
echo "[-] Error : coudn't read /home/myuser/info.txt";
exit;
}

 

this always ends as Couldn't read. So I tried only running fopen('/home/myuser/info.txt','r'); and I got a blank response. So I tried changing the function to

 

 

 

readfile('/home/myuser/info.txt','r');

That seemed to work, the file was read. Now I changed that in my script and next thing I know I get this error:

 

Warning: feof(): supplied argument is not a valid stream resource in /path/to/my/script.php on line 17
Warning: fgets(): supplied argument is not a valid stream resource in /path/to/my/script.php on line 18

 

Line 17 and 18 in the script contain the following:

while(!feof($info)) {
$str=fgets($info);

 

This will be because for feof to work it must point to a file successfully opened by fopen(). Would any of you expert coders be able to suggest a replacement for this code, so I can use readfile() instead? Would anyone know any other way to execute this code by using an alternative function to read the file? I would greatly appreciate any help. Thank you all in advance.

Link to comment
https://forums.phpfreaks.com/topic/200024-rewriting-script-that-uses-fopen/
Share on other sites

I prefer to use fopen, read the data, and make sure there isn't any errors from there.

 

/* Define the file, so we can use the name to check size of the file in the future. Much faster when dealing with a large number of files */
$file = "/home/myuser/info.txt";

/* Open the file for reading */
$fh = fopen($file, "r");
/* Read the file, in its entirety */
$data = fread($fh, filesize($file));
/* If reading the file failed, or if it is empty, throw an error. If not, move on */
if (!$data || empty($data)){
echo "[-] Error : couldn't read $file";
exit();
}
/* do whatever you are planning on doing from here */

/* Close the file */
fclose($fh);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.