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
Related
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.
I want to write a PHP code which write a string line in text file if the line already available in text file then count the requests for example
text file contain:
red.apple:1
big.orange:1
green.banana:1
If some one request to add big.orange in file if its already available in file then count as big.orange:2 if not available then write new line big.orange:1
after execution code text file
red.apple:1
big.orange:2
green.banana:1
I've written the following code but not working.
<?PHP
$name = $_GET['fname']
$file = fopen('request.txt', "r+") or die("Unable to open file!");
if ($file) {
while (!feof($file)) {
$entry_array = explode(":",fgets($file));
if ($entry_array[0] == $name) {
$entry_array[1]==$entry_array[1]+1;
fwrite($file, $entry_array[1]);
}
}
fclose($file);
}
else{
fwrite($file, $name.":1"."\n");
fclose($file);
}
?>
Instead of creating your own format which you need to parse manually, you can simply use json.
Below is a suggestion about how it would work. It will add the requested fname value if it doesn't already exist and will also create the file if it doesn't already exists.
$name = $_GET['fname'] ?? null;
if (is_null($name)) {
// The fname query param is missing so we can't really continue
die('Got no name');
}
$file = 'request.json';
if (is_file($file)) {
// The file exists. Load it's content
$content = file_get_contents($file);
// Convert the contents (stringified json) to an array
$data = json_decode($content, true);
} else {
// The file does not extst. Create an empty array we can use
$data = [];
}
// Get the current value if it exists or start with 0
$currentValue = $data[$name] ?? 0;
// Set the new value
$data[$name] = $currentValue + 1;
// Convert the array to a stringified json object
$content = json_encode($data);
// Save the file
file_put_contents($file, $content);
If you still need to use this format (like, this is some exam test or legacy), try the function:
function touchFile($file, $string) {
if (!file_exists($file)) {
if (is_writable(dirname($file))) {
// create file (later)
$fileData = "";
} else {
throw new ErrorException("File '".$file."' doesn't exist and cannot be created");
}
} else $fileData = file_get_contents($file);
if (preg_match("#^".preg_quote($string).":(\d+)\n#m", $fileData, $args)) {
$fileData = str_replace($args[0], $string.":".(intval($args[1])+1)."\n", $fileData);
} else {
$fileData .= $string.":1\n";
}
if (file_put_contents($file, $fileData)) {
return true;
} else {
return false;
}
}
Here has a question: I need execute a task to put many data to another mysql database per minute; if the first task hasn't finish, the second has start; so,there has a multiple concurrent problem; how to resolve the problem??
I have some ideas, first, Let the task has a execute-time which less than the start time of next task;second, let the task support multi-process; but,i don't the how to write the code?
public function execute(Input $input, Output $output)
{
$tele_data = Telesales::field('*')->where([['create_time','<',time()-48*3600],['customer_label','in',[2,6,7]],['virtual_sale','=','0']])->whereRaw('phone is not null')->select()->toArray();
foreach($tele_data as $key=>$value) {
static::pushTeleToIdc($value);
}
}
private static function pushTeleToIdc($data = []) {
$res = Telesales::where('id',$value['id'])->update(['virtual_sale'=>'1']);
if(!$res) {
return;
}
$url = config('idc.tele_url');
$key = config('idc.tele_key');
$channel = config('idc.tele_channel');
$time = time();
$sign = md5($key.$channel.$time);
$urls = $url."?channel=".$channel."&sign=".$sign."&time=".$time;
$require_params = config('idc.require_params');
foreach($require_params as $key=>$value) {
if(array_key_exists($key,$data) && !empty($data[$key])) {
$d[$key] = $data[$key];
}else{
$d[$key] = empty($value)?'':$value[array_rand($value,1)];
}
}
$d['register_time'] = $d['create_time'];
$res = post_url($urls,$d);
$result = json_decode($res,true);
if (isset($result['code']) && $result['code'] != 0){
Log::init(['single'=>'tpushidc'])->error($res);
}
}
Could you help me resolve the problem?
The easiest thing to do is to setup a flag to tell that the process is already in progress and check if that's the case at the start of the function. I don't know how you want to setup the visibility of your code, so I leave it to you to extract $myFile to the file/class scope (same goes for the file path, you probably want to use some /var or /log folder for such stuff).
So the gist is: we create a file, if it doesn't exist or there is a 0 in it - it means we can start working. On other hand, if the contents of the file is 1, the process will die and it will be so every time you run it, until the first one finishes and rewrites the contents of the file to 0 (which means the process is not in progress anymore).
public function execute(Input $input, Output $output)
{
if ($this->isProcessInProgress()) {
die('Process is in progress');
}
$this->startProcess();
$tele_data = [...];
foreach($tele_data as $key=>$value) {
static::pushTeleToIdc($value);
}
$this->finishProcess();
}
private function isProcessInProgress() {
$myFile = 'tele_to_idc_process.txt';
$handle = fopen($myFile, 'r');
if (!$handle)
return false;
$status = fread($handle, 1);
fclose($handle);
return (bool) $status;
}
private function startProcess() {
$myFile = 'tele_to_idc_process.txt';
$handle = fopen($myFile, 'w');
if (!$handle)
return;
$status = fwrite($handle, '1');
fclose($handle);
}
private function finishProcess() {
$myFile = 'tele_to_idc_process.txt';
$handle = fopen($myFile, 'w');
if (!$handle)
return;
$status = fwrite($handle, '0');
fclose($handle);
}
You might get a warning if the file doesn't exist, you can suppress it with #fopen instead of fopen
Hi I am trying to get this external text file to print inside my php document. The code looks fine to me however when I echo it does not output anything and I am not sure why this is. Can anybody help me out as I am new to this.
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
$fp = fopen($location, 'r');
if ($fp) {
$readin = fread($fp);
fclose($fp);
} else {
echo 'Can\'t open input.txt';
}
Not sure what you're trying to 'echo' but have you checked if the file exists in the first place?
Your code could be written as:
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
if (file_exists($location) && $data = file_get_content($location)){
echo $data;
} else {
echo 'File not found';
}
if (file_exists($location) && $file = fopen($location, 'r')){
$file_content = fread($file, filesize($location));
fclose($file);
} esle {
echo 'File not found';
}
See here for more: http://php.net/manual/en/function.file-get-contents.php, http://php.net/manual/en/function.filesize.php
I'm new to PHP. I planned to create folder, sub folder, into that file depends on user Input.
Folder and sub folders has been created successfully.
Finally I try to create a file its showing bellow error.
fopen(upload/localhost/hrms): failed to open stream: Permission denied
in C:\xampp\htdocs\ssspider\index.php on line 205
My code is:
$dir = "http://localhost:8080/hrms/index.php";
//make directory
$directoryForServer = "upload";
$directoryForClient = $directoryForServer."/".$host."";
mkdir($directoryForClient);
$splitePath = explode("/", $folderPath);
$folderPath1 = $directoryForClient;
for($x = 1; $x <= (count($splitePath)-1) ; $x++)
{
$folderPath1 = $folderPath1."/".$splitePath[$x];
echo "<br>".$folderPath1." - successfully created<br>";
mkdir($folderPath1);
}
writefile($folderPath1);
function writefile($dir)
{
if( is_dir($dir)){
echo $dir;
$myFile = fopen($dir,"w");
if($myFile)
{
fwrite($myFile, $returned_content);
}
fclose($myFile);
}
}
Please help me to find out my problem?
Edit: Thanks. I got an error. In fopen I didn't mention file name . Now its working fine. Thanks
because you open a directory , fopen function just open file. your code is fill with error , just Refer to the following:
<?php
//make directory
$host = "aa"; //define $host variable
$directoryForServer = "upload";
$directoryForClient = $directoryForServer."/".$host."";
#mkdir($directoryForClient);
$splitePath = explode("/", $directoryForClient);
$folderPath1 = $directoryForClient;
for($x = 1; $x <= (count($splitePath)-1) ; $x++)
{
$folderPath1 = $folderPath1."/".$splitePath[$x];
echo "<br>".$folderPath1." - successfully created<br>2";
#mkdir($folderPath1);
}
writefile($folderPath1);
function writefile($dir)
{
if( is_dir($dir)){
echo $dir;
$myFile = fopen("upload/aa.txt","w");
if($myFile)
{
$returned_content = "hello world"; //define variable and his content before write to file.
fwrite($myFile, $returned_content);
}
fclose($myFile);
}
}