2

How can I touch a file as sudo when using [Symfony's Filesystem][1]?

So far I have:

$fs = new Filesystem();
$confFile = sprintf('/etc/apache2/sites-available/%s.conf', $input->getArgument('name'));
$fs->touch($confFile);

But this code fails with error: Permission denied.

[1]: http://symfony.com/doc/current/components/filesystem/introduction.html

Coding Duchess
  • 6,445
  • 20
  • 113
  • 209
mikelovelyuk
  • 4,042
  • 9
  • 49
  • 95

2 Answers2

1

From the Symfony Filesystem component:

public function touch($files, $time = null, $atime = null)
{
    foreach ($this->toIterator($files) as $file) {
        $touch = $time ? @touch($file, $time, $atime) : @touch($file);
        if (true !== $touch) {
            throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file);
        }
    }
}

As you see there, the touch() method is just a simple wrapper around PHP's buildin touch() function. If you need to run touch with elevated rights via sudo, you have to call it directly:

shell_exec('sudo touch ' . escapeshellarg($file));
Dennis B.
  • 1,567
  • 1
  • 13
  • 20
0

you need to change the rights on /etc/apache2/sites-available/ to add write access to apache user

HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`

sudo chmod +a "$HTTPDUSER allow delete,write,append,file_inherit,directory_inherit" /etc/apache2/sites-available/