Clinet's Information
====================
(1) getenv from PHP
---------------
* REMOTEHOST
The hostname making the request. If the server does not have this information, it should set REMOTE_ADDR and leave this unset.
* REMOTE_ADDR
The IP address of the remote host making the request.
* REMOTE_USER
If the server supports user authentication, and the script is protected, this is the username they have authenticated as.
* REMOTE_IDENT
If the HTTP server supports RFC 931 identification, then this variable will be set to the remote user name retrieved from the server. Usage of this variable should be limited to logging only.
* CONTENT_TYPE
For queries which have attached information, such as HTTP POST and PUT, this is the content type of the data.
* CONTENT_LENGTH
The length of the said content as given by the client.
* PATH_INFO
The extra path information, as given by the client. In other words, scripts can be accessed by their virtual pathname, followed by extra information at the end of this path. The extra information is sent as PATH_INFO. This information should be decoded by the server if it comes from a URL before it is passed to the CGI script.
* PATH_TRANSLATED
The server provides a translated version of PATH_INFO, which takes the path and does any virtual-to-physical mapping to it.
* HTTP_ACCEPT
The MIME types which the client will accept, as given by HTTP headers. Other protocols may need to get this information from elsewhere. Each item in this list should be separated by commas as per the HTTP spec.
Format: type/subtype, type/subtype
* HTTP_USER_AGENT
The browser the client is using to send the request. General format: software/version library/version
* getmyuid ( void)
Returns the user ID of the current script
******************************************************************************************************
2) Javascript
==========
* getTimezoneOffset method
returns an integer value representing the number of minutes between the time on the current machine and UTC. These values are appropriate to the computer the script is executed on. If it is called from a server script, the return value is appropriate to the server. If it is called from a client script, the return value is appropriate to the client.
This number will be positive if you are behind UTC (e.g., Pacific Daylight Time), and negative if you are ahead of UTC (e.g., Japan).
For example, suppose a server in New York City is contacted by a client in Los Angeles on December 1. getTimezoneOffset returns 480 if executed on the client, or 300 if executed on the server.
The following example illustrates the use of the getTimezoneOffset method:
function TZDemo()
{
var d, tz, s = "The current local time is ";
d = new Date();
tz = d.getTimezoneOffset();
if (tz < 0)
s += tz / 60 + " hours before GMT";
else if (tz == 0)
s += "GMT";
else
s += tz / 60 + " hours after GMT";
return(s);
}
Monday, October 29, 2007
Sunday, October 28, 2007
PHP steganography
See the below example code. copy and paste (create a php file, it's enough for steganography)
/************************************************************\
*
* PHPStego Copyright 2005 Howard Yeend
* www.puremango.co.uk
*
* This file is part of PHPStego.
*
* PHPStego is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* PHPStego is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PHPStego; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
\************************************************************/
// this script is (almost) totally insecure, do not rely on it for security
ini_set("max_execution_time",3000);
function is_even($num)
{
// returns true if $num is even, false if not
return ($num%2==0);
}
function asc2bin($char)
{
// returns 8bit binary value from ASCII char
// eg; asc2bin("a") returns 01100001
return str_pad(decbin(ord($char)), 8, "0", STR_PAD_LEFT);
}
function bin2asc($bin)
{
// returns ASCII char from 8bit binary value
// eg; bin2asc("01100001") returns a
// argument MUST be sent as string
return chr(bindec($bin));
}
function rgb2bin($rgb)
{
// returns binary from rgb value (according to evenness)
// this way, we can store one ascii char in 2.6 pixels
// not a great ratio, but it works (albeit slowly)
$binstream = "";
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;
if(is_even($red))
{
$binstream .= "1";
} else {
$binstream .= "0";
}
if(is_even($green))
{
$binstream .= "1";
} else {
$binstream .= "0";
}
if(is_even($blue))
{
$binstream .= "1";
} else {
$binstream .= "0";
}
return $binstream;
}
function steg_hide($maskfile, $hidefile)
{
// hides $hidefile in $maskfile
// initialise some vars
$binstream = "";
$recordstream = "";
$make_odd = Array();
// ensure a readable mask file has been sent
$extension = strtolower(substr($maskfile['name'],-3));
if($extension=="jpg")
{
$createFunc = "ImageCreateFromJPEG";
/*
}
else if($extension=="png")
{
$createFunc = "ImageCreateFromPNG";
} else if($extension=="gif")
{
$createFunc = "ImageCreateFromGIF";
*/
} else {
return "Only .jpg mask files are supported";
}
// create images
$pic = @ImageCreateFromJPEG($maskfile['tmp_name']);
$attributes = @getImageSize($maskfile['tmp_name']);
$outpic = @ImageCreateFromJPEG($maskfile['tmp_name']);
if(!$pic || !$outpic || !$attributes)
{
// image creation failed
return "cannot create images - maybe GDlib not installed?";
}
// read file to be hidden
$data = file_get_contents($hidefile['tmp_name']);
// generate unique boundary that does not occur in $data
// 1 in 16581375 chance of a file containing all possible 3 ASCII char sequences
// 1 in every ~1.65 billion files will not be steganographisable by this script
// though my maths might be wrong.
// if you really want to get silly, add another 3 random chars. (1 in 274941996890625)
// ^^^^^^^^^^^^ would require appropriate modification to decoder.
do
{
$boundary = chr(rand(0,255)).chr(rand(0,255)).chr(rand(0,255));
} while(strpos($data,$boundary)!==false && strpos($hidefile['name'],$boundary)!==false);
// add boundary to data
$data = $boundary.$hidefile['name'].$boundary.$data.$boundary;
// you could add all sorts of other info here (eg IP of encoder, date/time encoded, etc, etc)
// decoder reads first boundary, then carries on reading until boundary encountered again
// saves that as filename, and carries on again until final boundary reached
// check that $data will fit in maskfile
if(strlen($data)*8 > ($attributes[0]*$attributes[1])*3)
{
// remove images
ImageDestroy($outpic);
ImageDestroy($pic);
return "Cannot fit ".$hidefile['name']." in ".$maskfile['name'].".
".$hidefile['name']." requires mask to contain at least ".(intval((strlen($data)*8)/3)+1)." pixels.
Maximum filesize that ".$maskfile['name']." can hide is ".intval((($attributes[0]*$attributes[1])*3)/8)." bytes";
}
// convert $data into array of true/false
// pixels in mask are made odd if true, even if false
for($i=0; $i {
// get 8bit binary representation of each char
$char = $data{$i};
$binary = asc2bin($char);
// save binary to string
$binstream .= $binary;
// create array of true/false for each bit. confusingly, 0=true, 1=false
for($j=0 ; $j {
$binpart = $binary{$j};
if($binpart=="0")
{
$make_odd[] = true;
} else {
$make_odd[] = false;
}
}
}
// now loop through each pixel and modify colour values according to $make_odd array
$y=0;
for($i=0,$x=0; $i {
// read RGB of pixel
$rgb = ImageColorAt($pic, $x,$y);
$cols = Array();
$cols[] = ($rgb >> 16) & 0xFF;
$cols[] = ($rgb >> 8) & 0xFF;
$cols[] = $rgb & 0xFF;
for($j=0 ; $j {
if($make_odd[$i+$j]===true && is_even($cols[$j]))
{
// is even, should be odd
$cols[$j]++;
} else if($make_odd[$i+$j]===false && !is_even($cols[$j])){
// is odd, should be even
$cols[$j]--;
} // else colour is fine as is
}
// modify pixel
$temp_col = ImageColorAllocate($outpic,$cols[0],$cols[1],$cols[2]);
ImageSetPixel($outpic,$x,$y,$temp_col);
// if at end of X, move down and start at x=0
if($x==($attributes[0]-1))
{
$y++;
// $x++ on next loop converts x to 0
$x=-1;
}
}
// output modified image as PNG (or other *LOSSLESS* format)
header("Content-type: image/png");
header("Content-Disposition: attachment; filename=encoded.png");
ImagePNG($outpic);
// remove images
ImageDestroy($outpic);
ImageDestroy($pic);
exit();
}
function steg_recover($maskfile)
{
// recovers file hidden in a PNG image
$binstream = "";
$filename = "";
// get image and width/height
$attributes = @getImageSize($maskfile['tmp_name']);
$pic = @ImageCreateFromPNG($maskfile['tmp_name']);
if(!$pic || !$attributes)
{
return "could not read image";
}
// get boundary
$bin_boundary = "";
for($x=0 ; $x<8 ; $x++)
{
$bin_boundary .= rgb2bin(ImageColorAt($pic, $x,0));
}
// convert boundary to ascii
for($i=0 ; $i {
$binchunk = substr($bin_boundary,$i,8);
$boundary .= bin2asc($binchunk);
}
// now convert RGB of each pixel into binary, stopping when we see $boundary again
// do not process first boundary
$start_x = 8;
for($y=0 ; $y<$attributes[1] ; $y++)
{
for($x=$start_x ; $x<$attributes[0] ; $x++)
{
// generate binary
$binstream .= rgb2bin(ImageColorAt($pic, $x,$y));
// convert to ascii
if(strlen($binstream)>=8)
{
$binchar = substr($binstream,0,8);
$ascii .= bin2asc($binchar);
$binstream = substr($binstream,8);
}
// test for boundary
if(strpos($ascii,$boundary)!==false)
{
// remove boundary
$ascii = substr($ascii,0,strlen($ascii)-3);
if(empty($filename))
{
$filename = $ascii;
$ascii = "";
} else {
// final boundary; exit both 'for' loops
break 2;
}
}
}
// on second line of pixels or greater; we can start at x=0 now
$start_x = 0;
}
// remove image from memory
ImageDestroy($pic);
// and output result (retaining original filename)
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=".$filename);
echo $ascii;
exit();
}
$result = true;
if(!empty($_FILES['hidefile']['tmp_name']))
{
// encode
$result = steg_hide($_FILES['maskfile'],$_FILES['hidefile']);
} else if(!empty($_FILES['maskfile']['tmp_name'])) {
// decode
$result = steg_recover($_FILES['maskfile']);
}
if($result!==true)
{
$error = "
Error:
".$result."
";
}
?>
PHP-Steg
PHP-Steg - www.puremango.co.uk
This is application is totally insecure(*) and is a 'concept' application rather than something to actually be employed for security.
Download the source code here.
* - for explanation, see the PHP-steg page on puremango.co.uk (under projects)
*****************************************************************
*****************************************************************
Thanks to http://www.puremango.co.uk/cm_steganography_112.php
/************************************************************\
*
* PHPStego Copyright 2005 Howard Yeend
* www.puremango.co.uk
*
* This file is part of PHPStego.
*
* PHPStego is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* PHPStego is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PHPStego; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
\************************************************************/
// this script is (almost) totally insecure, do not rely on it for security
ini_set("max_execution_time",3000);
function is_even($num)
{
// returns true if $num is even, false if not
return ($num%2==0);
}
function asc2bin($char)
{
// returns 8bit binary value from ASCII char
// eg; asc2bin("a") returns 01100001
return str_pad(decbin(ord($char)), 8, "0", STR_PAD_LEFT);
}
function bin2asc($bin)
{
// returns ASCII char from 8bit binary value
// eg; bin2asc("01100001") returns a
// argument MUST be sent as string
return chr(bindec($bin));
}
function rgb2bin($rgb)
{
// returns binary from rgb value (according to evenness)
// this way, we can store one ascii char in 2.6 pixels
// not a great ratio, but it works (albeit slowly)
$binstream = "";
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;
if(is_even($red))
{
$binstream .= "1";
} else {
$binstream .= "0";
}
if(is_even($green))
{
$binstream .= "1";
} else {
$binstream .= "0";
}
if(is_even($blue))
{
$binstream .= "1";
} else {
$binstream .= "0";
}
return $binstream;
}
function steg_hide($maskfile, $hidefile)
{
// hides $hidefile in $maskfile
// initialise some vars
$binstream = "";
$recordstream = "";
$make_odd = Array();
// ensure a readable mask file has been sent
$extension = strtolower(substr($maskfile['name'],-3));
if($extension=="jpg")
{
$createFunc = "ImageCreateFromJPEG";
/*
}
else if($extension=="png")
{
$createFunc = "ImageCreateFromPNG";
} else if($extension=="gif")
{
$createFunc = "ImageCreateFromGIF";
*/
} else {
return "Only .jpg mask files are supported";
}
// create images
$pic = @ImageCreateFromJPEG($maskfile['tmp_name']);
$attributes = @getImageSize($maskfile['tmp_name']);
$outpic = @ImageCreateFromJPEG($maskfile['tmp_name']);
if(!$pic || !$outpic || !$attributes)
{
// image creation failed
return "cannot create images - maybe GDlib not installed?";
}
// read file to be hidden
$data = file_get_contents($hidefile['tmp_name']);
// generate unique boundary that does not occur in $data
// 1 in 16581375 chance of a file containing all possible 3 ASCII char sequences
// 1 in every ~1.65 billion files will not be steganographisable by this script
// though my maths might be wrong.
// if you really want to get silly, add another 3 random chars. (1 in 274941996890625)
// ^^^^^^^^^^^^ would require appropriate modification to decoder.
do
{
$boundary = chr(rand(0,255)).chr(rand(0,255)).chr(rand(0,255));
} while(strpos($data,$boundary)!==false && strpos($hidefile['name'],$boundary)!==false);
// add boundary to data
$data = $boundary.$hidefile['name'].$boundary.$data.$boundary;
// you could add all sorts of other info here (eg IP of encoder, date/time encoded, etc, etc)
// decoder reads first boundary, then carries on reading until boundary encountered again
// saves that as filename, and carries on again until final boundary reached
// check that $data will fit in maskfile
if(strlen($data)*8 > ($attributes[0]*$attributes[1])*3)
{
// remove images
ImageDestroy($outpic);
ImageDestroy($pic);
return "Cannot fit ".$hidefile['name']." in ".$maskfile['name'].".
".$hidefile['name']." requires mask to contain at least ".(intval((strlen($data)*8)/3)+1)." pixels.
Maximum filesize that ".$maskfile['name']." can hide is ".intval((($attributes[0]*$attributes[1])*3)/8)." bytes";
}
// convert $data into array of true/false
// pixels in mask are made odd if true, even if false
for($i=0; $i
// get 8bit binary representation of each char
$char = $data{$i};
$binary = asc2bin($char);
// save binary to string
$binstream .= $binary;
// create array of true/false for each bit. confusingly, 0=true, 1=false
for($j=0 ; $j
$binpart = $binary{$j};
if($binpart=="0")
{
$make_odd[] = true;
} else {
$make_odd[] = false;
}
}
}
// now loop through each pixel and modify colour values according to $make_odd array
$y=0;
for($i=0,$x=0; $i
// read RGB of pixel
$rgb = ImageColorAt($pic, $x,$y);
$cols = Array();
$cols[] = ($rgb >> 16) & 0xFF;
$cols[] = ($rgb >> 8) & 0xFF;
$cols[] = $rgb & 0xFF;
for($j=0 ; $j
if($make_odd[$i+$j]===true && is_even($cols[$j]))
{
// is even, should be odd
$cols[$j]++;
} else if($make_odd[$i+$j]===false && !is_even($cols[$j])){
// is odd, should be even
$cols[$j]--;
} // else colour is fine as is
}
// modify pixel
$temp_col = ImageColorAllocate($outpic,$cols[0],$cols[1],$cols[2]);
ImageSetPixel($outpic,$x,$y,$temp_col);
// if at end of X, move down and start at x=0
if($x==($attributes[0]-1))
{
$y++;
// $x++ on next loop converts x to 0
$x=-1;
}
}
// output modified image as PNG (or other *LOSSLESS* format)
header("Content-type: image/png");
header("Content-Disposition: attachment; filename=encoded.png");
ImagePNG($outpic);
// remove images
ImageDestroy($outpic);
ImageDestroy($pic);
exit();
}
function steg_recover($maskfile)
{
// recovers file hidden in a PNG image
$binstream = "";
$filename = "";
// get image and width/height
$attributes = @getImageSize($maskfile['tmp_name']);
$pic = @ImageCreateFromPNG($maskfile['tmp_name']);
if(!$pic || !$attributes)
{
return "could not read image";
}
// get boundary
$bin_boundary = "";
for($x=0 ; $x<8 ; $x++)
{
$bin_boundary .= rgb2bin(ImageColorAt($pic, $x,0));
}
// convert boundary to ascii
for($i=0 ; $i
$binchunk = substr($bin_boundary,$i,8);
$boundary .= bin2asc($binchunk);
}
// now convert RGB of each pixel into binary, stopping when we see $boundary again
// do not process first boundary
$start_x = 8;
for($y=0 ; $y<$attributes[1] ; $y++)
{
for($x=$start_x ; $x<$attributes[0] ; $x++)
{
// generate binary
$binstream .= rgb2bin(ImageColorAt($pic, $x,$y));
// convert to ascii
if(strlen($binstream)>=8)
{
$binchar = substr($binstream,0,8);
$ascii .= bin2asc($binchar);
$binstream = substr($binstream,8);
}
// test for boundary
if(strpos($ascii,$boundary)!==false)
{
// remove boundary
$ascii = substr($ascii,0,strlen($ascii)-3);
if(empty($filename))
{
$filename = $ascii;
$ascii = "";
} else {
// final boundary; exit both 'for' loops
break 2;
}
}
}
// on second line of pixels or greater; we can start at x=0 now
$start_x = 0;
}
// remove image from memory
ImageDestroy($pic);
// and output result (retaining original filename)
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=".$filename);
echo $ascii;
exit();
}
$result = true;
if(!empty($_FILES['hidefile']['tmp_name']))
{
// encode
$result = steg_hide($_FILES['maskfile'],$_FILES['hidefile']);
} else if(!empty($_FILES['maskfile']['tmp_name'])) {
// decode
$result = steg_recover($_FILES['maskfile']);
}
if($result!==true)
{
$error = "
Error:
".$result."
";
}
?>
PHP-Steg - www.puremango.co.uk
This is application is totally insecure(*) and is a 'concept' application rather than something to actually be employed for security.
Download the source code here.
* - for explanation, see the PHP-steg page on puremango.co.uk (under projects)
*****************************************************************
*****************************************************************
Thanks to http://www.puremango.co.uk/cm_steganography_112.php
Friday, October 19, 2007
php manual
Here some manual download available
http://www.php.net/download-docs.php
http://www.linuxforums.org/forum/linux-programming-scripting/17983-php-manual-download.html
http://www.php.net/download-docs.php
http://www.linuxforums.org/forum/linux-programming-scripting/17983-php-manual-download.html
php definition
elf-referentially short for PHP: Hypertext Preprocessor, an open source, server-side, HTML embedded scripting language used to create dynamic Web pages.
In an HTML document, PHP script (similar syntax to that of Perl or C ) is enclosed within special PHP tags. Because PHP is embedded within tags, the author can jump between HTML and PHP (similar to ASP and Cold Fusion) instead of having to rely on heavy amounts of code to output HTML. And, because PHP is executed on the server, the client cannot view the PHP code.
PHP can perform any task that any CGI program can do, but its strength lies in its compatibility with many types of databases. Also, PHP can talk across networks using IMAP, SNMP, NNTP, POP3, or HTTP.
PHP was created sometime in 1994 by Rasmus Lerdorf. During mid 1997, PHP development entered the hands of other contributors. Two of them, Zeev Suraski and Andi Gutmans, rewrote the parser from scratch to create PHP version 3 (PHP3).
In an HTML document, PHP script (similar syntax to that of Perl or C ) is enclosed within special PHP tags. Because PHP is embedded within tags, the author can jump between HTML and PHP (similar to ASP and Cold Fusion) instead of having to rely on heavy amounts of code to output HTML. And, because PHP is executed on the server, the client cannot view the PHP code.
PHP can perform any task that any CGI program can do, but its strength lies in its compatibility with many types of databases. Also, PHP can talk across networks using IMAP, SNMP, NNTP, POP3, or HTTP.
PHP was created sometime in 1994 by Rasmus Lerdorf. During mid 1997, PHP development entered the hands of other contributors. Two of them, Zeev Suraski and Andi Gutmans, rewrote the parser from scratch to create PHP version 3 (PHP3).
Thursday, October 18, 2007
cron job in php
Cron job is a system method to run a particulat task/page to a particular interval. It si a automated system process.
here the steps to install
On UNIX/Linux:
Use the cron daemon to execute the "runcronjobs.php" file.
Edit the desired crontab file and add the following lines:
# This must be set to the directory where eZ publish is installed.
EZPUBLISHROOT=/path/to/your/ezpublish/directory
# Location of the PHP Command Line Interface binary.
PHP=/usr/local/bin/php
# Executes the runcronjobs.php script every 15th minute.
0,15,30,45 * * * * cd $EZPUBLISHROOT; $PHP -C runcronjobs.php -q 2>&1
Shows current cron file contents
crontab -l
Replaces your current cron file
crontab /path/to/your/ezpublish/directory/ezpublish.cron
On Windows:
On Windows 2000 and XP it is possible to use the "Scheduled Tasks" mechanism to automatically run the maintenance file. You would probably have to create a batch (.bat) file (which is set up to run the runcronjobs.php file with the correct parameters, etc.) and then set up
------------ Version 3.4 update ----------
Usage: runcronjobs.php [OPTION]... [PART]
Executes eZ publish cronjobs.
General options:
-h,--help display this help and exit
-q,--quiet do not give any output except when errors occur
-s,--siteaccess selected siteaccess for operations, if not specified default siteaccess is used
-d,--debug display debug output at end of execution
-c,--colors display output using ANSI colors
--sql display sql queries
--logfiles create log files
--no-logfiles do not create log files (default)
--no-colors do not use ANSI coloring (default)
Example: Run all cronjobs in cronjob.ini
runcronjobs.php
Example: Run a subset. i.e. I only want to run workflow. A good idea as link checking every ten minutes is just a waste of cpu and bandwidth
This example will run the workflow elements configured by adding the following to you cronjob.ini file.
[CronjobPart-workflow]
Scripts[]=workflow.php
runcronjobs.php workflow
Thursday, October 11, 2007
Develop an Events Calendar
Project: Develop an Events Calendar
Putting into practice many of the concepts that have been introduced thus far, I’ll
conclude this chapter with instructions illustrating how to create a Web-based
events calendar. This calendar could store information regarding the latest cooking
shows, wine-tasting seminars, or whatever else you deem necessary for your
needs. This calendar will make use of many of the concepts you’ve learned thus
far and will introduce you to a few others that will be covered in further detail in
later chapters.
A simple file will store the information contained in the calendar. Here are the
file’s contents:
July 21, 2000|8 p.m.|Cooking With Rasmus|PHP creator Rasmus Lerdorf discusses the
wonders of cheese.
July 23, 2000|11 a.m.|Boxed Lunch|Valerie researches the latest ham sandwich
making techniques (documentary)
Expressions, Operators, and Control Structures
77
NOTE The use of continue in long and complex algorithms can result in
unclear and confusing code. I recommend avoiding use of this construct in
these cases.
July 31, 2000|2:30pm|Progressive Gourmet|Forget the Chardonnay; iced tea is the
sophisticated gourmet's beverage of choice.
August 1, 2000|7 p.m.|Coder's Critique|Famed Food Critic Brian rates NYC's hottest
new Internet cafés.
August 3, 2000|6 p.m.|Australian Algorithms|Matt studies the alligator's diet.
Our PHP script shown in Listing 3-1 will produce the output seen in Figure 3-1.
Before delving into the code, take a moment to read through the algorithm,
which will outline the series of commands executed by the code:
1. Open the file containing the event information.
2. Split each line into four elements: date, time, event title, and event summary.
3. Format and display the event information.
4. Close the file.
Chapter 3
78
Figure 3-1. The sample events calendar.
Listing 3-1: Script used to display contents of events.txt to browser
// application: events calendar
// purpose: read and parse data from a file and format it
// for output to a browser.
// open filehandle entitled '$events' to file 'events.txt'.
$events = fopen("events.txt", "r");
print "
| "; print " Events Calendar:";// while not the end of the file while (! feof($events)) : // read the next line of the events.txt file $event = fgets($events, 4096); // separate event information in the current // line into array elements. $event_info = explode("|", $event); // Format and output event information print "$event_info[0] ( $event_info[1] ) "; print "$event_info[2] "; print "$event_info[3] "; endwhile; // close the table print " |
fclose ($events);
?>
This short example serves as further proof that PHP enables even novice
programmers to develop practical applications while investing a minimum of
time and learning. Don’t worry if you don’t understand some of the concepts introduced;
they are actually quite simple and will be covered in detail in later
Escaping to PHP
Escaping to PHP
The PHP parsing engine needs a way to differentiate PHP code from other elements
in the page. The mechanism for doing so is known as ‘escaping to PHP.’
There are four ways to do this:
• Default tags
• Short tags
• Script tags
• ASP-style tags
Default Tags
The default tags are perhaps those most commonly used by PHP programmers,
due to clarity and convenience of use:
These tags may also be the most practical ones because the initial escape
characters are followed by php, which explicitly makes reference to the type of
code that follows. This can be useful because you may be simultaneously using
An Introduction to PHP
23
several technologies in the same page, such as JavaScript, server-side includes,
and PHP. Any ensuing PHP code will then follow the initial escape sequence, preceded
by the closing escape sequence, "?>".
Short Tags
The short tag style is the shortest available for escaping to PHP code:
Short tags must be enabled in order for them to work. There are two ways to
do this:
• Include the —enable-short-tags option when compiling PHP.
• Enable the short_open_tag configuration directive found within the php.ini
file.
Script Tags
Several text editors will mistakenly interpret PHP code as HTML (that is, viewable)
code, interfering with the Web page development process. To eliminate this
problem, use the following escape tags:
ASP-Style Tags
Chapter 1
24
A fourth and final way to embed PHP code is through the use of ASP (Active
Server Page)-style tags. This way is much like the short tag way just described,
except that a percentage sign (%) is used instead of a question mark.
<% print "Welcome to the world of PHP!"; %>
A variation of the ASP-style tag that can result in a lesser degree of code clutter
is available. This variation eliminates the need to include a ‘print’ statement in
the enclosed PHP code. The equals sign (=) immediately following the opening
ASP tag signals the PHP parser to output the value of the variable:
<%= $variable %>
Making use of this convenient tag style, we could execute the following:
<%
// set variable $recipe to something…
$recipe = "Lasagna";
%>
Luigi’s favorite recipe is <%=$recipe;%>
There are actually two separate PHP scripts in this listing. The first assigns the
value “Lasagna” to the variable $recipe. Later on, when it is necessary to display
the value of the variable $recipe, you can use the ASP-style variation for this sole
purpose. Incidentally, you could also use short tags () in much the same
way.
password random generator
$totalChar = 8; // number of chars in the password
$salt = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789"; // salt to select chars from
srand((double)microtime()*1000000); // start the random generator
$password=""; // set the inital variable
for ($i=0;$i<$totalChar;$i++) // loop and create password
$password = $password . substr ($salt, rand() % strlen($salt), 1);
echo "Password is " . $password;
?>
[/php]
Solutions for image validation
Mostly no one validate the image in client (ya of course we validate type of image but could not validate is that true image), here that code to validate the image is available,have true
function validate()
{
if(document.form1.thumbnailimg.value!="")
{
var nnp=/\\\/g
var img1
img1 = new Image()
val ="file:///" + (document.form1.thumbnailimg.value).replace(nnp,"/")
img1.src=val
alert (img1.src)
alert (img1.height);
alert(img1.width);
}
}
form name="form1" id="form1" method="post" enctype="multipart/form-data" onsubmit="return validate();"
This code is my own code to develope for avoiding server side validate
Monday, October 1, 2007
PHP - Tutorial Reference url
1.http://www.lastcraft.com/first_test_tutorial.php
2.http://www.tizag.com/mysqlTutorial/
3.http://in2.php.net/tut.php
4.http://www.php-mysql-tutorial.com/
5.http://www.pdftutorials.com/
Simple program - Session in php
Create a php file and paste these code to
if (!session_is_registered('count')) {
session_register('count');
$count = 1;
} else {
$count++;
}
/* set the session name to WebsiteID */
$previous_name = session_name("WebsiteID");
echo "The previous session name was $previous_name
";
?>
Hello visitor, you have seen this page times.
To continue, ">click
here.
Php Object - Chapter 3
Trading account application
The fifth PHP data type is the object. You can think of an object as a variable that is
instantiated from a kind of template otherwise known as a class. The concept of
objects and classes is integral to the notion of object-oriented programming
(OOP).
Contrary to the other data types contained in the PHP language, an object
must be explicitly declared. It is important to realize that an object is nothing
more than a particular instance of a class, which acts as a template for creating
objects having specific characteristics and functionality. Therefore, a class must
be defined before an object can be declared. A general example of class declaration
and subsequent object instantiation follows:
Chapter 2
38
class appliance {
var power;
function set_power($on_off) {
$this->power = $on_off;
}
}
. . .
$blender = new appliance;
A class definition creates several characteristics and functions pertinent to a
data structure, in this case a data structure named appliance. So far, the appliance
isn’t very functional. There is only one characteristic: power. This characteristic
can be modified by using the method set_power.
Remember, however, that a class definition is a template and cannot itself be
manipulated. Instead, objects are created based on this template. This is accomplished
via the new keyword. Therefore, in the preceding listing an object of class
appliance named blender is created.
The blender power can then be set by making use of the method set_power:
$blender->set_power("on");
Object-oriented programming is such an important strategy in today’s application
development standards that its use with PHP merits its own chapter. Chapter
6, “Object-Oriented PHP,” introduces PHP’s OOP implementation in further
detail.
Boolean, or True/False, Values
The boolean data type is essentially capable of representing only two data types:
true and false. Boolean values can be determined in two ways: as a comparison
evaluation or from a variable value. Both are rather straightforward.
Comparisons can take place in many forms. Evaluation typically takes place
by use of a double equal sign and an if conditional. Here is an example:
if ($sum == 40) :
. . .
This could evaluate to only either true or false. Either $sum equals 40, or it
does not. If $sum does equal 40, then the expression evaluates to true. Otherwise,
the result is false.
Boolean values can also be determined via explicitly setting a variable to a
true or false value. Here is an example:
Variables and Data Types
39
$flag = TRUE;
if ($flag == TRUE) :
print "The flag is true!";
else :
print "The flag is false!";
endif;
If the variable $flag has been set to true, then print the appropriate statement;
Otherwise, print an alternative statement.
An alternative way to represent true and false is by using the values 1 and 0,
respectively. Therefore, the previous example can be restated as follows:
$flag = 1;
if ($flag == TRUE) :
print "The flag is true!";
else :
print "The flag is false !";
endif;
Yet another alternative way to represent the above example follows:
$flag = TRUE;
// this implicitly asks "if ($flag == TRUE)"
if ($flag) :
print "The flag is true!";
else :
print "The flag is false!";
endif;
Identifiers
An identifier is a general term applied to variables, functions, and various other
user-defined objects. There are several properties that PHP identifiers must
abide by:
• An identifier can consist of one or more characters and must begin with an
alphabetical letter or an underscore. Furthermore, identifiers can only consist
of letters, numbers, underscore characters, and other ASCII characters
from 127 through 255. Consider a few examples:
Chapter 2
40
VALID INVALID
my_function This&that
Size !counter
_someword 4ward
• Identifiers are case sensitive. Therefore, a variable named $recipe is different
from variables named $Recipe, $rEciPe, or $recipE.
• Identifiers can be any length. This is advantageous, as it enables a programmer
to accurately describe the identifier’s purpose via the identifier name.
• Finally, an identifier name can’t be identical to any of PHP’s predefined keywords.
Variables
As a byproduct of examining the examples up to this point, I’ve introduced you to
how variables are assigned and manipulated. However, it would be wise to explicitly
lay the groundwork as to how variables are declared and manipulated. The
coming sections will examine these rules in detail.
Variable Declaration
A variable is a named memory location that contains data that may be manipulated
throughout the execution of the program.
A variable always begins with a dollar sign, $. The following are all valid variables:
$color
$operating_system
$_some_variable
$model
Variable names follow the same naming rules as those set for identifiers. That
is, a variable name can begin with either an alphabetical letter or underscore and
can consist of alphabetical letters, underscores, integers, or other ASCII characters
ranging from 127 through 255.
Variables and Data Types
41
Interestingly, variables do not have to be explicitly declared in PHP, much as
is the case with the Perl language. Rather, variables can be declared and assigned
values simultaneously. Furthermore, a variable’s data type is implicitly determined
by examining the kind of data that the variable holds. Consider the following
example:
$sentence = "This is a sentence."; // $sentence evaluates to string.
$price = 42.99; // $price evaluates to a floating-point
$weight = 185; // $weight evaluates to an integer.
You can declare variables anywhere in a PHP script. However, the location of
the declaration greatly influences the realm in which a variable can be accessed.
This access domain is known as its scope.
Variable Scope
Scope can be defined as the range of availability a variable has to the program in
which it is declared. PHP variables can be one of four scope types:
• Local variables
• Function parameters
• Global variables
• Static variables
Local Variables
A variable declared in a function is considered local; that is, it can be referenced
solely in that function. Any assignment outside of that function will be considered
to be an entirely different variable from the one contained in the function. Note
that when you exit the function in which the local variable has been declared, that
variable and its corresponding value will be destroyed.
Local variables are advantageous because they eliminate the possibility of
unexpected side effects, which can result from globally accessible variables that
are modified, intentionally or not. Consider this listing:
The fifth PHP data type is the object. You can think of an object as a variable that is
instantiated from a kind of template otherwise known as a class. The concept of
objects and classes is integral to the notion of object-oriented programming
(OOP).
Contrary to the other data types contained in the PHP language, an object
must be explicitly declared. It is important to realize that an object is nothing
more than a particular instance of a class, which acts as a template for creating
objects having specific characteristics and functionality. Therefore, a class must
be defined before an object can be declared. A general example of class declaration
and subsequent object instantiation follows:
Chapter 2
38
class appliance {
var power;
function set_power($on_off) {
$this->power = $on_off;
}
}
. . .
$blender = new appliance;
A class definition creates several characteristics and functions pertinent to a
data structure, in this case a data structure named appliance. So far, the appliance
isn’t very functional. There is only one characteristic: power. This characteristic
can be modified by using the method set_power.
Remember, however, that a class definition is a template and cannot itself be
manipulated. Instead, objects are created based on this template. This is accomplished
via the new keyword. Therefore, in the preceding listing an object of class
appliance named blender is created.
The blender power can then be set by making use of the method set_power:
$blender->set_power("on");
Object-oriented programming is such an important strategy in today’s application
development standards that its use with PHP merits its own chapter. Chapter
6, “Object-Oriented PHP,” introduces PHP’s OOP implementation in further
detail.
Boolean, or True/False, Values
The boolean data type is essentially capable of representing only two data types:
true and false. Boolean values can be determined in two ways: as a comparison
evaluation or from a variable value. Both are rather straightforward.
Comparisons can take place in many forms. Evaluation typically takes place
by use of a double equal sign and an if conditional. Here is an example:
if ($sum == 40) :
. . .
This could evaluate to only either true or false. Either $sum equals 40, or it
does not. If $sum does equal 40, then the expression evaluates to true. Otherwise,
the result is false.
Boolean values can also be determined via explicitly setting a variable to a
true or false value. Here is an example:
Variables and Data Types
39
$flag = TRUE;
if ($flag == TRUE) :
print "The flag is true!";
else :
print "The flag is false!";
endif;
If the variable $flag has been set to true, then print the appropriate statement;
Otherwise, print an alternative statement.
An alternative way to represent true and false is by using the values 1 and 0,
respectively. Therefore, the previous example can be restated as follows:
$flag = 1;
if ($flag == TRUE) :
print "The flag is true!";
else :
print "The flag is false !";
endif;
Yet another alternative way to represent the above example follows:
$flag = TRUE;
// this implicitly asks "if ($flag == TRUE)"
if ($flag) :
print "The flag is true!";
else :
print "The flag is false!";
endif;
Identifiers
An identifier is a general term applied to variables, functions, and various other
user-defined objects. There are several properties that PHP identifiers must
abide by:
• An identifier can consist of one or more characters and must begin with an
alphabetical letter or an underscore. Furthermore, identifiers can only consist
of letters, numbers, underscore characters, and other ASCII characters
from 127 through 255. Consider a few examples:
Chapter 2
40
VALID INVALID
my_function This&that
Size !counter
_someword 4ward
• Identifiers are case sensitive. Therefore, a variable named $recipe is different
from variables named $Recipe, $rEciPe, or $recipE.
• Identifiers can be any length. This is advantageous, as it enables a programmer
to accurately describe the identifier’s purpose via the identifier name.
• Finally, an identifier name can’t be identical to any of PHP’s predefined keywords.
Variables
As a byproduct of examining the examples up to this point, I’ve introduced you to
how variables are assigned and manipulated. However, it would be wise to explicitly
lay the groundwork as to how variables are declared and manipulated. The
coming sections will examine these rules in detail.
Variable Declaration
A variable is a named memory location that contains data that may be manipulated
throughout the execution of the program.
A variable always begins with a dollar sign, $. The following are all valid variables:
$color
$operating_system
$_some_variable
$model
Variable names follow the same naming rules as those set for identifiers. That
is, a variable name can begin with either an alphabetical letter or underscore and
can consist of alphabetical letters, underscores, integers, or other ASCII characters
ranging from 127 through 255.
Variables and Data Types
41
Interestingly, variables do not have to be explicitly declared in PHP, much as
is the case with the Perl language. Rather, variables can be declared and assigned
values simultaneously. Furthermore, a variable’s data type is implicitly determined
by examining the kind of data that the variable holds. Consider the following
example:
$sentence = "This is a sentence."; // $sentence evaluates to string.
$price = 42.99; // $price evaluates to a floating-point
$weight = 185; // $weight evaluates to an integer.
You can declare variables anywhere in a PHP script. However, the location of
the declaration greatly influences the realm in which a variable can be accessed.
This access domain is known as its scope.
Variable Scope
Scope can be defined as the range of availability a variable has to the program in
which it is declared. PHP variables can be one of four scope types:
• Local variables
• Function parameters
• Global variables
• Static variables
Local Variables
A variable declared in a function is considered local; that is, it can be referenced
solely in that function. Any assignment outside of that function will be considered
to be an entirely different variable from the one contained in the function. Note
that when you exit the function in which the local variable has been declared, that
variable and its corresponding value will be destroyed.
Local variables are advantageous because they eliminate the possibility of
unexpected side effects, which can result from globally accessible variables that
are modified, intentionally or not. Consider this listing:
Php Arrays - chapter2
Arrays
An array is a list of elements each having the same type. There are two types of arrays:
those that are accessed in accordance with the index position in which the
element resides, and those that are associative in nature, accessed by a key value
that bears some sort of association with its corresponding value. In practice, however,
both are manipulated in much the same way. Arrays can also be singledimensional
or multidimensional in size.
Single-Dimension Indexed Arrays
Single-dimension indexed arrays are handled using an integer subscript to denote
the position of the requested value.
Variables and Data Types
35
The general syntax of a single-dimension array is:
$name[index1];
A single-dimension array can be created as follows:
$meat[0] = "chicken";
$meat[1] = "steak";
$meat[2] = "turkey";
If you execute this command:
print $meat[1];
The following will be output to the browser:
steak
Alternatively, arrays may be created using PHP’s array() function. You can use
this function to create the same $meat array as the one in the preceding example:
$meat = array("chicken", "steak", "turkey");
Executing the same print command yields the same results as in the previous
example, again producing “steak”.
You can also assign values to the end of the array simply by assigning values
to an array variable using empty brackets. Therefore, another way to assign values
to the $meat array is as follows:
$meat[] = "chicken";
$meat[] = "steak";
$meat[] = "turkey";
Single-Dimension Associative Arrays
Associative arrays are particularly convenient when it makes more sense to map
an array using words rather than integers.
For example, assume that you wanted to keep track of all of the best food and
wine pairings. It would be most convenient if you could simply assign the arrays
using key-value pairings, for example, wine to dish. Use of an associative array to
store this information would be the wise choice:
Chapter 2
36
$pairings["zinfandel"] = "Broiled Veal Chops";
$pairings["merlot"] = "Baked Ham";
$pairings["sauvignon"] = "Prime Rib";
$pairings["sauternes"] = "Roasted Salmon";
Use of this associative array would greatly reduce the time and code required
to display a particular value. Assume that you wanted to inform a reader of the
best accompanying dish with merlot. A simple call to the pairings array would
produce the necessary output:
print $pairings["merlot"]; // outputs the value "Baked Ham"
An alternative method in which to create an array is via PHP’s array() function:
$pairings = array(
zinfandel => "Broiled Veal Chops",
merlot => "Baked Ham",
sauvignon => "Prime Rib",
sauternes => "Roasted Salmon";
This assignment method bears no difference in functionality from the previous
$pairings array, other than the format in which it was created.
Multidimensional Indexed Arrays
Multidimensional indexed arrays function much like their single-dimension
counterparts, except that more than one index array is used to specify an element.
There is no limit as to the dimension size, although it is unlikely that anything
beyond three dimensions would be used in most applications.
The general syntax of a multidimensional array is:
$name[index1] [index2]..[indexN];
An element of a two-dimensional indexed array could be referenced as follows:
$position = $chess_board[5][4];
Variables and Data Types
37
Multidimensional Associative Arrays
Multidimensional associative arrays are also possible (and quite useful) in PHP.
Assume you wanted to keep track of wine-food pairings, not only by wine type,
but also by producer. You could do something similar to the following:
$pairings["Martinelli"] ["zinfandel"] = "Broiled Veal Chops";
$pairings["Beringer"] ["merlot"] = "Baked Ham";
$pairings["Jarvis"] ["sauvignon"] = "Prime Rib";
$pairings["Climens"] ["sauternes"] = "Roasted Salmon";
Mixing Indexed and Associative Array Indexes
It is also possible to mix indexed and associative arrays indexes. Expanding on the
single-dimension associative array example, suppose you wanted to keep track of
the first and second string players of the Ohio State Buckeyes football team. You
could do something similar to the following:
$Buckeyes["quarterback"] [1] = "Bellisari";
$Buckeyes["quarterback"] [2] = "Moherman";
$Buckeyes["quarterback"] [3] = "Wiley";
PHP provides a vast assortment of functions for creating and manipulating
arrays, so much so that the subject merits an entire chapter. Read Chapter 5, “Arrays,”
for a complete discussion of how PHP arrays are handled.
Php Installation
Regardless of the installation variation you choose, you’ll need to begin by
decompressing the distributions. This is accomplished in two easy steps:
1. Unzip the packages. Once done, you’ll see that the files will be left with
*.tar extensions:
gunzip apache_1.3.9.tar.gz
gunzip php-4.0.0.tar.gz
2. Untar the packages. This will unarchive the distributions:
tar -zxvf apache_1.3.x.tar
tar -zxvf php-4.0.x.tar
The installation procedure will pick up from this point.
Apache Module
Installing PHP as an Apache module is rather simple. I’ll take you through each
step here:
1. Change location to the Apache directory:
cd apache_1.3.x
2. Configure Apache. You can use any path you like. Keep in mind that a
slash does not follow the pathname:
./configure —prefix=[path]
3. Change the location to the PHP directory and configure, build, and install
the distribution. The option with-config-file-path specifies the directory
that will contain PHP’s configuration file. Generally, this path is set to be
/usr/local/lib, but you can set it to be anything you wish:
./configure –with-apache=../apache_1.3.x —with-config-file-path=[config-path]
make
make install
An Introduction to PHP
13
4. Change back to the Apache directory. Now you will reconfigure, build,
and install Apache. The other-configuration-options option refers to any
special configuration options that you would like to pass along to the
Apache Web server. This is beyond the scope of this book. I suggest
checking out the Apache documentation for a complete explanation of
these options:
./configure –activate-module=src/modules/php4/libphp4.a
—other-configuration-options
make
make install
5. The final step involves modifying Apache’s httpd.conf file. Some of these
modifications relate specifically to Apache, while others are necessary to
ensure that PHP scripts can be recognized and sent to the Web server.
First, locate the line that reads:
ServerName new.host.name
Change this line to read:
ServerName localhost
Next, locate the following two lines:
#AddType application/x-httpd-php .php .php4
#AddType application/x-httpd-php-source .phps
These lines need to be uncommented in order for PHP-enabled files to work
correctly on the server. To uncomment these lines, simply remove the pound
symbol (#) from the beginning of each line. Save the file and move up one directory.
Start the Apache server using the following command:
./bin/apachectl start
Voilà! PHP and Apache are now ready for use. For testing purposes, insert the
following code into a file and save the file as phpinfo.php to the Apache’s document
root directory. This is the directory called htdocs, located in the Apache
installation directory.
php_info();
?>
Chapter 1
14
Open this file up in a browser on the server. You should see a lengthy list of
information regarding PHP’s configuration. Congratulations, you’ve successfully
installed PHP as an Apache Module.
Dynamic Apache Module
The Dynamic Module is useful because it allows you to upgrade your PHP distribution
without having to recompile the Web server as well. Apache considers it
just another one of its many modules, like ModuleRewrite or ModuleSpelling.
This idea becomes particularly useful when you want to add some kind of support
to PHP later, encryption, for example. All you have to do is reconfigure/compile
PHP in accordance with the encryption support, and you can immediately
begin using it in your Web applications. Here is the installation process:
1. Change location to the Apache directory:
cd apache_1.3.x
2. Configure Apache. You can use any path you like. Keep in mind that a
slash does not follow the pathname. The –other-configuration-options
option refers to any special configuration options that you would like to
pass along to the Apache Web server. This is beyond the scope of this
book. I suggest checking out the Apache documentation for a complete
explanation of these options:
./configure —prefix=[path] —enable-module=so —other-configuration-options
3. Build the Apache server. After typing make, you will see a bunch of messages
scroll by. This is normal.
make
4. Install the Apache server. After you type make install, another bunch of
messages will scroll by. Again, this is normal. Once this has finished,
you’ll see a message stating that you have successfully installed the
server.
make install
5. Assuming no errors occurred, you’re ready to modify Apache’s
“httpd.con” file. This file is located in the conf directory in the path that
An Introduction to PHP
15
you designated in step 4. Open this file in your favorite text editor. Locate
the following line:
ServerName new.host.name
Modify this line to read:
ServerName localhost
6. Change location to the directory in which you downloaded PHP. Then,
configure, make, and install PHP. You will need to specify the path directory
pointing to the apxs file. This file can be found in the bin directory of
the path you designated in step 4.
./configure —with-apxs=[path/to/apxs]
make
make install
7. Reopen Apache’s httpd.conf file for another modification. In order for
incoming requests for PHP-enabled files to be properly parsed, the file
extension must coincide with the one as specified in the Apache server’s
configuration file, httpd.conf. This file contains a number of options,
which can be modified at the administrator’s discretion; a few of these
options relate directly to PHP. Open the httpd.conf file in your favorite
text editor. Towards the end of the file are two lines similar to the following:
#AddType application/x-httpd-php .php .php4
#AddType application/x-httpd-php-source .phps
8. You must uncomment these in order for PHP-enabled files to work correctly
on the server. To uncomment these lines, simply remove the pound
symbol (#) from the beginning of each line.
9. Save the file and move up one directory (to cd). Start the Apache server
using the following command:
./bin/apachectl start
Voilà! PHP and Apache are now ready for use.
Chapter 1
16
For testing purposes, insert the following code into a file and save the file as
phpinfo.php to the Apache’s document root directory. This is the directory called
htdocs, located in the Apache installation directory.
php_info();
?>
Open this file up in a browser on the server. You should see a lengthy list of
information regarding PHP’s configuration. Congratulations, you’ve successfully
installed the Dynamic Apache Module.
Installation on Windows 95/98/NT
If you have installed an application on the Windows operating system, you have
probably found it to be very easy. Click a few buttons, agree to a few statements,
and the application is installed. And so is the case with the installation of Apache
and PHP on a Windows machine.
1. Double-click the Apache executable to begin the installation. You will be
greeted with an installation wizard. Read attentively and accept the
licensing agreement.
2. The wizard will suggest a default installation directory
(C:\Program Files\Apache Group\Apache). This is fine, but you may want
to shorten it to just C:\Apache\. However, it’s up to you.
3. You will then be prompted for what name you would like to have appear
in the Start menu. Enter whatever you want, or accept the default.
4. Next you will be prompted for the installation type. Just pick Typical.
After you make your choice, the installation process is carried out.
5. Now it is time to modify the “httpd.conf” file, located in the conf directory,
which is located in whatever directory you chose to install the
Apache server in step 2. Open this file using your favorite text editor.
You’ll probably want to make at least three basic modifications:
An Introduction to PHP
17
Replace yourname@yoursite.com with the correct information.
ServerAdmin yourname@yoursite.com
Uncomment this line and place the correct server name. Just use localhost
if you do not have an actual server name:
ServerName localhost
6. Attempt to start Apache to ensure that everything is working. At this
point you need to make the differentiation as to the type of Windows OS
you are using:
If you’re using Windows NT, choose “Install Apache as Service (NT Only)”
from the Start menu. Then go to the Control Panel, open up the Services
window, choose Apache, and click the “Start” button. Apache will start,
and it will start automatically at every subsequent boot of the machine.
If you’re not using Windows NT, choose “Start Apache” from the Start
menu. A small window will open. This window must be kept open in
order for the server to run.
7. Finally, go to a browser installed on the server and enter
http://localhost/. You should see a default page stating that the installation
has been carried out correctly.
8. Now it’s time to install PHP. Change the directory to wherever you downloaded
the PHP package. Extract it to the directory of your choice using
an unzipping application.
9. Go to that directory and look for a file entitled “php.ini-dist”. Rename this
file to php.ini and place it in the C:\Windows\ directory.
10. Go back to the PHP directory. Look for two more files, php4ts.dll and
Mscvrt.dll. Place these files in the C:\Windows\System\ directory. You
probably already have the Mscvrt.dll file, and you will be prompted to
overwrite it. Don’t overwrite the file or copy it.
11. Return to the Apache http.conf file, again opening it up in a text editor.
There are a few more modifications that you need to make:
[(H2L)]
18
Look for this line:
ScriptAlias /cgi-bin/ "C:/Apache/cgi-bin/"
Directly below this line, add the following:
ScriptAlias /php4/ "C:/php4/"
Then search for “AddType”. You will see the following two commented lines:
#AddType application/x-httpd-php3 .phtml
#AddType application/x-httpd-php3-source .phps
Directly below these lines, add the following:
AddType application/x-httpd-php .phtml .php
AddType application/x-httpd-php-source .phps
Keep scrolling down. You will find the following commented lines:
#
# Action lets you define media types that will execute a script whenever
# a matching file is called. This eliminates the need for repeated URL
# pathnames for oft-used CGI file processors.
# Format: Action media/type /cgi-script/location
# Format: Action handler-name /cgi-script/location
#
Below this, add the following:
Action application/x-httpd-php /php4/php.exe
12. Voilà! PHP and Apache are now ready for use.
For testing purposes, insert the following code into a file and save the file as
“phpinfo.php” to the Apache’s document root directory. This is the directory
called htdocs located in whatever directory you specified in step 4.
php_info();
?>
[(H1L)]
19
Open this file in a browser on the server. You should see a lengthy list of information
regarding PHP’s configuration.
PHP Configuration
Although PHP will correctly run given its default configuration setting, you can
make quite a few modifications to fine-tune the installation to your needs. The
php.ini file, copied by default into the /usr/local/lib/ directory during the installation
process, contains all of these configuration settings.
Regardless of the platform and Web server used in conjunction with PHP, the
php.ini file will contain the same default set of parameters, from which several
important characteristics of the PHP installation can be administered. This file
contains all of the characteristics relevant to how your installation will act when
PHP scripts are executed. The PHP engine reads the php.ini file when PHP
starts up.
General Configuration Directives
Reiterating all of the configuration directives is beyond the scope of this book, but
there are several directives worth mentioning, as most the developers may find
them particularly useful. I’ll mention other directives as appropriate in subsequent
chapters.
Chapter 1
20
CAUTION Although successfully completing the steps outlined above does
make it possible for the Web server/PHP configuration to be used for testing
purposes, it does not imply that your Web server is accessible via the World
Wide Web. Check out the official Apache site ( http://www.apache.org) for
information regarding this matter. Furthermore, although the preceding
steps suffice to get the PHP package up and running, you will probably be
interested in modifying PHP’s configuration to best suit your needs. See
“PHP Configuration,” later in this chapter, for details.
NOTE The configuration file is entitled php3.ini in the 3.0 version but has
been changed to php.ini in the 4.0 version.
short_open_tag [on | off]
The short_open_tag [on | off] configuration directive determines the use of the
short PHP escape tags , in addition to the default tags.
asp_tags [on | off]
The asp_tags [on | off] configuration directive determines the use of ASP style tags
in addition to the default tags. ASP style tags are those that enclose PHP code as
follows:
<%
print "This is PHP code.";
%>
precision [integer]
The precision [integer] configuration directive sets the number of significant digits
displayed in floating point numbers.
safe_mode [on | off]
Turning on safe mode is a particularly good idea if you have several users on your
system. Essentially, turning on safe mode eliminates the possibility that a user
can use a PHP script to gain access to another file on the system, for example, the
passwd file on a Linux machine. Safe_mode works solely on the CGI version of
PHP. Check out Chapter 16 for more details regarding this matter.
max_execution_time [integer]
The max_execution_time [integer] configuration directive determines the maximum
number of seconds that a given PHP script may execute. This prevents runaway
scripts from eating up valuable system resources.
error_reporting [1–8]
The error_reporting [1-8] configuration directive gauges to what degree errors will
be reported, if any. The higher the bit value, the more sensitive PHP will be to
reporting errors:
An Introduction to PHP
21
BIT VALUE REPORTING SENSITIVITY
1 normal errors
2 normal warnings
4 parser errors
8 notices
display_errors [on | off]
The display_errors [on | off ] configuration directive display the errors in the
browser.
log_errors
The log_errors configuration directive determines whether or not errors are
logged to a file. If log_errors is turned on, the directive error_log designates which
file the errors are logged to.
error_log [filename]
If log_errors is turned on, error_log designates the filename to which all errors
should be logged.
magic_quotes_gpc
When magic_quotes_gpc is activated, all special characters contained in user or
database data will automatically be escaped with the necessary backslash. By the
way, “gpc” stands for “get/post/cookie”.
Personally, I find it more efficient to keep magic_quotes_gpc turned off and to
escape the special characters explicitly. Regardless of the way you ultimately
decide to do it, there can be no compromise or your data may be corrupted. If
magic_quotes_gpc is “on”, then never physically escape special characters with a
backslash; otherwise, make it a habit to always do so.
Php learn in simple manner - Chapter 1
One of the pillars of any programming language is its support for numbers. PHP
supports both integers and real (double) numbers. Each of these number formats
is described in further detail later.
Integer Values
An integer is nothing more than a whole number. Integers are represented as a series
of one or more digits. Some examples of integers are:
5
591
52
31
Octals and Hexadecimals
Integers in octal (base 8) and hexadecimal (base 16) formats are supported. Octal
values begin with the digit 0, followed by a sequence of digits, each ranging from 0
to 7. Some examples of octal integers are:
0422
0534
Hexadecimal integers can consist of the digits 0 through 9 or the letters a (A)
through f (F). All hexadecimal integers are preceded by 0x or 0X. Some examples
of hexadecimal integers are:
0x3FF
0X22abc
Floating-Point Numbers
A floating-point number is essentially a real numbers, that is, a number denoted
either wholly or in part by a fraction. Floating-point numbers are useful for representing
values that call for a more accurate representation, such as temperature
or monetary figures. PHP supports two floating-point formats: standard notation
and scientific notation.
Standard Notation
Standard notation is a convenient representation typically used for real numbers,
for example, monetary values. Some examples are:
12.45
98.6
Scientific Notation
Scientific notation is a more convenient representation for very large and very
small numbers, such as interplanetary distances or atomic measurements. Some
examples include:
3e8
5.9736e24
Chapter 2
32
An Introduction to PHP
An Introduction to PHP
The past five years have been fantastic in terms of the explosive growth of the
Internet and the new ways in which people are able to communicate with one
another. Spearheading this phenomenon has been the World Wide Web (WWW),
with thousands of new sites being launched daily and consumers being consistently
offered numerous outstanding services via this new communications
medium. With this exploding market has come a great need for new technologies
and developers to learn these technologies. Chances are that if you are reading
this paragraph, you are one of these Web developers or are soon to become one.
Regardless of your profession, you’ve picked this book up because you’ve heard of
the great new technology called PHP.
This chapter introduces the PHP language, discusses its history and capabilities,
and provides the basic information you need to begin developing PHPenabled
sites. Several examples are provided throughout, hopefully serving to
excite you about what PHP can offer you and your organization. You will learn
how to install and configure the PHP software on both Linux/UNIX and Windows
machines, and you will learn how to embed PHP in HTML. At the conclusion of
the chapter, you will be ready to begin delving into the many important aspects of
the PHP language. So light the fire, turn on your favorite jazz album, and curl up
on the language.
definitions of php on web
The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.
www.webasyst.net/glossary.htm
PHP is a server-side, cross-platform, HTML embedded scripting language that lets you create dynamic web pages. PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally c reate regular HTML pages.
www.acad.bg/beginner/gnrt/appendix/glossary.html
PHP: Hypertext Preprocessor is an open source server side programming language extensively used for web scripts and to process data passed via the Common Gateway Interface from HTML forms etc. PHP can be written as scripts that reside on the server and may produce HTML output that downloads to the web browser. Alternatively, PHP can be embedded within HTML pages that are then saved with a .php file extension. ...
www.smallbizonline.co.uk/glossary_of_internet_terms.php
(Short for Hypertext Pre-processor) is a server-side, HTML embedded scripting language used to create dynamic Web content. PHP scripts can be embedded in HTML code and use similar syntax to the Perl and C programming languages.
www.greencomputer.com/solutions/glossary.shtml
(Hypertext Preprocessor) open source, server-side HTML scripting languaage used to create dynamic Web pages. PHP is embedded within tags, so the author authorr can move between HTML and PHP instead of using large amounts of code. Because PHP is executed on the server, the viewer cannot see the code. PHP can perform the same tasks as a CGI program can do and is compatible with many different kinds of databases.
mason.gmu.edu/~montecin/netterms.htm
Personal Home Page. Advanced scripting language for site design.
webmaster.lycos.co.uk/glossary/P/
PHP: Hypertext Preprocessor. A script language and interpreter that is freely available and used primarily on Linux Web servers. PHP is an alternative to Microsoft's Active Server Page (ASP) technology. As with ASP, the PHP script is embedded within a Web page along with its HTML. Before the page is sent to a user that has requested it, the Web server calls PHP to interpret and perform the operations called for in the PHP script.
www.netproject.com/docs/migoss/v1.0/glossary.html
PHP is a recursive acronym for "PHP Hypertext Preprocessor". It is an open source, interpretive, HTML centric, server side scripting language. PHP is especially suited for Web development and can be embedded into HTML pages. Also see PSP, JSP and ASP.
www.orafaq.org/glossary/faqglosp.htm
A scripting language used to create database interactivity and dynamic content on the Web. Often used with MySQL. PHP is an open source language that can be used on multiple platforms.
www.hostingconsumerreport.org/glossary.htm
In Web programming, PHP is a script language and interpreter that is freely available and used primarily on Linux Web servers. PHP (the initials come from the earliest version of the program, which was called "Personal Home Page Tools") is an alternative to Microsoft's Active Server Page (ASP) technology.
www.marketing.org.nz/emarket_dictionary.php
An open-source, server-side scripting language used to create dynamic web pages.
www.webhostworld.co.uk/glossary.htm
Self-referentially short for PHP: Hypertext Preprocessor, an open source, server-side, HTML embedded scripting language used to create Dynamic Web pages. Files created with PHP have the file extension .php.
www.brontedesign.com/glossary.asp
PHP is an HTML-embedded web scripting language. This means PHP code can be inserted into the HTML of a web page. When a PHP page is accessed the PHP code is read or "parsed" by the server the page resides on. The output from the PHP functions on the page are typically returned as HTML code which can be read by the browser. Because the PHP code is transformed into HTML before the page is loaded users cannot view the PHP code on a page. ...
www.netchico.com/support/glossary/p.html
One of the most popular server-side scripting languages on the web. PHP is open-source, and noted for its efficiency and suitability for developing web applications.
www.aardvarkmedia.co.uk/glossary.html
Shell – PHP Shells or any likeness thereof are prohibited. Files with any reference to PHP Shells or likeness thereof are prohibited.
visiblebits.com/terms/
is a recursive acronym for PHP: Hypertext Preprocessor. It is a popular server-side scripting language designed specifically for integration with HTML, and is used (often in conjunction with MySQL) in Content Management Systems and other web applications. It is available on many platforms, including Windows, Unix/Linux and Mac OS X, and is open source software.
codex.xwd.jp/index.php/Glossary
PHP(http://www.php.net/) is a server-side, interpreted programming language designed specifically for Web programming. It is closely integrated with Web server technology so does not use the CGI.
www.bized.ac.uk/educators/16-19/business/marketing/lesson/sup_glossary.htm
PHP is a robust programming language, similar to Microsoft's Active Server Page technology, except that it runs on UNIX servers, rather than Windows based servers. It is used for connecting to a database to create all kinds of web applications, such as product catalogs, changing content, calendars, and e commerce.
www.glaserweb.com/glossary.php
A script programming language that can be embedded into HTML. In effect, it turns your HTML pages into a program that is run by the Web server before being displayed, allowing you to customize your site's Web pages on the fly.
www.indra.com/support/glossary.html
PHP hypertext preprocessor is a widely-used general-purpose scripting language that is especially suited for web development (http://www.php.net/).
www.jisc.ac.uk/index.cfm
A server side language similar to ASP in functionality. PHP is open source and is used to create dynamic web pages. Pages implementing PHP end with a .php file extension.
www.optymise.co.nz/resources/glossary.asp
A script language and interpreter that can be embedded within HTML web pages and used to access information from a database or some other form of back-office system. Originally derived from Personal Home Page Tools, but now stands for PHP: Hypertext Pre-processor.
www.fluvius.co.uk/faq_glossary/glossary.htm
Very similar to shtml but utilizes PHP to do its work.
www.saugus.net/Computer/Extensions/Letter/P/
This acronym stands for PHP Hypertext Preprocessor (I haven’t quite worked that out yet...). It is programming language that is run on the web server. Not all web hosts support PHP, especially the free or cheaper packages, so worth checking before before using gallery software that depends on PHP.Web pages containg PHP have a .php extension.
frameroom.com/html/glossary.html
Is an abbreviation for Hypertext Pre-Processor.
www.c7.ca/glossary/
The Philippine peso (Filipino: piso) is the official currency of the Philippines. The word piso derives from the Spanish word peso, which means "weight". It is divided into 100 centavos or sentimos. Its ISO 4217 code is "PHP".
en.wikipedia.org/wiki/PhP
PHP is a popular open-source programming language used primarily for developing server-side applications and dynamic web content, and more recently, other software. The name is a recursive acronym for "PHP: Hypertext Preprocessor". This is actually a retronym; see history of PHP.
en.wikipedia.org/wiki/PHP
www.webasyst.net/glossary.htm
PHP is a server-side, cross-platform, HTML embedded scripting language that lets you create dynamic web pages. PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally c reate regular HTML pages.
www.acad.bg/beginner/gnrt/appendix/glossary.html
PHP: Hypertext Preprocessor is an open source server side programming language extensively used for web scripts and to process data passed via the Common Gateway Interface from HTML forms etc. PHP can be written as scripts that reside on the server and may produce HTML output that downloads to the web browser. Alternatively, PHP can be embedded within HTML pages that are then saved with a .php file extension. ...
www.smallbizonline.co.uk/glossary_of_internet_terms.php
(Short for Hypertext Pre-processor) is a server-side, HTML embedded scripting language used to create dynamic Web content. PHP scripts can be embedded in HTML code and use similar syntax to the Perl and C programming languages.
www.greencomputer.com/solutions/glossary.shtml
(Hypertext Preprocessor) open source, server-side HTML scripting languaage used to create dynamic Web pages. PHP is embedded within tags, so the author authorr can move between HTML and PHP instead of using large amounts of code. Because PHP is executed on the server, the viewer cannot see the code. PHP can perform the same tasks as a CGI program can do and is compatible with many different kinds of databases.
mason.gmu.edu/~montecin/netterms.htm
Personal Home Page. Advanced scripting language for site design.
webmaster.lycos.co.uk/glossary/P/
PHP: Hypertext Preprocessor. A script language and interpreter that is freely available and used primarily on Linux Web servers. PHP is an alternative to Microsoft's Active Server Page (ASP) technology. As with ASP, the PHP script is embedded within a Web page along with its HTML. Before the page is sent to a user that has requested it, the Web server calls PHP to interpret and perform the operations called for in the PHP script.
www.netproject.com/docs/migoss/v1.0/glossary.html
PHP is a recursive acronym for "PHP Hypertext Preprocessor". It is an open source, interpretive, HTML centric, server side scripting language. PHP is especially suited for Web development and can be embedded into HTML pages. Also see PSP, JSP and ASP.
www.orafaq.org/glossary/faqglosp.htm
A scripting language used to create database interactivity and dynamic content on the Web. Often used with MySQL. PHP is an open source language that can be used on multiple platforms.
www.hostingconsumerreport.org/glossary.htm
In Web programming, PHP is a script language and interpreter that is freely available and used primarily on Linux Web servers. PHP (the initials come from the earliest version of the program, which was called "Personal Home Page Tools") is an alternative to Microsoft's Active Server Page (ASP) technology.
www.marketing.org.nz/emarket_dictionary.php
An open-source, server-side scripting language used to create dynamic web pages.
www.webhostworld.co.uk/glossary.htm
Self-referentially short for PHP: Hypertext Preprocessor, an open source, server-side, HTML embedded scripting language used to create Dynamic Web pages. Files created with PHP have the file extension .php.
www.brontedesign.com/glossary.asp
PHP is an HTML-embedded web scripting language. This means PHP code can be inserted into the HTML of a web page. When a PHP page is accessed the PHP code is read or "parsed" by the server the page resides on. The output from the PHP functions on the page are typically returned as HTML code which can be read by the browser. Because the PHP code is transformed into HTML before the page is loaded users cannot view the PHP code on a page. ...
www.netchico.com/support/glossary/p.html
One of the most popular server-side scripting languages on the web. PHP is open-source, and noted for its efficiency and suitability for developing web applications.
www.aardvarkmedia.co.uk/glossary.html
Shell – PHP Shells or any likeness thereof are prohibited. Files with any reference to PHP Shells or likeness thereof are prohibited.
visiblebits.com/terms/
is a recursive acronym for PHP: Hypertext Preprocessor. It is a popular server-side scripting language designed specifically for integration with HTML, and is used (often in conjunction with MySQL) in Content Management Systems and other web applications. It is available on many platforms, including Windows, Unix/Linux and Mac OS X, and is open source software.
codex.xwd.jp/index.php/Glossary
PHP(http://www.php.net/) is a server-side, interpreted programming language designed specifically for Web programming. It is closely integrated with Web server technology so does not use the CGI.
www.bized.ac.uk/educators/16-19/business/marketing/lesson/sup_glossary.htm
PHP is a robust programming language, similar to Microsoft's Active Server Page technology, except that it runs on UNIX servers, rather than Windows based servers. It is used for connecting to a database to create all kinds of web applications, such as product catalogs, changing content, calendars, and e commerce.
www.glaserweb.com/glossary.php
A script programming language that can be embedded into HTML. In effect, it turns your HTML pages into a program that is run by the Web server before being displayed, allowing you to customize your site's Web pages on the fly.
www.indra.com/support/glossary.html
PHP hypertext preprocessor is a widely-used general-purpose scripting language that is especially suited for web development (http://www.php.net/).
www.jisc.ac.uk/index.cfm
A server side language similar to ASP in functionality. PHP is open source and is used to create dynamic web pages. Pages implementing PHP end with a .php file extension.
www.optymise.co.nz/resources/glossary.asp
A script language and interpreter that can be embedded within HTML web pages and used to access information from a database or some other form of back-office system. Originally derived from Personal Home Page Tools, but now stands for PHP: Hypertext Pre-processor.
www.fluvius.co.uk/faq_glossary/glossary.htm
Very similar to shtml but utilizes PHP to do its work.
www.saugus.net/Computer/Extensions/Letter/P/
This acronym stands for PHP Hypertext Preprocessor (I haven’t quite worked that out yet...). It is programming language that is run on the web server. Not all web hosts support PHP, especially the free or cheaper packages, so worth checking before before using gallery software that depends on PHP.Web pages containg PHP have a .php extension.
frameroom.com/html/glossary.html
Is an abbreviation for Hypertext Pre-Processor.
www.c7.ca/glossary/
The Philippine peso (Filipino: piso) is the official currency of the Philippines. The word piso derives from the Spanish word peso, which means "weight". It is divided into 100 centavos or sentimos. Its ISO 4217 code is "PHP".
en.wikipedia.org/wiki/PhP
PHP is a popular open-source programming language used primarily for developing server-side applications and dynamic web content, and more recently, other software. The name is a recursive acronym for "PHP: Hypertext Preprocessor". This is actually a retronym; see history of PHP.
en.wikipedia.org/wiki/PHP
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
Subscribe to:
Posts (Atom)