PHP - PHP Notice: unserialize(): Error at offset in function - php

I have the following PHP function:
function readDataFile_array($dataFileName) {
if (file_exists($dataFileName)) {
$readFile = fopen($dataFileName, 'r');
$previousData = fread($readFile, filesize($dataFileName));
fclose($readFile);
$previousData = unserialize($previousData);
} else {
$previousData = null;
}
return $previousData;
}
I'm getting the following error: PHP Notice: unserialize(): Error at offset 416687 of 416690 bytes
The data to be read by the function is being saved using the following:
function writeDataFile_array($dataFileName, $insertData) {
$insertData = serialize($insertData);
$writeFile = fopen($dataFileName, 'w') or die('Unable to open file!');
fwrite($writeFile, $insertData);
fclose($writeFile);
}
I'm not sure why I'm getting the error that refers to $previousData = unserialize($previousData);

You are f-reading the wrong chunk size.
The EOF seems to be added to the file size.
Try to get the file by using file_get_contents() which is the proper way to read file data.
$previousData = file_get_contents($dataFileName);

Related

PHP fread() other length argument than filesize

I am trying to have PHP read a file to the end, which works perfectly fine, except when the file is empty. Then it throws an error saying:
Uncaught ValueError: fread(): Argument #2 ($length) must be greater than 0`
`strlen()`does not work in this case.
Is there some argument for the length like "read all that is there and if it is empty, just ignore it"? Here is the PHP:
$data_file_read = fopen("data.txt","r");
$alldata = fread($data_file_read,filesize("data.txt"));
fclose($data_file_read);
Get the length of the file into a variable and check that for your length
$filename = "data.txt";
//
// Check file exists first
//
if (file_exists($filename) === true) {
//
// Get file length and check if it is > 0
//
$dataLength = filesize($filename);
if ($dataLength > 0) {
//
// Finally read the data
//
$data_file_read = fopen($filename, "r");
$alldata = fread($data_file_read, $dataLength);
fclose($data_file_read);
}
}

Error on PHP fgets() reading a line of CSV

I am working on this snippet. Why am I getting fgets() error on line 6?
Warning: fgets() expects parameter 1 to be resource, string given in
D:\wamp64\www\WP\wp-content\plugins\test.php on line 6
Code:
<?php
$file = "http://localhost:8080/WP/Data.csv";
function wdm_validate_csv($csv_file)
{
$requiredHeaders = array('title', 'price','color');
$firstLine = fgets($csv_file); //get first line of the CSV file
$fileHeader = str_getcsv(trim($firstLine), ',', "'"); //parse the contents to an array
//check the headers of the file
if ($foundHeaders !== $requiredHeaders) {
// report an error
return false;
}
return true;
}
wdm_validate_csv($file);
As you can see I have a CSV file at this $file = "http://localhost:8080/WP/Data.csv" directory and trying to read it
if you read a file with Url you can use the function file_get_contents(), but if you need to read in the local server change this http://localhost:8080/WP/Data.csv for "./WP/Data.csv" if the php file is in the root directory.
`
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>
`
Using file()[0] will give you the first line of a file.
file() returns a file as an array line by line, and [0] means give me the first line only.
Then I assume it's a typo $fileheaders and $foundheaders?
$file = "http://localhost:8080/WP/Data.csv";
function wdm_validate_csv($csv_file)
{
$requiredHeaders = array('title', 'price','color');
$firstLine = file($csv_file)[0]; //get first line of the CSV file
$fileHeader = str_getcsv(trim($firstLine), ',', "'"); //parse the contents to an array
//check the headers of the file
if ($fileHeader !== $requiredHeaders) {
// report an error
return false;
}
return true;
}
wdm_validate_csv($file);
Assuming you're going to do other stuff with the file after validating its headers, I think it makes sense to open it and pass the resource handle to the function instead of just the path.
$file = fopen("http://localhost:8080/WP/Data.csv");
$valid_headers = wdm_validate_csv($file);
If your CSV is valid, you can combine fgets and str_getcsv into one operation with fgetcsv.
function wdm_validate_csv($csv_file)
{
$requiredHeaders = array('title', 'price','color');
$fileHeader = fgetcsv($csv_file); //get first line of the CSV file
return $fileHeader == $requiredHeaders;
}
file_get_contents and file are great, but they're both going to read the entire file in, which is a bit heavy if you just need to check the first line.
As the error suggests, fgets requires a resource, not a string. Try using file_get_contents instead:
<?php
$file = "http://localhost:8080/WP/Data.csv";
function wdm_validate_csv($csv_file)
{
$requiredHeaders = array('title', 'price','color');
$firstLine = file_get_contents($csv_file); //get first line of the CSV file
$data = str_getcsv(trim($firstLine), ',', "'"); //parse the contents to an array
$foundHeaders = array_key_exists($data[0]) ? $data[0] : null;
//check the headers of the file
if ($foundHeaders !== $requiredHeaders) {
// report an error
return false;
}
return true;
}
wdm_validate_csv($file);

PHP - remove line from a file pointer

How can I remove a line from a file pointer in PHP?
I open the file using fgets() and not with file() because the file is too big.
The actual problem is: I have 2 very big files. I need to remove all lines from file 1 which exist in file 2.
This is the code:
$handle1 = fopen("1.txt", "r+");
$handle2 = fopen("2.txt", "r");
if ($handle2) {
while (!feof($handle2)) {
$buffer2 = trim(fgets($handle2));
if ($handle1) {
while (!feof($handle1)) {
$buffer1 = trim(fgets($handle1));
if($buffer1 == $buffer2)
// stuck here
}
fclose($handle1);
}
}
fclose($handle2);
}
How the line can be removed?
Thanks!

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

Why am I getting a Fatal error with this MongoDB function?

I've got a simple php script for getting a csv file into array and inserting each row into MongoDB (CD Collection). But somehow insert returns an error after first successful one:
"Fatal error: in C:\xampp\htdocs\mongo\lesson1\index.php on line 17"
Here's the code. What could possibly cause such an error? DB receives only one (first).
$filename = 'd:/cd_col.csv'; // Each line: Title;No. of CD with movie
$csvfile = fopen($filename,'rb');
while(!feof($csvfile)) {
$csvarray[] = fgetcsv($csvfile);
}
$m = new MongoClient();
$db = $m->mymovies;
$collection = $db->movies;
$id=0;
foreach($csvarray as $key=>$value)
{
$movie = explode(';', $value[0]);
$fmovie = array('_id'=>++$id, 'title'=>$movie[0], 'cdno'=>$movie[1]);
if($collection->save($fmovie)===true) { // this is line 17
echo 'Successful insert: '.$key;
}
}
SOLVED:
Cannot use save in php, that's it.
You should use $collection->insert(); instead.

Categories