Add PHP GD support on a Linux server with Plesk

Posted on in Categories Apache, php, Troubleshooting last updated October 11, 2006

PHP is one of the popular web programming languages.

The Plesk software package is a commercial web hosting automation software. It allows to setup set up new websites, email accounts, and DNS entries through a web-based interface.

The php gd package contains a dynamic shared object that will add support for using the gd graphics library to PHP. If users are using popular CMS software such as WordPress, you need GD support.

Adding GD graphic libraries support to php is quite easy job w/o breaking Plesk software.

Red Hat Enterprise Linux

Type following two command as root user:
# up2date php-gd
# /etc/init.d/httpd restart

Cent OS or Fedora Core Linux

Type following two command as root user:
# yum install php-gd
# /etc/init.d/httpd restart

Verify that php gd support loaded

Type any one of the following command:
# php -m | less
# php -m | grep gd

You can also use phpinfo() to verify that php gd loaded and working perfectly.

Now, your web server should up and runing php with GD 🙂

Shell Scripting: Generate or Print Range of Numbers ( Sequence of Numbers for Loop )

Posted on in Categories FreeBSD, Gentoo Linux, Howto, Linux, php, programming, Shell scripting, Tips, Troubleshooting, Ubuntu Linux, UNIX last updated September 26, 2006

One our reader asks:

How do I generate a range of numbers under BASH for loop command? For example, I need to run particular command inside loop 100 or 500 times. Basically I want function that counts FROM and TO a range of numbers like 50-10.

Lighttpd web server and php eAccelerator cache problem

Posted on in Categories lighttpd, Linux, php, Troubleshooting last updated August 29, 2006

eAccelerator is a fork of MMCache which provide an opcode cache and encode i.e. it increases performance of php based application by providing web (content) caching for dynamic apps.

Recently one of Linux box, which runs Lighttpd, started to sever php pages very slowly. First, I thought server might be severing large amount of request but netstat just return over 600 connection:
$ netstat -vtn | wc -l

Output:

649

System load was under control:
$ uptime
Output:

12:09:32 up 87 days, 11:58,  1 user,  load average: 1.08, 1.19, 1.06

No zombie process were found. Next I had gone through server logs and error logs and found nothing special. I did restarted both Lightttpd and MySQL servers. Memory usage was under control. HTML pages was loading fine, it was php application. All php based application was taking time to load (but no connection time out error). It was clear something was wrong with PHP.

So I started to investigate all php related installed extension. I found eAccelerator installed on system. I went to /chroot/var/cache/php-eaccelerator and I found over 5000+ files.

I had just deleted all cached files and voila! My problem was solved php started to work normally:
# rm -f *
# /etc/init.d/lighttpd restart

I guess now I need to write a script that will delete cahce on regular basis.

Tutorial: MySQL Connection Management and caching in PHP

Posted on in Categories MySQL, php, Tuning last updated August 8, 2006

Jay Pipes writes about MySQL Connection Management and caching in PHP.

This small tutorial will help you understand the MySQL Connection Management and caching in PHP.

FTA, “This article is intended to highlight various basic topics concerning proper methods of handling connections to MySQL databases in PHP, guidelines for caching dynamic content, and a technique called “lazy loading”. Hopefully by the end of the article you’ll have learned how to combat a very widespread and potentially devastating scalability problem seen in an enormous number of PHP web applications

Read more at jpipes

On a related note MySQL Performance Blog also covers caching techniques such as:

  • TTL Based Caching
  • Cache Invalidate
  • Cache Update
  • Version based caching

Change Linux or UNIX system password using PHP script

Posted on in Categories Apache, lighttpd, php, Shell scripting last updated August 3, 2006

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

#!/bin/sh
# \
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:

<?php
// 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");
 writeForm();
 writeFoot();
}
else {
 // try to change the password
 $callshell=true;
 // 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'])) {
   $callshell=false;
 }
 if(empty($_POST['passwd'])) {
   $callshell=false;
 }
 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
   exec($cmd,$output,$status);
   if ( $status == 0 ) { // Success - password changed
   writeHead("Password changed");
   echo '<h3>Password changed</h3>Setup a new password';
   writeFoot();
   }
   else { // Password failed
      writeHead("Password change failed");
      echo '<h3>Password change failed</h3>';
      echo '<p>System returned following information:</p>';
      print_r($output);
      echo '<p><em>Please contact tech-support for more info! Or try <a href='.$_SERVER['PHP_SELF'].'again</a></em></p>';
      writeFoot();
   }
 }
 else {
   writeHead("Something was wrong -- Please try again");
   echo 'Error - Please enter username and password';
   writeForm();
   writeFoot();
 }
}
 
// display html head
function writeHead($title) {
echo '
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<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 {
}
</style>
 
</head>
 
<body>';
 
}
// display html form
function writeForm() {
echo '
<h3>Use following form to change password:</h3>
 
<script>
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;
}
</script>
 
<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>
</form>
</div>
';
 
}
// display footer
function writeFoot(){
echo '</body>
</html>
';
}
?>

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 🙂

How to deal with common PHP database problems

Posted on in Categories php, Troubleshooting last updated August 3, 2006

Jack Herrington shows us how to fix the common problem. I never used php PEAR DB package, the idea sounds good.

FTA, “Discover five common database problems that occur in PHP applications — including database schema design, database access, and the business logic code that uses the database — as well as their solutions.

You can create database design, database access, and the PHP business logic code that sits on top of it in any number of ways, and you often end up getting it wrong. This article illustrates five common problems in database design, in the PHP code that accesses databases, and how to fix these problems when you see them…”

Read more at IBM developerworks

Zend Framework PHP (based object-oriented) howtos

Posted on in Categories Howto, php last updated July 29, 2006

Zend Framework based on PHP and it is object-oriented stuff.

A couple of years ago, PHP sat at the top of the powerful-but-easy-to-use scripting languages heap — at least as far as popularity was concerned. It was installed on most UNIX and Linux-based Web servers. And if you were a programmer, it was easy to get a hosting account that would let you use it. Ruby had been around for quite some time, but not many people were using it. If you wanted to build a Web site using dynamically generated content, but you weren’t sure that you needed to go so far as to use an application server like J2EE, you would very likely use PHP. It was fast, easy to learn, convenient, and you didn’t have to learn Perl.

These howtos will help you to kick start development with Zend Framework 🙂

How to secure the data in your PHP applications with PHP encryption

Posted on in Categories Open source coding, php last updated July 26, 2006

PHP encryption for the common man (read as newbie)

FTA, “…In this increasingly virtual online world, you have to be careful to protect your data. Learn the basics of encoding and encrypting important bits of information, such as passwords, credit card numbers, and even entire messages. Get an overview of what it means to encrypt and decrypt information, as well as some practical examples involving passwords and other data, using PHP’s built-in functionality.

Fast-forward to today and encryption is everywhere. Passwords are stored encrypted in databases. Encrypted tunnels through cyberspace are possible via SSL, SSH, and other technologies — not to mention virtual private networks. Everyday people can and do use Pretty Good Privacy (PGP) to armor their sensitive files and e-mail.

As a PHP developer, you should be aware that strong security practices aren’t just for exotic applications — they’re for the project you’re working on now. This awareness runs from the pedestrian (such as not showing plaintext in a password field on a login page) to dizzying heights of cryptographic methods (such as DES, MD5, SHA1, Blowfish)….

Read more at IBM developerworks

Lighttpd PHP fastcgi configuration

Posted on in Categories Howto, lighttpd, Linux, Networking, php, RedHat/Fedora Linux, Suse Linux, Sys admin, Ubuntu Linux, UNIX last updated July 7, 2006
Lighttpd logo

FastCGI is a language independent, scalable, open extension to CGI that provides high performance without the limitations of server specific APIs. FastCGI provides better scalability and performance. Instead of creating a new process (the CGI program) for every request, FastCGI uses a single persistent process which handles many requests over its lifetime. (See wikipedia article for more information)

Make sure php support fastcgi

Type any one of the following command to verify that php support fastcgi
$ php -v

Output:

PHP 5.0.4 (cli) (built: Nov  8 2005 08:27:12)
Copyright (c) 1997-2004 The PHP Group
Zend Engine v2.0.4-dev, Copyright (c) 1998-2004 Zend Technologies

OR
$ php-cgi -v
Output:

PHP 5.0.4 (cgi-fcgi) (built: Nov  8 2005 08:25:54)
Copyright (c) 1997-2004 The PHP Group
Zend Engine v2.0.4-dev, Copyright (c) 1998-2004 Zend Technologies

You must get string cgi-fcgi. Next find out full path to php-cgi or php binary:
$ which php-cgi
Output:

/usr/bin/php-cgi

Open lighttpd configuration file:
# vi /etc/lighttpd/lighttpd.conf

First add the module mod_fastcgi (lighttpd provides an interface to a external programs that support the FastCGI interface via this module). Make sure your server.modules loades mod_fastcgi:

server.modules              = (
            "mod_access",
            "mod_accesslog",
            "mod_fastcgi",
            "mod_rewrite",
            "mod_auth"
)

Now add following lines to configuration:

fastcgi.server = ( ".php" => ((
                     "bin-path" => "/usr/bin/php-cgi",
                     "socket" => "/tmp/php.socket"
                 )))

Save the configuration and close all the files. Restart the lighttpd:
# /etc/init.d/lighttpd restart

Test your configuration by running php program or application.

See also