function numOfLines () {
$file = fopen("data/text.txt", "r");
$count = 0;
while (!feof($file)) {
$line = fgets($file);
$count++;
}
return $count;
}
print_r(numOfLines()); = output 13 (for example)
Above code works perfectly fine.
However, if I declare $FILE variable outside the function and pass it as parameter of the function, then it gives this error "feof(): supplied resource is not a valid stream resource "
$FILE = fopen("data/text.txt", "r");
function numOfLines ($file) {
$count = 0;
while (!feof($file)) {
$line = fgets($file, 1024);
$count++;
}
return $count;
}
print_r(numOfLines($FILE)); = feof(): supplied resource is not a valid stream resource
Could anyone explain it a little bit what's actually going on here?
You're declaring $FILE as the file handle, but passing the undefined $file as an argument to the function. PHP is case sensitive.
Related
I use newrelic to keep track of anything on my website and I always get this error:
Error message: E_WARNING: fclose() expects parameter 1 to be resource, boolean given
Stack trace: in fclose called at /etc/snmp/bfd-stats.php (68)
This is how /etc/snmp/bfd-stats.php looks like
<?php
$a = 0;
$ptr = 0;
$any = 0;
$mx = 0;
$ns = 0;
$cname = 0;
$soa = 0;
$srv = 0;
$aaaa = 0;
$txt = 0;
$total = 0;
if(file_exists('/etc/snmp/bfd-log-pos.stat')) {
$lfh = fopen('/etc/snmp/bfd-log-pos.stat','r');
$string = fread($lfh,2087);
$res = explode(',',$string);
fclose($lfh);
}
else {
$res = array();
$res[0] = 0;
$res[1] = 0;
}
if(file_exists("/var/log/bfd_log.1")) {
$stats = stat('/var/log/bfd_log.1');
if($stats[10] > $res[0]) {
$res[0] = 0;
$res[1] = 0;
}
}
$fh = fopen('/var/log/bfd_log', 'r');
fseek($fh,$res[1]);
$blocks = 0;
if(!$fh) {
echo "Error! Couldn't open the file.";
} else {
while (!feof($fh)) {
$data = fgets($fh);
if(preg_match('/executed\sban/',$data)) {
$blocks++;
}
}
}
$lfh = fopen('/etc/snmp/bfd-log-pos.stat','w');
$timestamp = time();
$pos = ftell($fh);
fwrite($lfh,"$timestamp,$pos");
fclose($lfh);
if(!fclose($fh)) {
echo "Error! Couldn't close the file.";
}
print("bfd_blocks\n$blocks");
?>
On line 40: $fh = fopen('/var/log/bfd_log', 'r'); I looked at the directory /var/log and there is no file called bfd_log, I dont know if I have to create it by myself or it is automatically created.
Can anyone help me on fixing this error, Thanks in advance.
The error indicates that you are trying to pass a variable with a boolean value (true/false) to a function that needs a resource instead of a boolean value.
Please make sure that before you use resources from variables, the function that returns the resource has not run into trouble. Only on success perform the other functions that use this resource/variable.
$fh = fopen('/var/log/bfd_log', 'r');
// check fh before other functions use this variable
if (!$fh) {
echo "Error! Couldn't open the file.";
} else {
// perform task with resource $fh
fseek($fh, $res[1]);
[...]
$lfh = fopen('/etc/snmp/bfd-log-pos.stat', 'w');
// check before other code block is executed and use this variable
if( $lfh )
{
// perform task with resource $lfh
$pos = ftell($fh);
fwrite($lfh, "$timestamp,$pos");
fclose($lfh);
fclose($fh);
[...]
} else {
// lfh error
}
}
If you always check before using variables, you won't run into this error anymore.
I wrestled with this problem and could not find the answer until I separated my write check (put it first) from the actual file write code. So before I would open the file fopen/fwrite then do the is_writable check and then do the fclose and i would get this error.
To resolve I moved the is_writable and variable declaration before the fopen/fwrite and the error went away. Shown below (former php code position shown in comments) The first comment did help me realize this... Thank you.
$myfile = "/var/www/html/newfile.txt";
if (is_writable($myfile)) {
echo "The file is writable";
}
else {
echo "The file is not writable";
}
$txt = "$name, $email, $command, $searchtype, $keyword \n";
$myfile = fopen('/var/www/html/newfile.txt', 'w') or die("Unable to open file!");
fwrite($myfile, $txt);
// $myfile = "/var/www/html/newfile.txt";
// if (is_writable($myfile)) {
// echo "The file is writable";
// }
// else {
// echo "The file is not writable";
// }
fclose($myfile);
Try
$fh = fopen('/var/log/bfd_log', 'a+');
a+ mode will create the file if it does not exists
I have a little problem with this code I have here. This code searches in a txt file and returnes what it has found.
Now what I want to do is change the file path with a $_GET method
But when I put in a $_GET method inside the "" it just says alot of errors such as "Your path cannot be empty"
What does not work:
$handle = #fopen(."$_GET['filepath']"., "r");
How I want it
$handle = #fopen("I/want/this/$_get/method", "r");
Full code
<?php
function find_value($input) {
// $input is the word being supplied by the user
$handle = #fopen("/users/edwin/list.txt", "r");
if ($handle) {
while (!feof($handle)) {
$entry_array = explode(":",fgets($handle));
if ($entry_array[0] == $input) {
return $entry_array[1];
}
}
fclose($handle);
}
return NULL;
}
?>
Thanks :)
Check the way you're handling your quotes.
$handle = #fopen($_GET['filepath'], "r");
Since it's a variable, it does not have to be encapsulated at all, unlike a string.
I would like to point out before I get into this that I am a PHP newb, and I have been struggling for a while with this before finally deciding that I don't know what I'm doing with
function extract_bin($Filename, $output){
global $template;
global $BinColumnDelimiter;
global $BinLineEnd;
$decodedfile = fopen($output,'w+');
$decodedfilecontents = "";
$handle = fopen($Filename, "r");
if ($handle) {
foreach ( $template as $ColName=>$Endians)
$decodedfilecontents .= $ColName.$BinColumnDelimiter;
$decodedfilecontents .= $BinLineEnd;
while (!feof($handle)) {
$lastLine = '';
foreach ($template as $ColName => $Endians){
$hex = bin2hex(fread($handle,$Endians));
if ( $Endians <= 4) {
$val = hexdec(decodehex($hex));
if ( $val == 4294967295 ) $val = -1;
$lastLine .= $val.$BinColumnDelimiter;
} else {
$lastLine .= str_replace("\t"," ",hex2str($hex)).$BinColumnDelimiter;
}
}
if ( ! feof($handle))
$decodedfilecontents .= $lastLine.$BinLineEnd;
}
fclose($handle);
fwrite($decodedfile,$decodedfilecontents);
fclose($decodedfile);
}
echo '<h1>'.$output.'</h1>';
echo '<hr />';
print_r($decodedfilecontents);
}
And I keep getting this error:
Warning: fopen(): Filename cannot be empty in C:\xampp\htdocs\rh-bin\func.php on line 8
My questions are, what am I doing wrong in my attempt to pass on the uploaded file as an attachment? And, why does $FileName seem to be empty? Also, not everyone will be uploading files, so how could I allow the submit?
print_r($Filename) to check if it prints anything
check $Filename is empty or not before passing to fopen(). // it is good practice.
According to your question, your saying that not every one is uploading file, then your calling this function every time with empty value while not uploading the file also check this and make sure.
I am a new PHP developer and I just started working with files in PHP.
I have the following code to count number of txt files in the directory and store their names in an array and then using a loop display the total lines in each of the files!
here is the code, help me where I have gone wrong!
$dir = opendir('directory/');
$num_files = 0;
$dir_files[] = array();
while (false !== ($file = readdir($dir))){
if (!in_array($file, array('.', '..','Thumbs.db')) and !is_dir($file)){
$num_files++;
echo $file;
array_push($dir_files,$file);
echo "<br />";
}
}
echo "--------------------------------------<br />";
echo "Number of files in this directory: ".$num_files."<br />";
echo "--------------------------------------<br />";
foreach($dir_files as $dir_file=>$value){
$file='directory/'.$value;
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
echo "File $file has $linecount lines!";
}
I get the following errors:
Notice: Array to string conversion in D:\xampp\htdocs\PHP_practice\read_lines_of_files.php on line 19
Warning: fopen(directory/Array): failed to open stream: No such file or directory in D:\xampp\htdocs\PHP_practice\read_lines_of_files.php on line 21
Warning: feof() expects parameter 1 to be resource, boolean given in D:\xampp\htdocs\PHP_practice\read_lines_of_files.php on line 22
Your code is toooooooo lengthy. Try this : This will do whole functionality for you, let me know if any issues.
foreach(glob('directory/*.txt',GLOB_BRACE) as $value){
$file =$value;
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
echo "File $file has $linecount lines!";
}
change:
$dir_files[] = array();
to
$dir_files = array();
And:
fopen() returns a file pointer resource on success, or FALSE on error.As it is throwing an error opening the file, feof() is receiving FALSE instead of a file pointer resource: so you get the error "expects parameter 1 to be resource, boolean given in"...
I'm trying to define an array with a list of file urls, and then have each file parsed and if a predefined string is found, for that string to be replaced. For some reason what I have isn't working, I'm not sure what's incorrect:
<?php
$htF = array('/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension');
function update() {
global $htF;
$handle = fopen($htF, "r");
if ($handle) {
$previous_line = $content = '';
while (!feof($handle)) {
$current_line = fgets($handle);
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
{
$output = shell_exec('URL.COM');
if(preg_match('#([0-9]{1,3}\.){3}[0-9]{1,3}#',$output,$matches))
{
$content .= 'PREDEFINED SENTENCE '.$matches[0]."\n";
}
}else{
$content .= $current_line;
}
$previous_line = $current_line;
}
fclose($handle);
$tempFile = tempnam('/tmp','allow_');
$fp = fopen($tempFile, 'w');
fwrite($fp, $content);
fclose($fp);
rename($tempFile,$htF);
chown($htF,'admin');
chmod($htF,'0644');
}
}
array_walk($htF, 'update');
?>
Any help would be massively appreciated!
Do you have permissions to open the file?
Do you have permissions to write to /tmp ?
Do you have permissions to write to the destination file or folder?
Do you have permissions to chown?
Have you checked your regex? Try something like http://regexpal.com/ to see if it's valid.
Try adding error messages or throw Exceptions for all of the fail conditions for these.
there's this line:
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
and I think you just want a != in there. Yes?
You're using $htF within the update function as global, which means you're trying to fopen() an array.
$fh = fopen($htF, 'r');
is going to get parsed as
$fh = fopen('Array', 'r');
and return false, unless you happen to have a file named 'Array'.
You've also not specified any parameters for your function, so array_walk cannot pass in the array element it's dealing with at the time.