2010-11-04 137 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