-1

I'm trying to change the Linux hostname with PHP script. I could do it directly on the Linux machine using the command hostname

But when I use the below PHP Statement .. it didn't work.

system('sudo hostname '.trim($Host));

Please suggest a solution.

Ben Carey
  • 16,540
  • 19
  • 87
  • 169
KiranD
  • 433
  • 2
  • 7
  • 20
  • 3
    I doubt very much that the web server user (apache/www) will have access to call this command, and rightly so. You don't want PHP or web servers to be able to make changes to the system... – fullybaked May 08 '13 at 11:02
  • 1
    Why would you want to change the hostname within PHP? – RMcLeod May 08 '13 at 11:03
  • I'm developing an application which has cpanel features – KiranD May 08 '13 at 11:09

2 Answers2

3

Assuming your Apache user can run sudo commands without entering a password (which, by the way, would be a huge security vulnerability, so please don't do it) you could do this:

exec("sudo hostname " . $hostname);

In order to make sure your www-user can do this, edit /etc/sudoers with the following line:

www-user ALL=NOPASSWD: /bin/hostname

Whatever you're trying to accomplish by changing the hostname, you'll probably find that you can do it another, safer, way. To anyone reading this, I thoroughly do not recommend you follow these instructions, you are opening your server up to potential harm by escalating the priveleges of the www-user account.

Glitch Desire
  • 14,632
  • 7
  • 43
  • 55
  • It's probably that your www-user isn't in `sudoers`. I really don't recommend doing this in a production environment. – Glitch Desire May 08 '13 at 11:11
  • I understand the security issue .. putting it aside.. www-data is added to visudo .. but still it doesn't work. – KiranD May 08 '13 at 11:13
  • Try echoing the output to that command, should give an error if there is one. Does `www-data` have to input password in order to use `sudo` commands? – Glitch Desire May 08 '13 at 11:14
  • In `sudoers`, the user should be specified like: `www-data ALL=NOPASSWD: /bin/hostname` (replace your `hostname` location) -- this way at least your PHP won't have *full* `root` access. – Glitch Desire May 08 '13 at 11:17
  • Excellent.. the issue is solved when I added /bin/hostname to sudoers. Thanks :) – KiranD May 08 '13 at 11:21
0

try this command with the function exec(). http://php.net/manual/de/function.exec.php

Evolutio
  • 976
  • 17
  • 37