1

I am trying to dynamically edit and update my /etc/hosts using the below php code

$string_Data = 'It works success!!';
$file_To_Edit = "/etc/hosts";
exec("sudo chmod 777 /etc/hosts");
$opened_File = file($file_To_Edit) or die("Error. Code:2 - Can not open file $file_To_Edit");
$lines = preg_grep(' /test.com/', $opened_File);
   foreach(array_keys($lines) as $key) {
       $opened_File[$key] = substr($opened_File[$key], 0, -1) . $string_Data;
  }
$f = fopen($file_To_Edit, 'w') or die("Error $file_To_Edit"); 
fwrite($f, implode("\n", $opened_File)); 
fclose($f);

Can anyone tell me where am i going wrong, since i am not able to update the /etc/hosts file.

1
  • I think you need run this script as root and something like exec("sudo chmod 777 /etc/hosts"); is security issue IMHO Commented Nov 21, 2013 at 10:18

2 Answers 2

1
//suppose you are in  /var/www/html/website/

$currentdir=getcwd();  // it will save your current directory location    

chdir('../../../../etc/');  // it will change your web directory( /var/www/html/website/)  to etc directory (/etc/)

$file='hosts';
$current=file_get_contents($file);
$string_Data = 'It works success!!';
$current.=$string_Data;
if(file_put_contents($file, $current))
{
echo "success in writing";
}
else
{
echo "fail in writing";
}

chdir("$currentdir"); // it will change directory (/etc/) to your web directory( /var/www/html/website/ )

//change permission before run php page because if your user don't have permission this code can't do writing
Sign up to request clarification or add additional context in comments.

2 Comments

I wish someone who down votes would provide explanation why this is wrong. Obviously the poster put thought into it and it worked for him, now I have to trial and error to see if it works?
@vaibhav your code is working for such directory which does not need administrative rights. But for host file editing you need administrative rights to open host file or change chdir('../../../../Windows/System32/drivers/etc/'); directory. Can help me which code I can use to access '/etc/' location for windows?
1

You need root rights to modify /etc/hosts file

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.