fclose() expects parameter 1 to be resource - php

I've a problem with a PHP script that creates some csv file.
The PHP script is the following:
<?php
$inputFile = "/var/www/vhosts/pecso.it/httpdocs/test/export30gg.txt";
$csvData = file_get_contents($inputFile);
$rows = explode(PHP_EOL, $csvData);
$rowsArray = array();
foreach ($rows as $row) {
$rowsArray[] = str_getcsv($row);
}
$csvFileName = "/var/www/vhosts/pecso.it/httpdocs/graphs/export30gg.csv";
if (file_exists($csvFileName)){
unlink($csvFileName);
}
$csvFile = fopen($csvFileName, "w");
$csvFileForGraph = fopen($csvFileNameForGraph, "w");
for ($i = 0; $i < count($rowsArray); $i++) {
$dateTime = DateTime::createFromFormat('d/m/Y', $rowsArray[$i][0]);
$d = $dateTime->format('Y-m-d');
$rowsArray[$i][0] = $d;
$rowForGraph = $rowsArray[$i];
unset($rowForGraph[1]);
$row = implode(',',$rowsArray[$i]);
$rowForGraph = implode(',',$rowForGraph);
file_put_contents($csvFileName, $row.PHP_EOL , FILE_APPEND);
}
fclose($csvFileName);
?>
This script works correctly and csv file export30gg.csv is correctly created but, every time I run this script, I've the following error:
fclose() expects parameter 1 to be resource
Can you help me, please?

flose() accepts parameter as file pointer resource which will be found while code execution for example in your case it is $csvFile = fopen($csvFileName, "w");
So, it should be
fclose($csvFile);
and not the fclose($csvFileName);

It should be like
fclose($csvFile);
because you've stored recourse link in $csvFile, not in $csvFileName

Related

how can I sort a text file in php

english, lang1, lang2
rat, rat_lang1, rat_lang2
ball, ball_lang1, ball_lang2
air, air_lang1, air_lang2
If I have this text file I read in php, how can I sort it starting the second line, the first line being the heading of the file. So that the file will print out like..
english....
air....
ball...
rat....
I read the file using fopen, put it in $content using fread, used explode with new line. I can see the array of lines but cannot figure out how to sort it. Any suggestions would be appreciated.
Much of this solution was answered within the comments in response to your question. All put together you're looking for something like:
<?php
$f = file("text.txt"); //read the text file into an array
$newf = fopen("newtext.txt", "w+"); //open another file
$header = $f[0]; //store the first element of the array as $header
echo $header."<br>"; //and echo the header
fwrite($newf, $header); //write the header to the new file
array_shift($f); //then remove the first element of the array i.e. the header
sort($f); //sort the array (no flag param = alphabetical sort)
foreach($f as $line){ //loop through the sorted array
echo $line."<br>"; //print each element as it's own line
fwrite($newf, trim($line)."\n"); //write other elements to new file on own line
}
fclose($newf); //close the file
?>
Try this:
$data = trim(file_get_contents('sort_test.txt'));
$data = explode("\n", $data);
$array_order = array();
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation, "w");
for ($i = 0; $i < count($data); $i++) {
($i > 0) ? $array_order[$i] = $data[$i] : fwrite($file, $data[0]);
}
sort($array_order);
$data = implode("\n", $array_order);
fwrite($file, $data);
fclose($file);
echo 'file created - location::' . $fileLocation;
Output myfile.txt
english, lang1, lang2
air, air_lang1, air_lang2
ball, ball_lang1, ball_lang2
rat, rat_lang1, rat_lang2
Maybe the new file (myfile.txt) will needs write permission to the directory you are writing to , in my case the file has been stored into C:/.../htdocs/myfile.txt

php warning fclose() expects parameter 1 to be resource boolean given

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

Join part of line in csv with php

I have one csv file like this:
"Name","surname","note"
"Jhon","Jhon","fdskngkfngkfnkglnlksanjlbgsjangkjlvnkajsdf"
"Jhon2","Jhon2","fdssfsfsfkngkfngkfnkglnlksanjlbgsjangkjlvnkajsdf"
"Jhon3","Jhon3","fdssfsfsfkngkfngkfnk
glnlksanjlbgsjangkjlvnkajsdf"
"Jhon4","Jhon4","fdssfsfsf
kngkfngkfnkglnlks
anjlbgsjangkjlvnkajsdf"
I need to join the line who return, because i need to add this file in mySQL.
I use this code
$csv_file = "output.csv";
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile))
{
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode('","', $csv_data[$i]);
$insert_csv = array();
$insert_csv['Gestore'] = ltrim($csv_array[0], '"');
echo $insert_csv['Gestore'] . "</br>";
$query = "INSERT INTO prova(Gestore) VALUES('".$insert_csv['Gestore']."')";
$n=mysql_query($query, $connect );
$i++;
}
It works but i need to solve precedent problem...
You can simply use the PHP function fgetcsv.
As an alternative to PHP you could use
LOAD DATA INFILE
see MySQL manual, LOAD DATA INFILE, if you've got the FILE privilege.

PHP file-writing problems

I have a file called "number.txt"(there is a number inside, e.g.: 0 )
And I want to read the number inside the number.txt and use fwrite to write the number plus 1
(number+1), so that each time anyone visit this webpage, the number will add 1.
but when i test it, it only works at first time(now number.txt is 1).
Then i try another time, the fread function read 0 but not 1.
<?php
$fgc = file_get_contents('number.txt');
settype($cont, "integer");
$cont = $cont + 1;
settype($cont, "string");
file_put_contents('number.txt', $cont);
$str = settype($cont, "string");
$fp = fopen( $str ,'w+');
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
$da = $_GET['data'];
fwrite($fp, $da);
fclose($fp);
?>
And why not to do simple like this:
file_put_contents('numbers.txt', is_writeable('numbers.txt')?((int)file_get_contents('numbers.txt'))+1:exit('Failed to open file'));
Borrowing on Eugene's great one-liner, came up with the following solution.
(Credit goes to go Eugene)
The following code will create the file if it does not exist, and increment by +1 each time it is reloaded.
(Tested)
<?php
$filename = "number.txt";
$filename = fopen($filename, 'a') or die("can't open file");
file_put_contents('number.txt', ((int)file_get_contents('number.txt'))+1);
// To show (echo) the contents of the file, you can use one of the following
// include("number.txt");
// echo file_get_contents('number.txt');
?>
It is because you are setting the write data to the old GET var and not the new set var.
fwrite($fp, $da);
Try using
fwrite($fp, $str);
And also you only need to fopen() once.
$filename = 'number.txt';
$content = (int) file_get_contents($filename);
$content++;
var_dump($content);
file_put_contents($filename, $content);
You have to create that file number.txt and insert there 0 as file content, then your script should work every time.
You are reading the contents into the variable $fgc, but you're trying to use $cont to represent that value, which is uninitialized. So your settype call is going to cast that to 0. Instead, try:
$fgc = file_get_contents('number.txt');
settype($fgc, "integer");

mysql foreach fwrite

I use some code here, transfer mysql query data into json data and write into a file. where is the problem? why the file is zero kb?
while($row = mysql_fetch_array($Query)){
$arr = array ('name'=>$row['name']);
$jsondata = json_encode($arr);
$countfile="data.txt";
if(!file_exists($countfile))
{
fopen($countfile,"w");
}
$fp = fopen($countfile, 'r');
fwrite($fp, $jsondata);
fclose($fp);
}
Several things.
You dont need (and should avoid) to open the file in every iteration
You open the file read-only (r)
At all something like this should do it
$countfile="data.txt";
$fp = fopen($countfile, 'w');
while($row = mysql_fetch_array($Query))
{
$arr = array ('name'=>$row['name']);
$jsondata = json_encode($arr);
fwrite($fp, $jsondata);
}
fclose($fp);
Additional you append separate json structures into the file, what is probably not, what you want. You should first collect all you want to store into one json structure and save it then
$data = array();
while($row = mysql_fetch_array($Query))
{
$data[] = array ('name'=>$row['name']);
}
file_put_contents('data.txt', json_encode($data));
This feels more like what you are probably looking for.
Because you're reopening the file as read only
$fp = fopen($countfile, 'r');
try
$fp = fopen($countfile, 'w'); // to write
or
$fp = fopen($countfile, 'a'); // to append
you could also open the file for writing at the start, append your rows in a variable and then write it all together to the file.
$countfile="data.txt";
$fp = fopen($countfile, 'w');
while($row = mysql_fetch_array($Query))
{
$arr = array ('name'=>$row['name']);
$jsondata .= json_encode($arr) . "\n";
}
fwrite($fp, $jsondata);
fclose($fp);
You are opening the file read-only. You probably want 'w' or 'r+'.
You are opening the file for reading only
$fp = fopen($countfile, 'r');
You also dont need
if(!file_exists($countfile))
{
fopen($countfile,"w");
}
just use:
$fp = fopen($countfile, 'w');

Categories