Home > Article > Backend Development > is_writeable function bug problem
[Title] PHP's is_writeable() function has a bug and cannot accurately determine whether a directory/file is writable. Please write a function to determine whether the directory/file is absolutely writable.
【Level】Level 6
[Solution] The following is the solution to the is_really_writable function in CodeIgniter. Please see the function comments for details
The bug exists in two aspects,
1. In windows, when the file only has a read-only attribute, the is_writeable() function returns false. When it returns true, the file is not necessarily writable.
If it is a directory, create a new file in the directory and judge by opening the file;
If it is a file, you can test whether the file is writable by opening the file (fopen).
2. In Unix, when safe_mode is turned on in the php configuration file (safe_mode=on), is_writeable() is also unavailable.
Read the configuration file to see if safe_mode is turned on.
<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>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });
The above introduces the is_writeable function bug problem, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.