【題目】PHP的is_writeable()函數存在Bug,無法準確判斷一個目錄/檔案是否可寫,請寫一個函數來判斷目錄/檔案是否絕對可寫。
【等級】六級
【解決】 以下是CodeIgniter 中的is_really_writable函數解決方案,詳見函數註解
其中bug存在兩方面,
1.在windowns中,當檔案只有唯讀屬性時,is_writeable()函數才會傳回false,當傳回true時,該檔案不一定是可寫的。
如果是目錄,在目錄中新建檔案並透過開啟檔案來判斷;
如果是文件,可以透過開啟文件(fopen),來測試文件是否可寫入。
2.在Unix中,當php設定檔中開啟safe_mode時(safe_mode=on),is_writeable()同樣不可用。
讀取設定檔是否safe_mode是否開啟。
<code><span>/** * Tests for file writability * * is_writable() returns TRUE on Windows servers when you really can't write to * the file, based on the read-only attribute. is_writable() is also unreliable * on Unix servers if safe_mode is on. * *<span> @access</span> private *<span> @return</span> void */</span><span>if</span> ( ! function_exists(<span>'is_really_writable'</span>)) { <span><span>function</span><span>is_really_writable</span><span>(<span>$file</span>)</span> {</span><span>// If we're on a Unix server with safe_mode off we call is_writable</span><span>if</span> (DIRECTORY_SEPARATOR == <span>'/'</span><span>AND</span> @ini_get(<span>"safe_mode"</span>) == <span>FALSE</span>) { <span>return</span> is_writable(<span>$file</span>); } <span>// For windows servers and safe_mode "on" installations we'll actually</span><span>// write a file then read it. Bah...</span><span>if</span> (is_dir(<span>$file</span>)) { <span>$file</span> = rtrim(<span>$file</span>, <span>'/'</span>).<span>'/'</span>.md5(mt_rand(<span>1</span>,<span>100</span>).mt_rand(<span>1</span>,<span>100</span>)); <span>if</span> ((<span>$fp</span> = @fopen(<span>$file</span>, FOPEN_WRITE_CREATE)) === <span>FALSE</span>) { <span>return</span><span>FALSE</span>; } fclose(<span>$fp</span>); @chmod(<span>$file</span>, DIR_WRITE_MODE); @unlink(<span>$file</span>); <span>return</span><span>TRUE</span>; } <span>elseif</span> ( ! is_file(<span>$file</span>) <span>OR</span> (<span>$fp</span> = @fopen(<span>$file</span>, FOPEN_WRITE_CREATE)) === <span>FALSE</span>) { <span>return</span><span>FALSE</span>; } fclose(<span>$fp</span>); <span>return</span><span>TRUE</span>; } }</code>
以上就介紹了is_writeable函數bug問題,包含了面向的內容,希望對PHP教學有興趣的朋友有幫助。