0
<?
if(isset($_POST['Submit']))
{
   $password=$_POST['newpwd'];
   if(!empty($password))
   {
    $old_file = "password.txt";
    chmod($old_file,0777);
    $fh = fopen($old_file, 'w') or die("Can't open file");
    fwrite($fh,$password);
    fclose($fh);
    header("location:index.php");
  }
  else
  {
    echo "Please enter a valid password!";
  }
}
?>

Above code is used to reset the password. I am getting error "Can't open file" when change the password. Also the chmod operation is not working. The file permission is given below:

-rwxr-xr-x 1 root root    4 Mar  5 13:55 password.txt

I have tried unlink to delete the text file, it also failed.

The above code is working when I delete the text file manually, and then set the file permission to 777.

Any help should be appreciated!

Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43
NewPHP
  • 608
  • 2
  • 15
  • 28
  • 3
    You can't `chmod` a file if you have insufficient permission on it or its directory to begin with. Do so via FTP/SSH beforehand. Also `file_put_contents()` for brevity. – mario Mar 05 '13 at 23:37
  • 1
    your webserver probably is not running as root, and root is the only one with write permissions. And why are you storing a password plaintext in a txt file? – Green Black Mar 05 '13 at 23:39
  • 1
    If you delete the file manually, then run this script, who has permissions on password.txt? – landons Mar 05 '13 at 23:43

1 Answers1

2

The script is owned by root and is writable by the owner only. This means than no one else than root can change its permissions. You'll have to sudo chown or sudo chmod and change the owner or the permissions of the file manually.

Tchoupi
  • 14,560
  • 5
  • 37
  • 71
  • @landons actually the script owner doesn't matter. PHP would have to be run as root on the command line or apache would have to be run under root for access to write the file. The scripts owner has nothing to do with the scripts permissions or the account it is run under. – Jonathan Kuhn Mar 05 '13 at 23:46
  • @landons I assumed that PHP doesn't run as root. It would be insane. – Tchoupi Mar 05 '13 at 23:49
  • I misunderstood what you were saying by "The script is owned by root" – landons Mar 05 '13 at 23:49