php write file and set permission

空扰寡人 提交于 2020-01-02 17:49:11

问题


I'm trying to create a php file which I can edit straight away without manually set the permissions.

I'm trying this...

<?php

$var = '<?php $mycontent = new Content(); echo $mycontent->block($p_name);?>';

$myFile = "testFile.php";

$fh = fopen($myFile, 'w+') or die("can't open file");

$stringData = $var;

fwrite($fh, $stringData);

fclose($fh);

?>

...it creates the file, but when I try to edit the file in my IDE it won't let me of course. I have to manually set the permission of the file created. Is there any way I can create the file and have the permission already set?

Thanks in advance

Mauro


回答1:


Yes, you can thanks to PHP CHMOD

// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);



回答2:


Since this aspect wasn't covered in previous answers I'll add it here:

chmod() will only take a path string as the 1st argument. So you cannot try to pass to resource that was open with fopen(), in this case $fh.

You need to fclose() the resource and then run chmod() with the file path. So a proper practice would be storing the filePath in a variable and using that variable when calling fopen() rather than passing it a direct string in the first argument.

In the case of the example code in the answer this would simply mean running chmod($myfile, 0755) (the permission code is only an example and be different of course.)

full code after corrections:

<?php

$var = '<?php $mycontent = new Content(); echo $mycontent->block($p_name);?>';

$myFile = "testFile.php";

$fh = fopen($myFile, 'w+') or die("can't open file");

$stringData = $var;

fwrite($fh, $stringData);

fclose($fh);


// Here comes the added chmod:
chmod($myFile, 0755);
?>



回答3:


Php has chmod, works just like the Linux version.



来源:https://stackoverflow.com/questions/5225828/php-write-file-and-set-permission

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!