user6862524 user6862524 - 1 year ago 42
PHP Question

PHP file handling and fread error

i'm working on PHP file handling:

i have two question:

In the following function i have this error :
Warning: fread() expects parameter 1 to be resource, string given in C:\xampp\htdocs...

and my function is:

function readingFile($file,$mode) {
if (gettype($file) !== 'string' && gettype($mode) !== 'string') {
return 'Pleas enter a file name and mode';
fopen($file,$mode) or die ('File Not Exist!!');
$size = filesize($file);
return fread($file,$size);
echo readingFile('file_1.txt','r');

1) how can i fix that?

2) when i write the following code and then press the enter i get a (False) in the first of next row. my mean's:

$size = filesize('file.txt'); // i press enter
False //here i get this word


$file = fopen('file.txt','r'); // i press enter
False // here i get this word

what is that?do not correct my codes?

in addition i'm using notepad++.

Answer Source

fread takes a file handle as a first parameter (not a filename), so you need to change your code like this:

$handle = fopen($file,$mode) or die ('File Not Exist!!');
$size = filesize($file);
return fread($handle,$size);

Also if you want to read the entire file, a more straightforward method is file_get_contents. The code would then just be:

return file_get_contents($file);