≡ Menu

server side code

Change Linux or UNIX system password using PHP script

If you just wanted to change your own password or other user passwords use passwd command.

I was asked to setup a PHP based interface to change the password. Since my knowledge of php is limited. Here is what I did:

Warning: This is an outdated and insecure information. Please see the official php.net document for more information. You have been warned to ignore this post.

Required tools/setup:

You must have following tools/software installed

=> Shell script to change password

=> Sudo access

=> Apache or Lighttpd web server

=> PHP server side

Step # 1: Setup a shell script to change password

This shell script use expect tool to change the password (see more about expect tool here).

Sample shell script code

# \
exec expect -f "$0" ${1+"$@"}
set password [lindex $argv 1]
spawn passwd [lindex $argv 0]
sleep 1
expect "assword:"
send "$password\r"
expect "assword:"
send "$password\r"
expect eof

You can execute this script as follows (dowload link):
$ chpasswd username password

Download script and copy to your webroot or location where webserver can read this script file:
$ cp chpasswd /var/www/

ALTERNATIVELY, if you are using Ligtttpd web server:
$ cp chpasswd /home/lighttpd

Step # 2: Setup sudo to execute a command as root user

Apache or Lighttpd web server drops root privileges as soon as they go into background. This makes changing password scenario difficult as passwd command needs root privileges to change other user account password.

Typically, Apache 2 use www-data user and Lighttpd use lighttppd username to drop privileges. Login as root user and type the following command:
# visudo

Now allow your web server to execute a script (chpasswd) w/o password. If you are using Apache web server, type the following command:
www-data ALL=NOPASSWD: /var/www/chpasswd

ALTERNATIVELY, if you are using Ligtttpd web server, type the following command:
lighttpd ALL=NOPASSWD: /home/lighttpd/chpasswd

Save and close the file.

Step # 3: Create a PHP based interface

Now you need to write a php script. Here is sample php script. This is a demo script. You should modify it according to your requirement or setup. At minimum, you need to setup correct shell script location so that it will work for you out of box. Open php script and locate line:
$shellscript = "sudo /home/lighttpd/chpasswd";

Change it to point to correct location. PHP Source code:

// change .. me! - shell script name
$shellscript = "sudo /home/lighttpd/chpasswd";
// Make sure form is submitted by user
if(!(isset($_POST['pwdchange']))) {
 // if not display them form
 writeHead("Change password");
else {
 // try to change the password
 // get username and password
 $_POST['username'] = stripslashes(trim($_POST['username']));
 $_POST['passwd'] = stripslashes(trim($_POST['passwd']));
// if user skip our javascript ...
// make sure we can only change password if we have both username and password
 if(empty($_POST['username'])) {
 if(empty($_POST['passwd'])) {
 if ( $callshell == true ) {
  // command to change password 
  $cmd="$shellscript " . $_POST['username'] . " " . $_POST['passwd'];
  // call command
  // $cmd - command, $output - output of $cmd, $status - useful to find if command failed or not
   if ( $status == 0 ) { // Success - password changed
   writeHead("Password changed");
   echo '<h3>Password changed</h3>Setup a new password';
   else { // Password failed 
      writeHead("Password change failed");
      echo '<h3>Password change failed</h3>';
      echo '<p>System returned following information:</p>';
      echo '<p><em>Please contact tech-support for more info! Or try <a href='.$_SERVER['PHP_SELF'].'again</a></em></p>';
 else {
   writeHead("Something was wrong -- Please try again");
   echo 'Error - Please enter username and password';
// display html head
function writeHead($title) {
echo '
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title> ' .$title. '</title>
<style type="text/css" media="screen">
.passwdform {
	position: static;
	overflow: hidden;
.passwdleft {
	width: 25%;
	text-align: right;
	clear: both;
	float: left;
	display: inline;
	padding: 4px;
	margin: 5px 0;
.passwdright {
	width: 70%;
	text-align: left;
	float: right;
	display: inline;
	padding: 4px;
	margin: 5px 0;
.passwderror {
	border: 1px solid #ff0000;
.passwdsubmit {
// display html form
function writeForm() {
echo '
<h3>Use following form to change password:</h3>
function checkForm() {
if (document.forms.changepassword.elements[\'username\'].value.length == 0) {
    alert(\'Please enter a value for the "User name" field\');
    return false;
if (document.forms.changepassword.elements[\'passwd\'].value.length == 0) {
    alert(\'Please enter a value for the "Password" field\');
    return false;
  return true;
<div class="contactform">
<form action="' . $_SERVER[PHP_SELF]. '" method="post" onSubmit="return checkForm()" name="changepassword">
<div class="passwdleft"><label for="lblusername">User Name: </label></div>
<div class="passwdright"><input type="text" name="username" id="lblusername" size="30" maxlength="50" value="" /> (required)</div>
<div class="passwdleft"><label for="lblpasswd">Password: </label></div>
<div class="passwdright"><input type="password" name="passwd" id="lblpasswd" size="30" maxlength="50" value="" /> (required)</div>
<div class="passwdright"><input type="submit" name="Submit" value="Change password" id="passwdsubmit" />
<input type="hidden" name="pwdchange" value="process" /></div>
// display footer 
function writeFoot(){
echo '</body>

Step # 4: Run the script

Point a web browser to your server url - https://mydomain.com/changepassword.php. You should see a username and password form as follows:

changepassword php script output # 1

If a password is changed successfully, you should get confirmation as follows:

changepassword php script output # 2

For some reason if a password failed to change, you should get detailed error message as follows:

changepassword php script output # 3

Step # 5: Security

Note this is an example and not final solution as it is little insecure.

  • Never ever run this script over http session. Always run over https session.
  • Put script in a password protected directory (see how to setup Apache or Lighttpd web server password protected directory).
  • Never ever, trust user input. Above php script is just a sample, for real life production you should consider more powerful user input validation. Discussion regarding PHP programming security is beyond the scope of this article. You can consult a good PHP book or search a web using your favorite search engine :)