Jon Lyles's notes on Linux, PHP, CakePHP, PEAR, Pyrus, Apache, and MySQL

This blog is about C++, CakePHP, Linux, PEAR, PHP, Pyrus, Apache, and MySQL and related topics.

Saturday, November 21, 2009

How To Create Name-Based Virtual Hosts In Apache If You Are Using WAMP

This article will show you how to create name-based virtual hosts (vhosts) in Apache if you are running Apache as your web server on a Windows machine using Wampserver 2.0i (WAMP). (Wampserver installation is very easy!)


If you would like a more in-depth discussion of virtual hosts, refer to Apache Virtual Host Documentation


If you are using the Zend Framework and/or Ubuntu you may prefer to follow this article: Appendix A. Creating A Local Domain Using Apache Virtual Hosts from Surviving the Deep End!,a free book about the Zend Framework for the PHP language


Virtual hosts lets us create new domains for each project and removes the need to maintain everything as a set of subdirectories under localhost. 1


Step 1: Edit httpd.conf


In the httpd.conf file, located at c:\wamp\bin\apache\apache2.2.11\conf\httpd.conf, locate the following line and make sure it is uncommented, meaning there is no '#' at the beginning of the line. This is how it should look:
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
Step 2: Edit httpd-vhosts.conf

The httpd-vhosts.conf file is located at c:\wamp\bin\apache\apache2.2.11\ conf\extra\httpd-vhosts.conf
Here is a sample httpd-vhosts.conf file:
# Setup Listening Port
NameVirtualHost *:80

# Ensure "localhost" is preserved
<VirtualHost *:80>
    ServerName localhost
    DocumentRoot "C:\wamp\www"
</VirtualHost>

# Setup "helloworld" Virtual Host
<VirtualHost *:80>
    ServerName helloworld.tld
    DocumentRoot "C:\projects\helloworld\public"

    <Directory "C:\projects\helloworld\public">
        Options Indexes FollowSymLinks Includes
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>
Explanation:


Any line that begins with '#' is ignored by Apache. This is a comment-line.


The NameVirtualHost directive specifies the IP-address (and possibly the port) that will be accepting requests for the hosts. '*' is a wild-card meaning that any and all IP-addresses on the web-server should be used. The colon ':' separates the IP-address from the port number. '80' means the web-server will accept requests on port 80.


Next, there are two <VirtualHost> blocks, one for each domain. The argument for the <VirtualHost> directive should be the same as the argument to the NameVirtualHost directive (ie, an IP address, or * for all addresses). Inside each <VirtualHost> block, you will need at minimum a ServerName directive to designate which host is served and a DocumentRoot directive to show where in the filesystem the content for that host lives.


If you are adding virtual hosts to an existing web server, you must also create a <VirtualHost> block for the existing host. The ServerName and DocumentRoot included in this virtual host should be the same as the global ServerName and DocumentRoot. List this virtual host first in the configuration file so that it will act as the default host.2


For the first block we are just making sure that localhost (existing host discussed above) is preserved:

# Ensure "localhost" is preserved
<VirtualHost *:80>
    ServerName localhost
    DocumentRoot "C:\wamp\www"
</VirtualHost>
 In the second <VirtualHost> block we create the "helloworld" virtual host:




# Setup "helloworld" Virtual Host
<VirtualHost *:80>
    ServerName helloworld.tld
    DocumentRoot "C:\projects\helloworld\public"

    <Directory "C:\projects\helloworld\public">
        Options Indexes FollowSymLinks Includes
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>


The final part is to add a Directory configuration for the new Virtual Host's Document Root. This ensures Apache can serve requests from this directory by supplying appropriate permissions. Apache will not serve files from a directory without the correct access permissions. By default, options are severely limited to prevent unauthorised access from the web, so be sure to add this to allow files to be served from the Document Root. The options I'm using here are the usual ones Apache applies to localhost's Document Root which are fairly liberal and allow for the use of .htaccess files so users can access Apache configuration options at runtime.3>


Step 3: Configuring the Local HOSTS file.


The new domain must also be 'mapped' to the correct local IP. This is easily resolved by adding the new domain name to the local HOSTS file which recognises and maps local domains to IP addresses


In Windows this file is located at  C:\Windows\System32\drivers\etc\hosts


This is what the file looks like:




# Copyright (c) 1993-2006 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

127.0.0.1       localhost
127.0.0.1       helloworld.tld 
Sources:






Apache Virtual Host Documentation http://httpd.apache.org/docs/1.3/vhosts/


Apache Name-Based Virtual Hosts
http://httpd.apache.org/docs/1.3/vhosts/name-based.html


Footnotes:
1 and 3 :From "Creating A Local Domain Using Apache Virtual Hosts"


2. From "Using Name-based Virtual Hosts"

Wednesday, October 28, 2009

Why I Chose Notepad++ As My Primary Source Code Editor For PHP, HTML, and CSS

I have been using Notepad++ for several months now for writing code. The main reasons why I like Notepad++ are:


  • learning curve almost zero
  • it is free
  • very convenient if you have multiple open files 
  • supports many programming and markup languages
And this is only scratching the surface of what Notepad++ can do and of the accolades it has received from developers.

Wikipedia article: http://bit.ly/UUqxO
Website: http://bit.ly/3ED7wa

How To Install Smarty Template Engine WampServer (Extended Setup)

This article will show how to an extended setup of Smarty with WampServer. This article is a modified version of Extended Setup on Smarty's website and is a continuation of How To Install Smarty Template Engine WampServer (Basic Installation) which is modified from the Basic Installation on Smarty's website.


Step One: Create an 'includes' folder at c:\wamp\bin\php\php5.3.0\includes\


Step Two: Create a folder for the application inside the includes folder. The folder name should be the same as your application name. So if your application is called 'guestbook' then name the folder 'guestbook'.


Step Three: Modify include_path in php.ini to find new 'includes' folder.


Step Four: Create a file called setup.php which will go in c:\wamp\bin\php\php5.3.0\includes\guestbook\


Cut and paste the following code:




<?php
//load Smarty library
require('Smarty.class.php');

// The setup.php file is a good place to load
// required application library files, and you
// can do that right here. An example:
// require('guestbook/guestbook.lib.php');

class Smarty_GuestBook extends Smarty {

   function Smarty_GuestBook()
   {

        // Class Constructor.
        // These automatically get set with each new instance.

$path = $_SERVER['DOCUMENT_ROOT'];

        $this->Smarty();

        $this->template_dir = $path.'guestbook/templates/';
        $this->compile_dir  = $path.'guestbook/templates_c/';
        $this->config_dir   = $path.'guestbook/configs/';
        $this->cache_dir    = $path.'guestbook/cache/';

        $this->caching = true;
        $this->assign('app_name', 'Guest Book');
   }

}
?>


I modified this code from the setup.php code on the Extended Setup page. The main difference being the $path variable set to $_SERVER['DOCUMENT_ROOT'] to make setting the path easier.




Step Five: Create the directory structure for our application


First we create a folder named after the application in the document root: c:\wamp\www\guestbook\


Then we create four subfolders inside the guestbook folder: cache, configs, templates, templates_c




Step Six: Create the index.tpl file inside c:\wamp\www\guestbook\templates\


Place the following code inside:






{* Smarty *}

Hello {$name}, welcome to Smarty!

Step Seven: Create the index.php file inside c:\wamp\www\guestbook\

Place the following code inside:
<?php
require('guestbook/setup.php');
$smarty = new Smarty_GuestBook();
$smarty->assign('name','Ned');
$smarty->display('index.tpl');
?>
Step Eight: Test

Open the browser go to http://localhost/guestbook/index.php

If you see the following:
Hello Ned, welcome to Smarty!





Then congratulations you have installed Smarty on WampServer doing it the Extended Setup way!




Tuesday, October 27, 2009

How To Install Smarty Template Engine WampServer (Basic Installation)

This article will show how to install the Smarty Template Engine with WampServer.

This article is a modified version of the Basic Installation Instructions found on Smarty's website.

Once you understand the basic installation you can try the Extended Setup article which is a modified version of the Extended Installation Instructions found on Smarty's website.

This is my setup:
  • Windows XP SP3
  • WampServer 2.0i
    • -Apache 2.2.11
    • -MySQL 5.1.36
    • -PHP 5.3.0
  • Smarty 2.6.26
  • Notepad++

Table of Contents

Here is an ordered list of each step needed to complete our tutorial:
  1. Get WampServer
  2. Get Smarty
  3. Create Smarty/libs
  4. Modify php.ini
  5. Restart Apache
  6. Test
  7. Make application folder
  8. Make Smarty directories
  9. Make index.tpl
  10. Make index.php
  11. Test
Step One: Get WampServer:

This tutorial assumes that you have already installed WampServer.

Step Two: Get Smarty:

Download Smarty at http://www.smarty.net/download.php - Download the most recent .zip file.

Right click the .zip file select 'Extract All' the .zip file and you will have a folder that should have a name similar to Smarty-X.X.X, in my case it is named Smarty-2.6.26









Inside Smarty-2.6.26 there are two sub-folders called 'demo' and 'libs' as well as several files.




Step Three: Create Smarty 'libs' folder

Go to your PHP folder. (If you installed WampServer using the default configuration then your PHP folder should be at c:\wamp\bin\php\php5.3.0\ )

Create a folder called Smarty. Now copy Smarty's 'libs' folder and paste it into the Smarty folder we just created.

I could have placed the libs folder at c:\www\{application-name}\libs but "to avoid any security concerns, it is recommended (but not mandatory) to place these directories outside of the web server's document root"1 

The file structure should look like this:

c:\wamp\bin\php\php5.3.0\Smarty\libs\internals\      <this is a directory>
c:\wamp\bin\php\php5.3.0\Smarty\ libs\plugins\        <this is a directory>
c:\wamp\bin\php\php5.3.0\Smarty\libs\Config_File.class.php
c:\wamp\bin\php\php5.3.0\Smarty\ libs\debug.tpl
c:\wamp\bin\php\php5.3.0\Smarty\ libs\Smarty.class.php
c:\wamp\bin\php\php5.3.0\Smarty\ libs\Smarty_Compiler.class.php

Step Four: Modify php.ini

Next we need to edit include_path in php.ini. The php.ini file is located at c:\wamp\bin\apache2.2.11\bin\php.ini . Scroll down to the section called 'Paths and Directories'. Find the include_path. There are two include paths. One for UNIX and one for Windows. Notice how the include_path under UNIX starts with a semi-colon. The semi-colon at the beginning of a line will cause that line to be ignored. If you see a semi-colon at the beginning of the include_path for windows, remove it.  You can add multiple include_paths, seperated by semi-colons.

If this is the first and only path then the include_path directive should look something like this:

include_path = ".;c:\wamp\bin\php\php5.3.0\Smarty\libs".
If there already is a value then add a semi-colon at the end of the last path and then add the new path. Like this:
include_path = ".;c:\wamp\bin\php\php5.3.0\pear;c:\wamp\bin\php\php5.3.0\Smarty\libs"
Notice how the first value has a dot and a semi-colon preceding it and the second value is only preceded by a semi-colon.

Here is a screenshot of how my php.ini looks like after the change.





Step Five: Restart Apache

After you save the php.ini file. Restart Apache for the changes to take effect.



To verify the include_path has been updated open your browser to http://localhost/. You should be on the WampServer Configuration Page.



About a quarter page down click on phpinfo(). This brings you to the PHP configuration page. Do a 'Ctrl-F' and search for 'include_path'.



Do you see the path you just put in the php.ini file? If you don't see it then go back and check the following:

  • Did you edit the right php.ini file? Make sure. There's more than one php.ini file. (The php.ini located at c:\bin\php\php5.3.0\php.ini is not the right file!)
  • Did you save the php.ini file? Very easy to check. Open the file and look if your change is still there.
  • Did you enter the path correctly?  (right path? / correct spelling?)
Step Six: Test

Before going further we should test that php.ini is finding Smarty. So let's create a simple webpage that will call the Smarty.class.php and see what happens. Open a text editor. Notepad will do (Start>All Programs>Accessories>Notepad). I am using Notepad ++ .

Here is the code for the page:

<html>
<head>
<title>Smarty test</title>
</head>
<body>
<?php
// NOTE: Smarty has a capital 'S'
require_once('Smarty.class.php');
$smarty = new Smarty();
?>
<p>If this is all you see then the test passed. If you see an error saying Smarty.class.php could not be found then go to 'http://www.smarty.net/manual/en/installing.smarty.basic.php' and troubleshoot the problem.</p>
</body>
</html>

Just copy the code and paste it in a text file and save this text file as 'c:\wamp\www\smarty_test.php'.

Open your browser and type this address in the address window:  http:\\localhost\smarty_test.php.

If you see an error, go back and make sure you followed each step correctly.

Step Seven: Make Application Folder:

If the test passed then we move on to the next step which is to create a folder for the application. The name of the folder should be the same as the name of our application. The application folder should be located in the document root. The location of the document root can be verified by looking at our PHP configuration page which is accessed by going to http://localhost/ then clicking on phpinfo(). Then do a search for 'DOCUMENT_ROOT'.

The directory structure should look like this:
  • c:\wamp\www  (this is your document root)
  • c:\wamp\www\application-name
Step Eight: Make Smarty Directories:

After the application folder is set up it is time to create the Smarty directories:
  • c:\wamp\www\application-name\templates
  • c:\wamp\www\application-name\templates_c
  • c:\wamp\www\application-name\configs
  • c:\wamp\www\application-name\cache
Step Nine: Test


Let's do a test to make sure everything is working fine. We'll just grab the code of Smarty's page for this one.

Create a new file called index.tpl inside the 'templates' folder. Place the following code inside this file:
{* Smarty *}
Hello {$name}, welcome to Smarty!
Create a new file called index.php inside the 'application-name' folder. Place the following code inside this file:

<?php

require_once(SMARTY_DIR 'Smarty.class.php');

$smarty = new Smarty();

$smarty->template_dir 'templates';
$smarty->compile_dir  'templates_c';
$smarty->config_dir   'configs';
$smarty->cache_dir    'cache';

$smarty->assign('name','Jonathan');

//** un-comment the following line to show the debug console
//$smarty->debugging = true;

$smarty->display('index.tpl');

?>

If everything goes as planned you should see the following on the screen:

Hello Jonathan, welcome to Smarty!

VoilĂ ! You have successfully installed Smarty with WampServer




Sunday, October 25, 2009

How To Install PEAR Services_Recaptcha-0.2.1

In this blog post I will show you how I installed PEAR Services_Recaptcha-0.2.1.

This is my setup:

  • Windows XP SP3
  • WampServer 2.0i
    • PHP version 5.3.0
    • Apache version 2.2.11
    • MySQL version 5.1.36
  • PEAR version 1.9.0
If you want to have a setup like mine just follow the instructions here. I have also explained How To Install PEAR with PHP 5.3.0 for those who don't want to install WampServer.

This is what we have to do:

  1. Load the pear console
  2. Login to the pear channel
  3. Services_Recaptcha-0.2.1 requires HTTP_Request2-0.4.1 which in turn requires Net_URL2-0.2.0 so we will install in this order: Net_URL2-0.2.0, HTTP_Request2-0.4.1, then Services_Recaptcha-0.2.1
  4. Test it is working
Step One: Load the pear console
Step One can be further broken down into two steps:

  1. Open the windows command line
  2. Switch to the PHP directory
1: Open the Command Prompt (also known as DOS and cmd.exe).
This is one way of doing it:

  • click start
  • click run
  • type cmd.exe in the 'open' field
  • click ok or press enter
The Command Prompt should now load and this is what it looks like:



2: Switch to the PHP directory.

This is the directory where php.exe is located. If you installed WampServer using default configurations then you will probably be going here: c:\wamp\bin\php\php5.3.0


On the command line type the following: cd c:\wamp\bin\php\php5.3.0

The prompt should now look like this c:\wamp\bin\php\php5.3.0




At this point it would be good to verify everything is going ok. Type 'pear' (without quotes) and hit enter. A list of pear commands should load.

This is what it looks like:




If this does not happen then check the following:


  • Did you spell pear correctly? This is the most obvious mistake so rule this one out first.
  • Are you in the right directory? Type 'dir' and a list of files should load. You know you are in the right directory if you see the following files:
    • php.exe
    • php.ini
    • pear.bat
    • PEAR 
    'PEAR' is a directory and not a file, but it should be there just the same.
  • Did you install PEAR (or did you install it correctly)? Go back and do it again

Step Two:  Login to the pear channel
At the prompt just type the following: pear login





  • Select '1' and enter a username
  • Select '2' and enter a password
  • Review and hit enter if everything is ok.
  • You are logged in

Step Three: Installations

 It's as simple as typing these three commands in succession:


  • pear install pear/Net_URL2-0.2.0
  • pear install pear/HTTP_Request2-0.4.1
  • pear install pear/Services_Recaptcha-0.2.1
The error messages are very helpful here. You can use them to verify which versions you should be installing. For example if you type 'pear install Services_Recaptcha' you will get an error telling you which version to install and which channel to install it from. Also if you type 'pear install pear/Services_Recaptcha-0.2.1' first you will get an error message telling you HTTP_Request2-0.4.1 should be installed and 'pear install pear/HTTP_Request2-0.4.1' will give you an error message that Net_URL2-0.2.0 should be installed.

It would also be a good idea to check http://pear.php.net to make sure you are installing the most recent version of Services_Recaptcha and its dependencies.

Step Four: Test it is working

To test it is working we will use some test code. Just cut and paste the following code and save as recaptcha.php and put this file in your DocumentRoot (c:\wamp\www if you installed WampServer with default configuration)

 This code comes from: http://code.google.com/p/services-recaptcha/wiki/RecaptchaExample2

Here is the code:



<?php

/**
 * Include the Services_ReCaptcha class
 */
require_once 'Services/ReCaptcha.php';

// you must get your API keys here:
// http://recaptcha.net/api/getkey
$publicKey  = 'your_public_key';
$privateKey = 'your_private_key';

// we instanciate our Services_ReCaptcha instance with the public key and the 
// private key
$recaptcha = new Services_ReCaptcha($publicKey, $privateKey);

// we are going to customize our Services_ReCaptcha instance
$recaptcha->setOption('secure', true);   // force the secure URL
$recaptcha->setOption('theme', 'white'); // use the white theme
$recaptcha->setOption('lang', 'fr');     // set language to french

// alternatively we could have done:
// $recaptcha = new Services_ReCaptcha($publicKey, $privateKey, true, array(
//     'secure' => true,
//     'theme'  => 'white',
//     'lang'   => 'fr'
// ));
// or:
// $recaptcha->setOptions(array('secure' => true, 'theme' => 'white', 'lang' => 'fr'));

// we use a proxy, so we need to configure it
$recaptcha->getRequest()->setConfig(array(
    'proxy_host' => 'localhost',
    'proxy_port' => 8118,
));

// if the form was submitted
if (isset($_POST['submit'])) {
    if ($recaptcha->validate()) {
        // the catpcha challenge response is ok, we display a message and exit
        echo "Challenge response ok !";
        exit(0);
    } else {
        // if the captcha validation failed, instead of letting the captcha 
        // display the error, we want to echo the error and exit
        echo $recaptcha->getError();
        exit(1);
    }
}

// we display the html form
?>
<html>
<head>
    <title>recaptcha test</title>
</head>
<body>
    <form method="post" action="">
<?php echo $recaptcha; ?>
        <hr/>
        <input type="submit" name="submit" value="Ok"/>
    </form>
</body>
</html>


Get the Recaptcha Keys


Next we go to  http://recaptcha.net/api/getkey and get a public and private key to insert into the script (around lines 10-11). For development purposes make global keys. In other words, we don't intend to use these keys in the real world and we don't want to set up new keys more than once for development purposes.

Load the page into your browser. This is what you should see:



That's it! You have successfully installed PEAR package Services_Recaptcha-0.2.1

Friday, October 23, 2009

How To Install PEAR With WampServer 2.0i

My last post described how to install PEAR with PHP 5.3.0 on a Windows XP machine.

Here, I will describe how I was able to get PEAR running with WampServer 2.0i

I like WampServer because it is the easiest way to install PHP, MySQL, and Apache on a Windows machine. Just go to the WampServer site, download and install the file. That's it.

Once it is installed if you want to add PEAR. This is what to do:

Note: I used the default folders when installing WampServer so if you want to follow me exactly then use the default folders. Otherwise, make note of your folders and make the necessary adjustments.

1. Go to this page and copy the content and create a file called go-pear.php. Save this file in the following directory: c:\wamp\bin\php\php5.3.0

2. Open the command line. Switch to the php directory (the one that has php.exe in it).

cd c:\wamp\bin\php\php5.3.0

3. Type this command:

pear.php go-pear.php

4. Answer the installation questions. You might see a lot of warnings concerning deprecated methods. This is normal.

5. Update php.ini. This is the key to getting this right. There are two php.ini files. They are:

C:\wamp\bin\php\php5.3.0\php.ini
C:\wamp\bin\apache\Apache2.2.11\bin\php.ini

The phpinfo() page says the loaded configuration file is C:\wamp\bin\apache\Apache2.2.11\bin\php.ini but change I made to c:\wamp\bin\php\php5.3.0\php.ini were reflected on this page. Instead of figuring out which to use I decided to update both.

Do this to both php.ini files:

Open the php.ini file in any text editor. Notepad will do. In the "Paths and Directories" section find this line:;

Windows: "\path1;\path2"

Change the next line to the following:

include_path = ".;c:\wamp\bin\php\php5.3.0\pear"

Be certain to remove the ';' at the beginning of the line if one is present.

Save and close file.

Now it's time to verify if PEAR is properly installed. <--This article will show you how to do that.

How To Install PEAR With PHP 5.3.0 On A Windows machine

When PHP 5.3.1 is finally released we'll be able to use Pyrus to install PEAR and this should be a lot easier than it is now to install PEAR.

You've come to the right place if you are trying to install PEAR on a Windows XP machine to run with PHP 5.3.0 and are getting frustrated because you can't get it to work.

This is how you do it.

Step 1: Download and install PHP . If you will be using Apache webserver then do not choose VC9, choose VC6. Download the installer for V6 86x Thread Safe or V6 86x Non Thread Safe. If you would like to know what the difference between Thread Safe and Non Thread Safe, click here.

Step 2: Download go-pear from http://pear.php.net/go-pear and safe the file as go-pear.php and save in your PHP directory. I used c:\PHP.

Step 3: From the command prompt (Windows > Start > All Programs > Accessories > Command Prompt ), change the directory to the php directory. Note: the prompt is after '>' and the part before '>' is your current directory.

c:\> cd php
c:\php>

Once we are in the correct directory type the following

php go-pear.php

Installation should begin. Just answer the questions and be sure to update the php.ini

PEAR should be working now.

Followers