2013-04-21 27 views
0

幫助朋友解決他遇到的問題。他的網站使用fopen函數來打開文件並保存更改,但fopen失敗並顯示「權限被拒絕」錯誤。該文件位於遠程服務器上,權限似乎是正確的。PHP fopen不起作用,儘管文件檢查可寫

他正在使用的代碼是...

if (isset($_POST['save'])) { 
$filepath = "string.txt"; 
    if (file_exists($filepath)) { 
     $file = fopen($filepath, "w+"); 
     fwrite($file, $_POST['save']); 
     fclose($file); 
    } 
} 

我用VolkerK的代碼在這裏php fopen returns false but file is readable/writable以確定讀/寫權限,並得到以下。

PHP Version: 5.4.9
Uname: Windows NT
{File} exists
{File} is readable
{File} is writable
Last error: array(4){["type']=>int(2)["message"]=>string(131 "fopen({file}):failed to open stream: Permission denied.

起初我還以爲是文件權限問題,但我認爲,如果該文件是由PHP視爲寫這應該不是問題,我沒看錯?

+0

在win7上快速測試,這對我很有用。該文件寫入$ _POST變量的內容。嘗試使用新的* .txt文件。 – Daniel 2013-04-21 08:19:16

+0

你說文件在遠程服務器上,可能是['allow_url_fopen'](http://us2.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen)_might_是假的 - 儘管我不確定這會是什麼問題,但值得注意的是。除此之外,代碼按原樣運行,所以我們需要在遠程服務器上使用更多的上下文,並使用'$ filepath'。 – Jon 2013-04-21 08:35:38

+0

如果它是一個遠程文件,你使用什麼協議? – Uby 2013-04-21 09:33:46

回答

0

嘗試FTP併到達那裏。必須正確設置FTP連接的上下文選項。

感謝您指點我正確的方向。

if (isset($_POST['save'])) { 
//Setup FTP connection 
$ftp = "ftp://user:[email protected]/filepath/filename.txt"; 
//Set FTP Options 
$stream_options = array('ftp' => array('overwrite' => true)); 
$stream_context = stream_context_create($stream_options); 
//Open file and write changes 
if (file_exists($ftp)) { 
    $file = fopen($ftp, "w", 0 , $stream_context); 
    fwrite($file, $_POST['save']); 
    fclose($file); 
    } 
}