Sunday, October 14, 2012

Getting Started with PHP

Because of PHP's popularity and capabilities it is available on a multitude of platforms and supports the use of a variety of databases, both relational and the newer NoSQL. Many of these servers and database systems are also free. So it can be said that there are not many barriers to getting started with PHP.
Detailed instructions for many combinations can be found here. I'll illustrate installing on my Windows 7 laptop, using information from this site http://windows.php.net .
To run PHP on the command line, one only needs to install PHP, but to see PHP Web pages requires a Web server and doing realistic programming requires a database. I'm going to use Apache as my Web server. Apache is probably the most popular open source Web server.
(You should familiarize yourself with all the pages pertaining to the options for your platform, BEFORE installing anything.)
Install the Web server first. That way, the installation of PHP itself will make some of the necessary modifications to the Apache configuration automatically.
Apache 2.2
Following the instructions at Apache's Web site for Windows installation http://httpd.apache.org/docs/2.2/platform/windows.html, download and run “Win32 Binary including OpenSSL” 0.9.8t (MSI Installer): httpd-2.2.22-win32-x86-openssl-0.9.8t.msi.
Apache's download site
Apache's download site
The installation wizard will ask for your new server's domain and name. These are values you choose for your installed Apache – it's how you will address your pages in the browser. Also enter the administrator's email address. The installer uses these values to configure Apache (unfortunately the Windows installer doesn't actually complete the configuration). Also, select to run Apache as a service for all users on port 80 and then select the “Typical” installation. By installing as a service, Windows will start Apache for me and place an icon in the system tray.
Configuration
The two important things Apache needs to know is how to listen for HTTP requests and where it will find the requested scripts/pages.
Configuration of Apache can be very complex, because of all the possible scenarios for Web server deployment, but defaults will work for basic purposes. Fortunately, where you have to configure the product is centrally located within the installation directory. The main files we're concerned with are httpd.conf and extra/httpd-vhosts.conf.
apache config
Apache installs its important files clearly organized. conf and logs will become familiar.
Important:
When editing configuration files on Windows 7, you need to launch an editor as administrator first, then open the files from the editor. To do so, right click on the program's icon and select “Run as administrator”.
Using these instructions on Apache's Web site, I set up the information about the directory that will contain Web content. In httpd.conf, uncomment the line that includes the vhosts file:
1.# Virtual hosts
2.Include conf/extra/httpd-vhosts.conf
and make sure that Listen is set to port 80
in extra/httpd-vhosts.conf make sure NameVirtualHost is set to *:80 and add the following sections (ServerName refers to the same domain name you chose in the installation wizard):
01.<VirtualHost *:80>
02.DocumentRoot "C:/path/to/your/web/files"
03.ServerName your.server.name
04.</VirtualHost>
05. 
06.<Directory "C:/path/to/your/web/files">
07.Options FollowSymLinks
08.Order deny,allow
09.Allow from all
10.</Directory>
The last step is to tell Windows in C:\Windows\System32\drivers\etc\hosts by adding
1.127.0.0.1        your.server.name
Just like the Apache files, the Windows hosts file must be edited as an administrator to be able to save it. Now, restart the Apache service (using the icon in the system tray), and for good measure, refresh Windows' information by opening a command prompt and typing >ipconfig /flushdns
Create a new directory called public inside your web directory (the one we put in VirtualHost and Directory). Save the following as index.html
01.<!DOCTYPE html>
02.<html>
03.<head>
04.<title>Plain HTML</title>
05.</head>
06.<body>
07.<p>Apache can serve static HTML files without PHP</p>
08.</body>
09.</html>
Open your browser and type your.server.name/public/index.html
static html)
Apache can serve static HTML files (and supporting CSS and Javascript, since they are requested by the browser, also
The reason we create a public folder is to separate pages and scripts that may be directly requested in the browser from PHP and other files that we want to protect from public access. We can put PHP scripts in the includes directory and protect them from being requested through HTTP with file permissions.
Congratulations, you have a Web server.
Apache keeps its logs, called access.log and error.log, in its installation directory, inside the logs directory. I keep these files open in my browser under separate tabs. You can actually see the response for your index.html request in the access log.
1.127.0.0.1 - - [03/Jul/2012:12:20:14 -0600] "GET /public/index.html HTTP/1.1" 200 161
If you have problems, stop Apache using the icon in the system tray, open a command prompt, go to Apache's bin directory and run httpd.exe. This will print out diagnostics associated with possible configuration errors.
PHP
For the recommended version of PHP (http://windows.php.net/downloads/releases/php-5.3.13-Win32-VC9-x86.msi) to go along with Windows 7 and Apache 2.x, I had to go the release archives link texthttp://windows.php.net/downloads/releases/archives/. Note that we don't want any version that contains "-nts-" in the name – that's "not thread safe".
Start the .msi file. When it prompts for the Web server information, pick “Apache 2.2.x Module” and browse to the Apache configuration directory, conf, Apache's httpd.conf will automatically updated so it loads PHP.
PHP web server
PHP can run a variety of Web servers. The installer will configure PHP based on the server in use and its location
Select XSL along with the default options.
PHP options
Leave the defaults and add XSL support
Configuration
If you open the Apache httpd.conf file, you see that PHP added a section at the bottom.
Find the file php.ini in the PHP installation directory. Make a copy of it so we can make the following changes (in Windows 7 make sure you run the editor as administrator and open files from the program.) There should be a section near the top of the file called "Quick Reference" that recommends various settings. Most of the defaults will be fine, and it's important that the following values are used for development. Feel free to redirect the error_log anywhere convenient.
1.allow_call_time_pass_reference = Off
2.display_errors = On
3.display_startup_errors = On
4.error_reporting = E_ALL
5.html_errors = On
6.log_errors = On
7.magic_quotes_gpc = Off
8.error_log = "C:\Windows\temp\php-errors.log"
These are not all the same settings we would use in production. For instance, the errorreporting() function allows one to decide what warnings and errors will be reported to a very fine-grained level. Many of the settings can be changed within a running script using iniset(), also. It can be useful to redirect the log, for instance, based on a particular project. By using ini_set() in personal configuration files, a project can be more easily shared by developers.
Add this to a file in your public directory, making sure the filename ends in “.php”, and view it in the browser (your.server.name/public/filename.php).
01.<!DOCTYPE html>
02.<html>
03.<head>
04.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
05.<title>phpinfo output</title>
06.</head>
07.<body>
08.<?php
09.phpinfo();
10.?>
11.</body>
12.</html>
PHP info output
phpinfo() dumps out a lot without any arguments. Try phpinfo(INFO_CONFIGURATION +INFO_MODULES +INFO_VARIABLES) to filter out some of the noise.
phpinfo() produces a lot of output, but it can be filtered using an optional flags argument. Find and remember the include_path setting. Change the source PHP in filename.php
1.<?php
2.$docroot = $_SERVER['DOCUMENT_ROOT'];
3.set_include_path($docroot . '/includes' . PATH_SEPARATOR  . get_include_path());
4.phpinfo();
5.?>
By adding the Web directory to PHP's include_path we won't have to specify the full path to files that we want to include.
$SERVER is one of PHP's “superglobals”; we can always count on these variables containing important information about the environment or specific request. In this case we asked for its 'DOCUMENTROOT' which returns the Web directory of the current script – based on the Apache server configuration. PATHSEPARATOR is a built in PHP constant that lets this code be platform independent.
We can print the $_SERVER array to see the information that's available for scripts to access.
1.print_r ($_SERVER);
Server array
It's difficult to inspect large arrays in the browser.
While print_r() is effective for showing small arrays in the browser, it's not formatted for easily reading anything large or complex. It's usually better to send the output to the error log for readability reasons and so as not interfere with actual Web page output we want to see. To do that, use the error_log() function to send the output to the log, and add an optional argument of true to print_r()
1.error_log (print_r ($_SERVER, true));
And open the php-error.log file in the browser to see a nicely formatted display of the array
01.[03-Jul-2012 22:31:56 UTC] Array
02.(
03.[HTTP_HOST] => vaio.web.gwp
04.[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1
05.[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
06.[HTTP_ACCEPT_LANGUAGE] => en-us,en;q=0.5
07.[HTTP_ACCEPT_ENCODING] => gzip, deflate
08.[HTTP_CONNECTION] => keep-alive
09.[HTTP_CACHE_CONTROL] => max-age=0
10.[PATH] => C:\Windows\system32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\PHP\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth Software\syswow64;\;C:\Program Files (x86)\Sony\VAIO Startup Setting Tool;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files (x86)\Windows Live\Shared;bin;C:\Program Files\Heroku\bin;C:\Program Files (x86)\ruby-1.9.3\bin;C:\Program Files (x86)\git\bin;C:\Program Files (x86)\git\cmd;c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Python27;C:\Users\grantwparks\AppData\Roaming\npm;C:\Program Files (x86)\nodejs\
11.[SystemRoot] => C:\Windows
12.[COMSPEC] => C:\Windows\system32\cmd.exe
13.[PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
14.[WINDIR] => C:\Windows
15.[SERVER_SIGNATURE] =>
16.[SERVER_SOFTWARE] => Apache/2.2.22 (Win32) PHP/5.3.13
17.[SERVER_NAME] => vaio.web.gwp
18.[SERVER_ADDR] => 127.0.0.1
19.[SERVER_PORT] => 80
20.[REMOTE_ADDR] => 127.0.0.1
21.[DOCUMENT_ROOT] => C:/Users/grantwparks/workspace/phpweb
22.[SERVER_ADMIN] => grantwparks@gmail.com
23.[SCRIPT_FILENAME] => C:/Users/grantwparks/workspace/phpweb/public/index.php
24.[REMOTE_PORT] => 61270
25.[GATEWAY_INTERFACE] => CGI/1.1
26.[SERVER_PROTOCOL] => HTTP/1.1
27.[REQUEST_METHOD] => GET
28.[QUERY_STRING] =>
29.[REQUEST_URI] => /public/index.php
30.[SCRIPT_NAME] => /public/index.php
31.[PHP_SELF] => /public/index.php
32.[REQUEST_TIME] => 1341354716
33.)
To avoid a warning like this when working with dates
PHP Warning: date(): It is not safe to rely on the system's timezone settings. You are *required to use the date.timezone setting or the datedefaulttimezone_set() function...*
The time zone can be set in php.ini. To see a list of the recognized time zones, replace phpinfo() with timezoneidentifierslist()
1.print_r (timezone_identifiers_list());
Pick the most appropriate time zone string and edit php.ini one more time. Find the date.timezone setting and use your time zone for the value.
1.date.timezone = 'America/Denver'

No comments:

Post a Comment