PHP中chmod设置0655返回无效值问题求助
问题:PHP设置chmod为0655后实际权限变为1217的原因
原代码
<?php $file = "/tmp/testfile2.txt"; $source = "text"; // substr(decoct(fileperms($file)), -4) // 用于获取当前文件权限 // 如果文件不存在,默认设置chmod为0655 $chmod = (is_file($file) ? substr(decoct(fileperms($file)), -4) : '0655'); echo "save chmod variable : $chmod\n"; if(file_put_contents($file, $source)){ // 写入成功则执行 echo "now executing chmod : $chmod\n"; chmod($file, $chmod); clearstatcache(); // 清除状态缓存 $chmod = substr(decoct(fileperms($file)), -4); echo "new chmod variable value : $chmod\n"; }else{ echo "fail"; }
实际执行输出
save chmod variable : 0655 now executing chmod : 0655 new chmod variable value : 1217
原因分析
PHP的chmod()函数第二个参数要求传入八进制整数,但你这里传的是字符串'0655'。PHP会自动将字符串转换为十进制整数处理,十进制的655转换成八进制就是1217(计算过程:655 = 1×8³ + 2×8² + 1×8 +7 = 512+128+8+7),所以最终文件被设置的是这个八进制对应的权限。
解决方案
你需要确保传给chmod()的是八进制格式的数值,有两种方式:
- 直接使用八进制整数:把
'0655'改成0655(注意前面的0,PHP中以0开头的整数表示八进制) - 把字符串转换成八进制整数:使用
octdec('0655')转换后再传入
修正后的代码示例
<?php $file = "/tmp/testfile2.txt"; $source = "text"; // 如果文件不存在,默认设置chmod为八进制0655 $chmod = is_file($file) ? substr(decoct(fileperms($file)), -4) : 0655; echo "save chmod variable : $chmod\n"; if(file_put_contents($file, $source)){ echo "now executing chmod : " . decoct($chmod) . "\n"; chmod($file, $chmod); clearstatcache(); $chmod = substr(decoct(fileperms($file)), -4); echo "new chmod variable value : $chmod\n"; }else{ echo "fail"; }
内容的提问来源于stack exchange,提问作者Anas
相关产品推荐
相关产品推荐

