again. First of all, bear with me, it's late at night, and I'm tired, so this is probably a simple answer...
I'm gathering info on products, one by one, then writing each product as a line in a CSV file. However, I don't want one huge CSV file, so I'm trying to split the files up by size. As each new product is gathered, the script should check whether or not the file it's about to write to is less than the limit. If it is, then it should go ahead and write to that file. If not, then a new file should be created and the product added to the new file.
Here's what I curently have trying to limit the size of the file:
$f = 1;
if(file_exists($shop_path.'items/items'.$f.'.txt'))
{
if(filesize($shop_path.'items/items'.$f.'.txt') >= 512000)
{
$f++;
$fh = fopen($shop_path.'items/items'.$f.'.txt', "a+");
}
else
{
$fh = fopen($shop_path.'items/items'.$f.'.txt', "a+");
}
}
else
{
$fh = fopen($shop_path.'items/items'.$f.'.txt', "a+");
}
if(fwrite($fh, $prod_str) === TRUE)
{
echo 'Done!<br />';
}
else
{
echo 'Could not write to file<br />';
}
fclose($fh);
However, I just keep getting the "Could not write to file" error. Why is this?
fwrite doesnt return a boolean value, only on failure (false).
"fwrite() returns the number of bytes written, or FALSE on error."
Check out: http://hu2.php.net/manual/en/function.fwrite.php
Maybe it works:
if(fwrite($fh, $prod_str))
{
echo 'Done!<br />';
}
else
{
echo 'Could not write to file<br />';
}
Edit:
Or even better:
if(fwrite($fh, $prod_str) !== false)
{
echo 'Done!<br />';
}
else
{
echo 'Could not write to file<br />';
}
The ftell() function will always tell you your current byte offset in a file. Test the value of this before each write, and if it's over your predefined value then you can close that file and open a new one.
Related
I have a form from which I save the given input into a textfile,
but I have trouble reading from the saved file:
while(!feof($fileNotizen)) {
$rawLine = fgets($fileNotizen);
if($rawLine==false) {
echo "An error occured while reading the file";
}
$rawLine seems to be always false, even though I use this function before, to fill the textfile:
function addToTable($notizFile) {
fwrite($notizFile, $_POST["vorname"]." ".$_POST["nachname"]."#");
$date = date(DATE_RFC850);
fwrite($notizFile, $date."#");
fwrite($notizFile, $_POST["notiz"].PHP_EOL);
}
And after I submit the form and get the error message, if I check the textfile, everything is there, so the function works correctly.
If it is of value, I open the file with this command:
$fileNotizen = fopen("notizen.txt", "a+");
Could the problem be that the pointer is already at the end of the file and thus returns false?
$fileNotizen = fopen("notizen.txt", "a+");
a+ opens for read/write but places file pointer AT THE END. So you must fseek() to the beginning first or look into fopen() flags and choose more wisely based on your needs.
Use fseek($fileNotizen, 0, SEEK_SET); to rewind the file.
To read/get content of the file try this function:
function read_file($file_name) {
if (is_readable($file_name)) {
$handle = fopen($file_name, "r");
while (!feof($handle)) {
$content .= fgets($handle);
}
return !empty($content) ? $content : "Empty file..";
} else {
return "This file is not readable.";
}
}
and if you want to see content of the file displayed on separate lines then use <pre></pre> tag like this:
echo "<pre>" . read_file("notizen.txt") . "</pre>";
and if you want to write/add content to the file then try this function:
function write_file($file_name, $content) {
if (file_exists($file_name) && is_writable($file_name)) {
$handle = fopen($file_name, "a");
fwrite($handle, $content . "\n");
fclose($handle);
}
}
and you can use it like this:
$content = "{$_POST["vorname"]} {$_POST["nachname"]}#" . date(DATE_RFC850) . "#{$_POST["notiz"]}";
write_file("notizen.txt", $content);
I have an issue I can't seem to find the solution for. I am trying to write to a flat text file. I have echoed all variables out on the screen, verified permissions for the user (www-data) and just for grins set everything in the whole folder to 777 - all to no avail. Worst part is I can call on the same function from another file and it writes. I can't see to find the common thread here.....
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
if (!$Handle = fopen($File, 'w')) {
return "Cannot open file ($File)";
exit;
}/*
if(!flock($Handle, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain file lock';
exit(-1);
}*/
if (fwrite($Handle, $NewContents) === FALSE) {
return "Cannot write to file ($File)";
exit;
}else{
return $NewContents;
}
}else{
return "<p align=\"center\">There was an issue saving your settings. Please try again. If the issue persists contact your provider.</p>";
}
}
Try with...
$Handle = fopen($File, 'w');
if ($Handle === false) {
die("Cannot open file ($File)");
}
$written = fwrite($Handle, $NewContents);
if ($written === false) {
die("Invalid arguments - could not write to file ($File)");
}
if ((strlen($NewContents) > 0) && ($written < strlen($NewContents))) {
die("There was a problem writing to $File - $written chars written");
}
fclose($Handle);
echo "Wrote $written bytes to $File\n"; // or log to a file
return $NewContents;
and also check for any problems in the error log. There should be something, assuming you've enabled error logging.
You need to check for number of characters written since in PHP fwrite behaves like this:
After having problems with fwrite() returning 0 in cases where one
would fully expect a return value of false, I took a look at the
source code for php's fwrite() itself. The function will only return
false if you pass in invalid arguments. Any other error, just as a
broken pipe or closed connection, will result in a return value of
less than strlen($string), in most cases 0.
Also, note that you might be writing to a file, but to a different file that you're expecting to write. Absolute paths might help with tracking this.
The final solution I ended up using for this:
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
return $NewContents;
}else{
return "<p align=\"center\">There was an issue saving your settings.</p>";
}
}
function WriteNewConfigToFile($File2WriteName, $ContentsForFile){
file_put_contents($File2WriteName, $ContentsForFile, LOCK_EX);
}
I did end up using absolute file paths and had to check the permissions on the files. I had to make sure the www-data user in Apache was able to write to the files and was also the user running the script.
$done=0;
$filename = "raw_urls.txt";
if(! ($fhandle = fopen($filename, "r")))
{ echo "File failed to open";
Exit; }
//
// main loop reads sitemap url list
//
while($url_full_raw = fgets($fhandle,4096))
{
print (mysql_error());
$url_full= preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $url_full_raw);
if(strlen($url_full) > 3)
{
$url_stat++;
// Echo ' tp1 Url from sitemap:',$url_stat,' - ' ,$url_full,'<br>';
$end_st = strlen($url_full)-29;
$s_url= substr($url_full,29,$end_st);
//Echo 'short:',$s_url,'<br>';
$url_full_raw= '';
}
else{
$done++;
Echo '----------- short string ---------------';
}
//
// Check for url
//
$res1=sql("SELECT * FROM `spy3` WHERE `Landingpage` LIKE '%$s_url%' LIMIT 0, 30 ",$o);
if($row=mysql_fetch_array($res1))
{
$lp=$row[6];
$found++;
// Echo '------->Url from sitemap:',$url_full,'<br>';
}
else{
Echo 'Not Found:-> ',$s_url,'<br>';
$nfound++;
}
sql("insert into sitemap (url, stat_url,nf, s_recno)
values (
'$url_full',
'$lp',
'$nfound',
'$url_stat'
)", $o);
print (mysql_error());
$found=0;
$nfound=0;
}
So the code works great. Except for one problem, after about 130 lines, it stops. It exits the program with no error. Yes full error reporting is on. PHP.ini memory is huge.
If I edit the txt file and take out some lines, no difference. I have been working on this for many hours.
Try doing it like they do in their example... with !== false. i.e,
while(($url_full_raw = fgets($fhandle,4096))!==false) {
I'm guessing your content is evaluating to false for whatever reason. That just happens to be at 130 lines (throw the 130 lines into a text file and see if the file size is close to 4 KB).
Also, you might want to fix your formatting for next time. Makes it very hard for us to read and help you.
I have been working on this for days, I thought I had it but was wrong.
$done=0;
$filename = "raw_urls.txt";
if(! ($fhandle = fopen($filename, "r")))
{ echo "File failed to open";
Exit; }
while((fscanf($fhandle, "%s\n",$url_full))!== false)
{
print (mysql_error());
if(strlen($url_full) > 3)
{
$url_stat++;
$end_st = strlen($url_full)-29;
$s_url= substr($url_full,29,$end_st);
}
else{
$done++;
}
$res1=sql("SELECT * FROM `spy3` WHERE `Landingpage` LIKE '%$s_url%' LIMIT 0, 30 ",$o);
if($row=mysql_fetch_array($res1))
{
$lp=$row[6];
$found++;
}
else{
$nfound++;
}
sql("insert into sitemap (url, stat_url,nf, s_recno)
values (
'$url_full',
'$lp',
'$nfound',
'$url_stat'
)", $o);
print (mysql_error());
$found=0;
$nfound=0;
}
?>
I have tried fgets, changed txt files, it always stops between 128 and 132 lines of text. There are 2500 lines in the text file. Php.ini memory is very big. If I cut the txt file where it stops and save it, its 9k big.
have seen this link..?
Please Click here
OR
you can also use fseek($handle, 0); AND refer this link
Thanks.
I've been struggling with writing a single string into a file.
I'm using just a simple code under Slackware 13:
$fp = fopen('/my/absolute/path/data.txt', 'w');
fwrite($fp, 'just a testing string...');
fclose($fp);
The file gets created (if it's not already created) but it's empty ?!
The directory in which this file is written is owned by apache's user & group (daemon.daemon) and has 0777 permissions.
This has never happened to me before. I'm curious what's the reason I'm not able to write inside the file ?
Thanks in advance.
Try $ df -h
It probably means your disk is full.
In my opinion you could check the return values:
$fp = fopen('/my/absolute/path/data.txt', 'w');
// $fp -> manual: "Returns a file pointer resource on success, or FALSE on error."
if ($fp) {
$bytes_written = fwrite($fp, 'just a testing string...');
if ($bytes_written) {
echo "$bytes_written bytes written!\n";
} else {
echo "Error while writing!\n"
}
$success = fclose($fp);
if ($success) {
echo "File successfully closed!\n";
} else {
echo "Error on closing!\n";
}
} else {
echo "No filepointer ressource!\n";
}
I suggest using file_put_conents($file_name, $file_cotents);
And to retrieve content: file_get_contents($file_name);
Code looks cleaner too.
http://php.net/manual/en/function.file-put-contents.php and
http://www.php.net/manual/en/function.file-get-contents.php
Could be something is happening to the script/file before the file is closed. Check if there are any other processes that try to access the file (you can use lsof). Also try writing to a new file to see if the same thing occurs.
Also, check the return value on fclose() to make sure the file is being closed successfully.