作者:天智-孙会军 | 来源:互联网 | 2014-05-13 19:36
系统环境:ubuntu11.10/apache2/php5.3.6
在LAMP环境中,测试一个简单的php文件上传功能时,发现/var/log/apache2/error.log中出现如下php警告:
1.[Tue Jan 31 09:40:27 2012][error] [client 127.0.0.1] PHP Warning: move_uploaded_file(/home/leotody/32883679.jpeg): failed to open stream: Permission denied in /var/www/upload_file.php on line 25, referer: http://localhost/info.html
2.[Tue Jan 31 09:40:27 2012][error] [client 127.0.0.1] PHP Warning: move_uploaded_file(): Unable to move '/tmp/phps05ssU' to '/home/leotody/32883679.jpeg?s=#39; in /var/www/upload_file.php on line 25, referer: http://localhost/info.html
提示没有访问权限,文件上传的代码如下:
1.if (file_exists("upload/". $_FILES["file"]["name"]))
2.{
3.echo $_FILES["file"]["name"]. " already exists. ";
4.}
5.else
6.{
7.if(move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]))
8.{
9.echo "Stored in: ". "upload/". $_FILES["file"]["name"];
10.}
11.else
12.{
13.echo "move error!";
14.}
15.}
页面中显示"move error!",说明move_uploaded_file()函数执行失败。
通过查找资料,发现网上有说是selinux启动的原因,检查系统并未启动selinux,查看upload目录默认权限ls -ld upload,结果为755:
1.drwxr-xr-x 2 root root 4096 2012-01-31 10:59 upload 将upload目录权限改为777,sudo chmod 777 upload,再测试上传功能成功。但这种修改权限的方法并不安全。
故可以改upload目录的拥有者为www-data(即apache)
1.sudo chown -R www-data:www-data upload 然后再测试上传功能成功。
1.drwxr-xr-x 2 www-data www-data 4096 2012-01-31 10:59 upload