2010-11-04 136 views
2

下面是一个脚本,我用它来修改一些带有占位符字符串的文件。 .htaccess文件有时会被截断。在编辑之前它的大小约为2,712字节,编辑后的大小会根据域名的长度而有所不同。当它被截断时,它的大小约为1,400字节。PHP通过FTP编辑文件

$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); 

是否有file_get_contents()str_replace(),或file_put_contents()一个错误?我已经做了相当多的搜索,并没有发现其他人发生这种情况的任何报告。

有没有更好的方法来完成这个?

SOLUTION

基于Wrikken的反应,我开始使用文件指针与ftp_f(被|放),但结束了零名长度的文件被写回。我停止使用文件指针,并切换到ftp_(获得|放),现在一切似乎工作:

$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 ([email protected]_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 ([email protected]_fput($conn_id, $remote_file, $tmpfname, FTP_ASCII, 0)) { 
      echo $php_errormsg; 
     } 
    } 
} 

unlink($tmpfname); 
+0

该文件的截断版本是什么样的? – 2010-11-04 17:03:07

+0

@Pekka - 它只是缺少文件的最后部分。我有几行'AddType'声明和截断通常结束于其中一行的中间。 – Sonny 2010-11-04 17:06:11

回答

2

随着被动主动FTP的,我从来没有使用文件,家里有多少运气文件与ftp包装函数一起,通常具有这种截断问题。我通常只是回到ftp functions与被动转移,这使得它更难切换,但完美地为我工作。

+0

您是否有get-> edit-> put类型的过程的示例代码? – Sonny 2010-11-04 17:08:42

+1

使用'tempnam'作为临时文件,'ftp_fget',改变临时文件中的数据,当你完成时使用'ftp_fput'就可以了。 – Wrikken 2010-11-04 17:11:02

+0

我现在正在尝试。 – Sonny 2010-11-04 17:33:34