5

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

3 Answers 3

16

Yes, you can thanks to PHP CHMOD

// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for that, but when do I put it in my code? Sorry my ignorance! :]
5

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);
?>

Comments

1

Php has chmod, works just like the Linux version.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.