Black
Black

Reputation: 20282

Laravel - Create file with specific user, group and permissions

I try to create a file by using put and give the file the permission 777.

If I create the File like this:

use File;

...

$content = "<?php echo 'test'; ?>";
$file   = app_path() . '/Http/Controllers/test.php';
File::put($file, $content);

However, the file is created with this rights:

-rw-r--r-- 1 daemon daemon 2,2K Mär 14 08:08 test.php

Also the user and group is daemon instead of root.

How can I create a file with user and group root and with permissions rwxrwxrwx ?

e.g.

-rwxrwxrwx 1 root root 2,2K Mär 14 08:08 test.php

I also added these lines to my /etc/sudoers

www-data ALL=(ALL) NOPASSWD: /bin/chmod 
www-data ALL=(ALL) NOPASSWD: /bin/chown
www-data ALL=(ALL) NOPASSWD: /bin/chgrp

But I still get chmod(): no permission with the following code:

File::chmod($unitPath, 0777);
chown($unitPath,"root");
chgrp($unitPath,"root");

Upvotes: 2

Views: 3925

Answers (2)

Black
Black

Reputation: 20282

I solved it by using shell_exec()

shell_exec('sudo chmod 0777 '. $unitPath);
shell_exec('sudo chown root:root '. $unitPath);

Make sure that www-data is allowed to execute the commands by entering these lines in the file /etc/sudoers.

www-data ALL=(ALL) NOPASSWD: /bin/chmod 
www-data ALL=(ALL) NOPASSWD: /bin/chown

Important! Always use visudo to edit /etc/sudoers otherwise you can easily make syntax errors and corrupt the file and loose the possibilty to use sudo, and you need to fix your system by booting from a live cd.

Upvotes: 1

Shady Atef
Shady Atef

Reputation: 2401

Laravel has built-in support for changing mod

ex:

File::chmod($file,0755); //the leading zero is a must

Unfortunately it doesn't has chown in its Filesystem module, but you can call the php one

chown($file,"root");

to change the group

chgrp($file,"group");

Note that : changing group and owner will fail if you're not a super user, even if you can sudo.

Upvotes: 5

Related Questions