Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php fwrite() doesn't finish writing string data to file, why?

Tags:

php

fopen

fwrite

I'm trying to write a sizable chunk of data to a file that is opened via fopen() in php. The protocol wrapper I'm using is ftp, so the file is remote to the server running the php code. The file I'm writing to is on a Windows server.

I verified that the file does, in fact, get created by my php code, but the problem is that the data within the file is either non-existant (0KB) or writing to the file stops prematurely. Not sure why this is the case.

Here is the code I am using for handling the operation:

$file_handle = fopen($node['ftp'].$path_to_lut, "wb", 0, $node['ftp_context']);
include_once($file);

if ($file_handle)
{
     fwrite($file_handle, $string);  //$string is inside included $file
     fclose($file_handle);
} else {
     die('There was a problem opening the file.');
}

This code works fine when I host it on my local machine, but when I upload it to my webhost (Rackspace Cloud), it fails. This leads me to believe it's an issue related to the configuration of the my server at Rackspace, but want to know if there is anything I can do to my php code to make it more robust.

Any ideas to ensure fwrite actually finishes writing the string to the remote machine?

Thanks!

Okay, I changed the code that writes to the file like so:

if ($file_handle)
{
    if ($bytesWritten = fwrite($file_handle, $string) ) {
        echo "There were " . $bytesWritten . " bytes written to the text file.";
    }

    if (!fflush($file_handle)) {
        die("There was a problem outputting all the data to the text file.");
    }

    if (!fclose($file_handle)) { 
        die("There was a problem closing the text file."); 
    }

} else {

    die("No file to write data to.  Sorry.");

}

What is strange is that the echo statement shows the following:

There were 10330 bytes written to the text file.

And yet, when I verify the text file size via FTP it shows it to be 0K and the data inside the file is, in fact, truncated. I can't imagine it has to do with the FTP server itself because it works if the PHP is hosted on a machine other than the one on Rackspace Cloud.

** UPDATE ** I spoke to a Rackspace Cloud rep who mentioned that they require passive ftp if you're going to ftp from their servers. I setup the remote server to handle passive ftp connections, and have verified that passive ftp now works on the remote server via the OSX Transmit ftp client. I added:

ftp_pasv($file_handle, true);

Right after the fopen() statement, but I get an error from PHP saying the I didn't provide a valid resource to ftp_pasv(). How can I ensure that the connection to the ftp site that PHP makes is PASV and not ACTIVE and still use fwrite()? Incidentally, I've noticed that the Windows machine reports that the file being written by my PHP code is 4096 bytes on disk. It never gets beyond that amount. This led me to change the output_buffering php value to 65536 just to troubleshoot, but that didn't fix the issue either. . .

** UPDATE PART DUEX **

Troubleshooting the problem on the my virtual server on the Rackspace Cloud Sites product was proving too difficult because they don't offer enough admin rights. I created a very small cloud server on Rackspace's Cloud Server product and configured everything to the point where I'm still seeing the same error with fwrite(). To make sure that I could write a file from that server to a remote server, I used basic ftp commands within my bash shell on the cloud server. It worked fine. So, I assume that there is a bug within the php implementation of fwrite(), and that it is probably due to some type of data throttling issue. When I write to the remote server from my local environment which has a slow upspeed compared to what is offered on the Rackspace Cloud server, it works fine. Is there any way to effectively throttle down the speed of the write? Just askin' :)

** UPDATE PART III *

So, I took the suggestion from @a sad dude and implemented a function that might help somebody trying to write to a new file and send it off in its entirety via ftp:

function writeFileAndFTP($filename=null, $data=null, $node=null, $local_path=null, $remote_path=null)
{

    //  !Determin the path and the file to upload from the webserver
    $file = $local_path.'/'.$filename;


    //  !Open a new file to write to on the local machine
    if (!($file_handle = fopen($file, "wb", 0))) { 
        die("There was a problem opening ".$file." for writing!");
    }


    //  !Write the file to local disk
    if ($bytesWritten = fwrite($file_handle, $data) ) {
        //echo "There were " . $bytesWritten . " bytes written to " . $file;
    }

    //  !Close the file from writing
    if (!fclose($file_handle)) {
        die("There was a problem closing " . $file);
    }

    //  !Create connection to remote FTP server
    $ftp_cxn = ftp_connect($node['addr'], $node['ftp_port']) or die("Couldn't connect to the ftp server.");

    //  !Login to the remote server
    ftp_login($ftp_cxn, $node['user'], getPwd($node['ID'])) or die("Couldn't login to the ftp server.");

    //  !Set PASV or ACTIVE FTP
    ftp_pasv($ftp_cxn, true);


    //  !Upload the file
    if (!ftp_put($ftp_cxn, $remote_path.'/'.$filename, $file, FTP_ASCII)) {
        die("There was an issue ftp'ing the file to ".$node['addr'].$remote_path);  
    }

    //  !Close the ftp connection
    ftp_close($ftp_cxn);

}
like image 845
ariestav Avatar asked Feb 27 '12 22:02

ariestav


People also ask

How do I know if PHP fwrite is successful?

fwrite() returns the number of bytes written, or FALSE on error. Check whether fwrite() returns false and you'll know that the write succeeded. Be careful to use the === comparison operator instead of the == operator when checking if the returned value is false.

Does fwrite overwrite?

fwrite() does not exactly overwrite by using fseek(). Instead, there are several cases: if the open permissions was 'r' then writing is an error.

Where does fwrite write to?

The fwrite() writes to an open file. The function will stop at the end of the file (EOF) or when it reaches the specified length, whichever comes first.

Does fwrite write in binary?

fwrite(obj,A,' precision ') writes binary data with precision specified by precision . precision controls the number of bits written for each value and the interpretation of those bits as integer, floating-point, or character values. If precision is not specified, uchar (an 8-bit unsigned character) is used.


1 Answers

The length of the string fwrite can write in one go is limited on some platforms (which is why it returns the number of bytes written). You can try running it in a loop, but a better idea is to simply use file_put_contents, which guarantees that the whole string will be written.

http://www.php.net/manual/en/function.file-put-contents.php

like image 104
a sad dude Avatar answered Sep 28 '22 10:09

a sad dude