在PHP中为动态创建的文件赋予777权限

21

嗨,我有一个脚本,它在我的本地目录中动态地创建了一个文件。 请告诉我如何立即给予该文件777权限,因为在浏览器中无法访问它。

<?php
//Get the file
$content = 'http://xxx.xxx.com.mx/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/b/r/bridal-shoes1.jpg ';
$content1 = explode('/', $content);
$end = end($content1);
echo $end;
//print_r($content1[12]);
//Store in the filesystem.
$my_file = $end;
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //implicitly creates file
$path = '/var/www/'.$end;

copy($content, $path);

 ?>

我只是把这个链接放在这里:http://php.net/manual/zh/function.chmod.php。只需在您的文件上使用它。 - Najzero
3
重要警告:0777权限允许拥有该文件路径的任何人打开、修改或执行文件内容。0777是一个巨大的安全风险,你应尽可能避免需要它。你并不需要使用0777权限仅仅为了浏览器读取文件。0644应该可以很好地完成工作。 - Charles
@Charles 假设我是一名开发人员,需要将调试日志写入文件。 我考虑将其设置为777。即使在这种情况下,仍然存在风险吗? - Gherman
7个回答

50
使用chmod函数
chmod
$fp = fopen($file, 'w');
fwrite($fp, $content);
fclose($fp);
chmod($file, 0777); 

如果我们在目录中没有写入权限,那么chmod命令还能起作用吗? - Ahmed Ali

3
使用chmod()函数来设置文件权限。

2

使用:

private function writeFileContent($file, $content){
   $fp = fopen($file, 'w');
   fwrite($fp, $content);
   fclose($fp);
   chmod($file, 0777);  //changed to add the zero
   return true;
}

2

授权动态创建的文件

                  $upPath = yourpath;
                    if(!file_exists($upPath)) 
                    {
                        $oldmask = umask(0);
                        mkdir($upPath, 0777, true);
                        umask($oldmask);
                    }  

0

我们甚至可以忽略 *$handle* 它仍然会创建该文件并将内容复制到 $path

 <?php
    //Get the file
    $content = 'http://dev.aviesta.com.mx/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/b/r/bridal-shoes1.jpg ';
    $content1 = explode('/', $content);
    $end = end($content1);
    echo $end;
    //print_r($content1[12]);
    //Store in the filesystem.
    $my_file = $end;
    $handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //implicitly creates file
    $path = '/var/www/'.$end;

    copy($content, $path);

     ?>

0

您可以使用chmod()来完成此操作。

例如:chmod($my_file, 0777);


0

使用 setfacl 命令 将您的目录(即 rwx)设置为默认权限。

ex: setfacl -d -m o::rwx your/directory/path

然后,您在该目录中创建的任何内容都将具有rwx权限。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接