By Rasmus Lerdorf, Kevin Tatroe
Cover | Table of Contents | Colophon
http://gtk.php.net), you can write
full-blown, cross-platform GUI applications in PHP.
http://gtk.php.net), you can write
full-blown, cross-platform GUI applications in PHP.
http://pear.php.net.
From: rasmus@io.org (Rasmus Lerdorf) Subject: Announce: Personal Home Page Tools (PHP Tools) Date: 1995/06/08 Message-ID: <3r7pgp$aa1@ionews.io.org>#1/1 organization: none newsgroups: comp.infosystems.www.authoring.cgi Announcing the Personal Home Page Tools (PHP Tools) version 1.0. These tools are a set of small tight cgi binaries written in C. They perform a number of functions including: . Logging accesses to your pages in your own private log files . Real-time viewing of log information . Providing a nice interface to this log information . Displaying last access information right on your pages . Full daily and total access counters . Banning access to users based on their domain . Password protecting pages based on users' domains . Tracking accesses ** based on users' e-mail addresses ** . Tracking referring URL's - HTTP_REFERER support . Performing server-side includes without needing server support for it . Ability to not log accesses from certain domains (ie. your own) . Easily create and display forms . Ability to use form information in following documents Here is what you don't need to use these tools: . You do not need root access - install in your ~/public_html dir . You do not need server-side includes enabled in your server . You do not need access to Perl or Tcl or any other script interpreter . You do not need access to the httpd log files The only requirement for these tools to work is that you have the ability to execute your own cgi programs. Ask your system administrator if you are not sure what this means. The tools also allow you to implement a guestbook or any other form that needs to write information and display it to users later in about 2 minutes. The tools are in the public domain distributed under the GNU Public License. Yes, that means they are free! For a complete demonstration of these tools, point your browser at: http://www.io.org/~rasmus -- Rasmus Lerdorf rasmus@io.org http://www.io.org/~rasmus
http://www.php.net
and http://www.apache.org,
respectively. Store the files in the same directory, so that you
have:
-rw-r--r-- 1 gnat wheel 2177983 Oct 9 09:34 apache_1.3.22.tar.gz -rw-r--r-- 1 gnat wheel 3371385 Dec 10 14:29 php-4.1.1.tar.gz
# gunzip -c apache_1.3.22.tar.gz | tar xf - # gunzip -c php-4.1.1.tar.gz | tar xf -
drwxr-xr-x 8 gnat wheel 512 Dec 16 11:26 apache_1.3.22 drwxr-xr-x 16 gnat wheel 2048 Dec 21 23:48 php-4.1.1
--prefix=/some/path option to
Apache's configure to change
where Apache expects its configuration files and utilities.
Similarly, typical options for PHP include
--with-apache to identify the location of the
Apache source tree, --enable-inline-optimizations
to enable compilation options that give a faster PHP interpreter, and
--with-mysql to identify where MySQL was
installed. Each configuration creates detailed output as it goes:
# cd apache_1.3.22
# ./configure --prefix=/usr/local/apache
Configuring for Apache, Version 1.3.22
+ using installation path layout: Apache (config.layout)
Creating Makefile
Creating Configuration.apaci in src
Creating Makefile in src
+ configured for FreeBSD 4.2 platform
+ setting C compiler to gcc
...
# cd ../php-4.1.1
# ./configure --with-apache=../apache_1.3.22 --enable-inline-optimization \
--with-mysql=/usr
creating cache ./config.cache
checking for a BSD compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking whether make sets ${MAKE}... yes
checking for working aclocal... missing
checking for working autoconf... found
checking for working automake... missing
checking for working autoheader... found
checking for working makeinfo... found
Updated php_version.h
...<html>
<head>
<title>Look Out World</title>
</head>
<body>
<?php echo 'Hello, world!' ?>
</body>
</html>
echo
command produces output (the string
"Hello, world!"), which is inserted
into the HTML file. In this example, the
PHP code is placed between
<?php and ?> tags. There
are other ways to tag your PHP code—see Chapter 2 for a full description.
phpinfo(
) creates an HTML page full of information on how
PHP was installed. You can use it to
see whether you have particular extensions installed, or whether the
php.ini file has been customized. Example 1-2 is a complete page that displays the
phpinfo( ) page.
<?php phpinfo( ); ?>
<html>
<head>
<title>Personalized Hello World</title>
</head>
<body>
<?php if(!empty($_POST['name'])) {
echo "Greetings, {$_POST['name']}, and welcome.";
} ?>
<form action="<?php echo $PHP_SELF; ?>" method="post">
Enter your name: <input type="text" name="name" />
<input type="submit" />
</form>
</body>
</html>echo,
while, class, etc., are
case-insensitive. Thus, these three lines are equivalent:
echo("hello, world");
ECHO("hello, world");
EcHo("hello, world");$name,
$NAME, and $NaME are three
different variables.
if test:
echo "Hello, world";
myfunc(42, "O'Reilly");
$a = 1;
$name = "Elphaba";
$b = $a / 25.0;
if ($a == $b) { echo "Rhyme? And Reason?"; }if ($needed) {
echo "We must have it!"; // semicolon required here
} // no semicolon required hereecho,
while, class, etc., are
case-insensitive. Thus, these three lines are equivalent:
echo("hello, world");
ECHO("hello, world");
EcHo("hello, world");$name,
$NAME, and $NaME are three
different variables.
if test:
echo "Hello, world";
myfunc(42, "O'Reilly");
$a = 1;
$name = "Elphaba";
$b = $a / 25.0;
if ($a == $b) { echo "Rhyme? And Reason?"; }if ($needed) {
echo "We must have it!"; // semicolon required here
} // no semicolon required here<?php
if ($a == $b) { echo "Rhyme? And Reason?"; }
echo "Hello, world" // no semicolon required before closing tag
?>+) or
minus (-) sign. If there is no sign, positive is
assumed. Examples of decimal integers include the following:
1998 -641 +33
0755 // decimal 493 +010 // decimal 8
0xFF // decimal 255 0x10 // decimal 16 -0xDAD1 // decimal -56017
is_int( )
function (or its is_integer(
) alias) to test whether a value is an integer:
if (is_int($x)) {
// $x is an integer
}$). For
example:
$name $Age $_debugging $MAXIMUM_IMPACT
$what = "Fred";
$what = 35;
$what = array('Fred', '35', 'Wilma');$day = 60 * 60 * 24;
echo "There are $day seconds in a day.\n";
There are 86400 seconds in a day.
NULL value:if ($uninitialized_variable === NULL) {
echo "Yes!";
}
Yes!
$foo = 'bar'; $$foo = 'baz';
$bar has the value "baz".
$black an alias for the variable
$white, use:
$black =& $white;
$black is lost. Instead,
$black is now another name for the value that is
stored in $white:
$big_long_variable_name = "PHP"; $short =& $big_long_variable_name; $big_long_variable_name .= " rocks!"; print "\$short is $short\n"; print "Long is $big_long_variable_name\n"; $short is PHP rocks! Long is PHP rocks! $short = "Programming $short"; print "\$short is $short\n"; print "Long is $big_long_variable_name\n"; $short is Programming PHP rocks! Long is Programming PHP rocks!
$white = "snow";
$black =& $white;
unset($white);
print $black;
snow
+
and - familiar to us from math. Some operators
modify their operands, while most do not.
|
P
|
A
|
Operator
|
Operation
|
|---|---|---|---|
|
19
|
N
|
new |
Create new object
|
|
18
|
R
|
[ |
Array subscript
|
|
17
|
R
|
! |
Logical NOT
|
|
R
|
~ |
Bitwise NOT
| |
|
R
|
if/else and
switch, allow a program to execute different
pieces of code, or none at all, depending on some condition.
Loops, such as
while and for, support the
repeated execution of particular code.
if
statement checks the truthfulness of
an expression and, if the expression is true, evaluates a statement.
An if statement looks like:
if (expression) statement
else
keyword:
if (expression) statement else statement
if ($user_validated) echo "Welcome!"; else echo "Access Forbidden!";
if
statement, use a
block
—a curly brace-enclosed set of
statements:
if ($user_validated) {
echo 'Welcome!";
$greeted = 1;
} else {
echo "Access Forbidden!";
exit;
}if line with a colon (:) and
use a specific keyword to end the block (endif, in
this case). For example:
if ($user_validated) : echo "Welcome!"; $greeted = 1; else : echo "Access Forbidden!"; exit; endif;
<?if($user_validated):?>
<table>
<tr>
<td>First Name:</td><td>Sophia</td>
</tr>
<tr>
<td>Last Name:</td><td>Lee</td>
</tr>
</table>
<?else:?>
Please log in.
<?endif?>if
is a statement, you can chain
them:
if ($good)
print('Dandy!');
else
if ($error)
print('Oh, no!');
else
print("I'm ambivalent...");require and
include. They both load a file as the PHP script
runs, work in conditionals and loops, and complain if the file being
loaded can't be found. The main difference is that
attempting to require a nonexistent file is a
fatal error, while attempting to include such a
file produces a warning but does not stop script execution.
include is to separate
page-specific content from general site design. Common elements such
as headers and footers go in separate HTML files, and each page then
looks like:
<? include 'header.html'; ?>
content
<? include 'footer.html'; ?>include because it allows PHP to continue
to process the page even if there's an error in the
site design file(s). The require construct is less
forgiving and is more suited to loading code libraries, where the
page can't be displayed if the libraries
don't load. For example:
require 'codelib.inc'; mysub( ); // defined in codelib.inc
<? require 'design.inc';
header( );
?>
content
<? footer( ); ?>include or require, a warning
is printed and execution continues. You can silence the warning by
prepending the call with the silence operator; for example,
@include.
allow_url_fopen option is enabled through
PHP's configuration file,
php.ini, you can include files from a remote
site by providing a URL instead of a simple local path:
include 'http://www.example.com/codelib.inc';
include and
require can be arbitrarily named. Common
extensions are .php, .inc,
and .html. Note that remotelyfetching a file that ends in .php
from a web server that has PHP enabled fetches the
output of that PHP script. For this reason, we
recommend you use <script> tag; this makes it easy to edit
pages with enabled PHP using a regular HTML editor.
<?php and
?>. Everything between these markers is
interpreted as PHP, and everything outside the markers is not.
Although it is not necessary to include spaces between the markers
and the enclosed text, doing so improves readability. For example, to
get PHP to print "Hello, world",
you can insert the following line in a web page:
<?php echo "Hello, world"; ?>
<!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <title>This is my first PHP program!</title> </head> <body> <p> Look, ma! It's my first PHP program:<br /> <?php echo "Hello, world"; ?><br /> How cool is that? </p> </body> </html>
$some_value = function_name( [ parameter, ... ] );
// strlen( ) is a built-in function that returns the length of a string
$length = strlen("PHP"); // $length is now 3
// sin() and asin( ) are the sine and arcsine math functions
$result = sin(asin(1)); // $result is the sine of arcsin(1), or 1.0
// unlink( ) deletes a file
$result = unlink("functions.txt"); // false if unsuccessful"PHP",
to the function strlen( ), which gives us the
number of characters in the string it's given. In
this case, it returns 3, which is assigned to the
variable $length. This is the simplest and most
common way to use a function.
$some_value = function_name( [ parameter, ... ] );
// strlen( ) is a built-in function that returns the length of a string
$length = strlen("PHP"); // $length is now 3
// sin() and asin( ) are the sine and arcsine math functions
$result = sin(asin(1)); // $result is the sine of arcsin(1), or 1.0
// unlink( ) deletes a file
$result = unlink("functions.txt"); // false if unsuccessful"PHP",
to the function strlen( ), which gives us the
number of characters in the string it's given. In
this case, it returns 3, which is assigned to the
variable $length. This is the simplest and most
common way to use a function.
asin(1)
to the sin( )
function. Since the sine and arcsine functions are reflexive, taking
the sine of the arcsine of any value will always return that same
value.
unlink(
)
function, which attempts to delete
the file. Like many functions, it returns false
when it fails. This allows you to use another built-in function,
die( )
, and the short-circuiting property of
the logic operators. Thus, this example might be rewritten as:
$result = unlink("functions.txt") or die("Operation failed!");unlink( ) function,
unlike the other two examples, affects something outside of the
parameters given to it. In this case, it deletes a file from the
filesystem. All such side effects of a function should be carefully
documented.
function [&] function_name ( [ parameter [, ... ] ] ) { statement list }
column( )
function simply gives a convenient
short name to HTML code that may be needed many times throughout the
page:
<? function column( ) { ?>
</td><td>
<? } ?>sin( ) function as
sin(1), SIN(1),
SiN(1), and so on, because all these names refer
to the same function.
return
statement: put return
expr inside your function. When a
return statement is encountered during execution,
control reverts to the calling statement, and the evaluated results
of expr will be returned as the value of
the function. Although it can make for messy code, you can actually
include multiple return statements in a function
if it makes sense (for example, if you have a
switch statement to determine which of several
values to return).
function strcat($left, $right) {
$combined_string = $left . $right;
return $combined_string;
}$left and
$right. Using the concatenation operator, the
function creates a combined string in the variable
$combined_string. Finally, in order to cause the
function to have a value when it's evaluated with
our arguments, we return the value
$a = 3;
function foo( ) {
$a += 2;
}
foo( );
echo $a;$a inside the function foo(
) is a different variable than the variable
$a outside the variable; even though foo(
) uses the add-and-assign operator, the value of the outer
$a remains 3 throughout the
life of the page. Inside the function, $a has the
value 2.
$a will be 5
by the time the echo statement is reached, so keep
that in mind when choosing names for your variables.
global
keyword.
Its syntax is:
global var1, var2, ...
global
keyword, we get:
$a = 3;
function foo( ) {
global $a;
$a += 2;
}
foo( );
echo $a;$a with
function-level scope, PHP uses the global $a
within the function. Now, when the value of $a is
displayed, it will be 5.
global keyword in a function
before any uses of the global variable or variables you want to
access. Because they are declared before the body of the function,
function parameters can never be global variables.
&). Example 3-5 revisits our
doubler( ) function with a slight change.
function doubler(&$value) {
$value = $value << 1;
}
$a = 3;
doubler($a);
echo $a;$value
parameter is passed by reference, the actual value of
$a, rather than a copy of that value, is modified
by the function. Before, we had to return the
doubled value, but now we change the caller's
variable to be the doubled value.
$a into doubler( ) by
reference, the value of $a is at the mercy of the
function. In this case, doubler( ) assigns a new
value to it.
<?=
doubler(7);
?> in the previous example, it would issue an
error.
function return_one() {
return 42;
}function return_two ( ) {
return array("Fred", 35);
}& before its name returns a
reference (alias) to its return value:
$names = array("Fred", "Barney", "Wilma", "Betty");
function & find_one($n) {
return $names[$n];
}
$person =& find_one(1); // Barney
$person = "Barnetta"; // changes $names[1]find_one( ) function returns an
alias for $names[1], instead of a copy of its
value. Because we assign by reference, $person is
an alias for $names[1], and the second assignment
changes the value in $names[1].
switch($which) {
case 'first':
first( );
break;
case 'second':
second( );
break;
case 'third':
third( );
break;
}$which(); // if $which is "first" the function first( ) is called, etc...
function_exists( ) to determine whether a
function exists for the value of the variable before calling the
function:
$yes_or_no = function_exists(function_name);if(function_exists($which)) {
$which(); // if $which is "first" the function first( ) is called, etc...
}echo( ) and
isset( ) cannot be called through variable
functions:
$f = 'echo';
$f('hello, world'); // does not workusort( ) function uses a
function you create and pass to it as a parameter to determine the
sort order of the items in an array.
create_function(
)
. This function takes two
parameters—the first describes the parameters the anonymous
function takes in, and the second is the actual code. A randomly
generated name for the function is returned:
$func_name = create_function(args_string, code_string);
usort( )
.
$lambda = create_function('$a,$b', 'return(strlen($a) - strlen($b));');
$array = array('really long string here, boy', 'this', 'middling length', 'larger');
usort($array, $lambda);
print_r($array);usort( ), using the
anonymous function, in order of string length.
$who = 'Kilroy';
$where = 'here';
echo "$who was $where";
Kilroy was here
$n = 12;
echo "You are the {$n}th person";$who = 'Kilroy';
$where = 'here';
echo "$who was $where";
Kilroy was here
$n = 12;
echo "You are the {$n}th person";
You are the 12th person
$nth variable.
$bar = 'this is not printed';
$foo = '$bar'; // single quotes
print("$foo");
$bar
echo construct lets you print many values at once,
while print( ) prints only one value. The
printf( ) function builds a formatted string by
inserting values into a template. The print_r( )
function is useful for debugging—it prints the contents of
arrays, objects, and other things, in a more-or-less human-readable
form.
echo. While it
looks—and for the most part behaves—like a function,
echo is a language construct. This means that you
can omit the parentheses, so the following are equivalent:
echo "Printy";
echo("Printy"); // also validecho "First", "second", "third";
Firstsecondthird
// this is a parse error
echo("Hello", "world");echo is not a true function, you
can't use it as part of a larger expression:
// parse error
if (echo("test")) {
echo("it worked!");
}print(
) or printf( ) functions.
print( )
function sends one value
(its argument) to the browser. It returns true if
the string was successfully displayed and false
otherwise (e.g., if the user pressed the Stop button on her browser
before this part of the page was rendered):
if (! print("Hello, world")) {
die("you're not listening to me!");
}
Hello, world
printf( )
function
outputs a string built by substituting
values into a template (the format string). It
is derived from the function of the same name in the standard C
library. The first argument to printf( ) is the
format string. The remaining arguments are the values to be
substituted in. A % character in the format string
indicates a substitution.
strlen( ) function returns the
number of characters in a string:
$string = 'Hello, world'; $length = strlen($string); // $length is 12
$string = 'Hello';
for ($i=0; $i < strlen($string); $i++) {
printf("The %dth character is %s\n", $i, $string[$i]);
}
The 0th character is H
The 1th character is e
The 2th character is l
The 3th character is l
The 4th character is o
trim( ), ltrim( ), and rtrim( ) functions:
$trimmed = trim(string [, charlist ]); $trimmed = ltrim(string [, charlist ]); $trimmed = rtrim(string [, charlist ]);
trim( ) returns a copy of
string with whitespace removed from the
beginning and the end. ltrim( ) (the
l is for left) does the
same, but removes whitespace only from the start of the string.
rtrim( ) (the r is for
right) removes whitespace only from the end of
the string.
The optional
charlist argument is a string that
specifies all the characters to strip. The default characters to
strip are given in Table 4-3.
|
Character
|
ASCII value
|
Meaning
|
|---|---|---|
" " |
0x20
|
Space
|
"\t" |
0x09
|
Tab
|
"\n" |
0x0A
|
Newline (line feed)
|
"\r" |
0x0D
|
Carriage return
|
"\0" |
0x00
|