0

I need to set multiple virtual host on Ubuntu 16.04,which can create manually.

But i want to do this with php dynamically.For this i have tried to create a file /tmp or in /www directory using a php's fopen function.So i can create a file but unable to move this file to /etc/apache2/sites-available directory using php shell_exec() function.

To move temporarily created file i have used shell_exec(mv temp_file path_to_move);

but command not run via php code.Then i have tried to create file directly in /etc/apache2/sites-available but it shows error Cannot open file

This is my code which i have used

<?php
    $myfile = fopen("example.com.conf", "w");
    $template ='<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>';

    fwrite($myfile, $template );
    fclose($myfile);

    $cmd= 'mv'.$myfile.' /etc/apache2/sites-available';
    shell_exec($cmd);
?>

It create file but move command not works

CyberAbhay
  • 494
  • 6
  • 17

1 Answers1

-1

You don't have a space after the mv command, and I am not sure what value $myfile has after fclose($myfile) but it sure isn't the filename.

With you current code this should work:

$cmd = 'mv example.com.conf /etc/apache2/sites-available';

However you then have the filename hardcoded in two places. Setting it as a variable would be better:

<?php
$filename = 'example.com.conf';
$myfile   = fopen($filename, "w");
$template = '<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>';

fwrite($myfile, $template );
fclose($myfile);

$cmd = 'mv ' . $filename . ' /etc/apache2/sites-available';
shell_exec($cmd);
?>

I haven't tested this, writing it on a Windows PC now, so let me know if this works.

sunomad
  • 1,693
  • 18
  • 23
  • yes it is variable in live code.just for here i have made hardcoded – CyberAbhay May 20 '17 at 10:24
  • btw, besides the command not being the right one, you might also have a permission issue – sunomad May 20 '17 at 10:32
  • cmd is not issue on live.i have space also in live code – CyberAbhay May 20 '17 at 10:33
  • Your code is same as mine.This work when /etc/apache2/sites-available have 777 permission,but i can't kept 777 on live. so i want a way to change 755 to 777 just for this file creation moment and then make it again 777 via php – CyberAbhay May 20 '17 at 10:44
  • most likely a permission rights problem. The script is running from a different user. You need to use sudo, but of course you need to find a way to give a password too. Do the answers on this page help you out with that? http://stackoverflow.com/questions/3173201/sudo-in-php-exec – sunomad May 20 '17 at 10:46