PHP通过FTP编辑文件

PHP通过FTP编辑文件

问题描述:

Below is a script I am using to modify some files with placeholder strings. The .htaccess file sometimes gets truncated. It's about 2,712 bytes in size before editing and will vary in size after editing depending on the length of the domain name. When it gets truncated, it ends up around 1,400 bytes in size.

$d_parts = explode('.', $vals['domain']);
$ftpstring = 'ftp://' . $vals['username']
        . ':' . $vals['password']
        . '@' . $vals['ftp_server']
        . '/' . $vals['web_path']
;
$stream_context = stream_context_create(array('ftp' => array('overwrite' => true)));

$htaccess = file_get_contents($ftpstring . '.htaccess');
$htaccess = str_replace(array('{SUB}', '{DOMAIN}', '{TLD}'), $d_parts, $htaccess);
file_put_contents($ftpstring . '.htaccess', $htaccess, 0, $stream_context);

$constants = file_get_contents($ftpstring . 'constants.php');
$constants = str_replace('{CUST_ID}', $vals['cust_id'], $constants);
file_put_contents($ftpstring . 'constants.php', $constants, 0, $stream_context);

Is there a bug in file_get_contents(), str_replace(), or file_put_contents()? I have done quite a bit of searching and haven't found any reports of this happening for others.

Is there a better method of accomplishing this?

SOLUTION

Based on Wrikken's response, I started using file pointers with ftp_f(get|put), but ended up with zero length files being written back. I stopped using file pointers and switched to ftp_(get|put), and now everything seems to be working:

$search = array('{SUB}', '{DOMAIN}', '{TLD}', '{CUST_ID}');
$replace = explode('.', $vals['site_domain']);
$replace[] = $vals['cust_id'];
$tmpfname = tempnam(sys_get_temp_dir(), 'config');

foreach (array('.htaccess', 'constants.php') as $file_name) {
    $remote_file = $dest_path . $file_name;
    if (!@ftp_get($conn_id, $tmpfname, $remote_file, FTP_ASCII, 0)) {
        echo $php_errormsg;
    } else {
        $contents = file_get_contents($tmpfname);
        $contents = str_replace($search, $replace, $contents);
        file_put_contents($tmpfname, $contents);
        if (!@ftp_fput($conn_id, $remote_file, $tmpfname, FTP_ASCII, 0)) {
            echo $php_errormsg;
        }
    }
}

unlink($tmpfname);

With either passive of active ftp, I've never had much luck file using the file-family of functions with the ftp wrappers, usually with that kind of truncation problem. I usually just revert to the ftp functions with passive transfers, which do make it harder to switch, but work flawlessly for me.