ds3464 2010-11-04 17:01
浏览 54
已采纳

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);
  • 写回答

1条回答 默认 最新

  • duanpeng1532 2010-11-04 17:06
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?