Cover | Table of Contents
http://www.php.net for availability details.
http://www.php.net for availability details.
AddType application/x-httpd-php3 .php3
LoadModule php3_module modules/libphp3.so
ScriptAlias /php3/ "/path-to-php-dir/php.exe" AddType application/x-httpd-php3 .php3 Action application/x-httpd-php3 "/php3/php.exe"
<HTML><HEAD><TITLE><?echo $title?></TITLE> </HEAD>...
<?echo $title?> portion of the document
is replaced by the contents of the $title PHP
variable. echo is a basic language statement that
you can use to output data.
<?
and ?> tags:
<? echo "Hello World"; ?>
short_open_tag directive. Another way to embed PHP
code is within <?php and
?> tags:
<?php echo "Hello World"; ?>
<SCRIPT> tags is another style that is
always available:
<SCRIPT LANGUAGE="php" > echo "Hello World"; </SCRIPT>
<%
and %> tags, is disabled by default:
<% echo "Hello World"; %>
asp_tags
directive in your php3.ini file. The style is
most useful when you are using Microsoft FrontPage or another HTML
authoring tool that prefers that tag style for HTML embedded scripts.
<? echo "Hello World"; echo "A second statement"; ?>
<BR> tags for some reason, you can do it
this way:
<? for($i=0; $i<100; $i++) { ?>
<BR>
<? } ?>
$A and $a are two distinct
variables. However, function names in PHP are not case-sensitive.
This applies to both built-in functions and user-defined functions.
/* C style comments */ // C++ style comments # Bourne shell style comments
$). The $ is followed by an
alphabetic character or an underscore, and optionally followed by a
sequence of alphanumeric characters and underscores. There is no
limit on the length of a variable. Variable names in PHP are
case-sensitive. Here are some examples:
$i $counter $first_name $_TMP
$var = "hello";
$var variable. You can do that like this:
$$var = "World";
$$var by first dereferencing the
innermost variable, meaning that $var becomes
"hello". The expression that is left is then
$"hello", which is just $hello.
In other words, we have just created a new variable named
hello and assigned it the value
"World". You can nest dynamic variables to an
infinite level in PHP, although once you get beyond two levels, it
can be very confusing for someone who is trying to read your code.
echo "Hello ${$var}";
$$var[1] is ambiguous because it is impossible for
PHP to know which level to apply the array index to.
${$var[1]} tells PHP to dereference the inner
level first and apply the array index to the result before
dereferencing the outer level. ${$var}[1], on the
other hand, tells PHP to apply the index to the outer level.
$array["abc"] = "Hello"; $array["def"] = "World";
long data type in
C. On 32-bit platforms, integer values can range from -2,147,483,648
to +2,147,483,647. PHP automatically converts larger values to
floating point numbers if you happen to overflow the range. An
integer can be expressed in decimal (base-10), hexadecimal (base-16),
or octal (base-8). For example:
$decimal=16; $hex=0x10; $octal=020;
double type in C. On most platforms a double can
range from 1.7E-308 to 1.7E+308. A double may be expressed either as
a regular number with a decimal point or in scientific notation. For
example:
$var=0.017; $var=17.0E-3
'PHP is cool' "Hello, World!"
$a="World"; echo "Hello\t$a\n";
$a and
the escape sequences are converted to their corresponding characters.
Contrast that with:
echo 'Hello\t$a\n';
|
Escape Sequence
|
Meaning
|
|---|---|
\n |
Newline
|
\t |
Tab
|
\r |
Carriage return
|
\\ |
Backslash
|
5 5+5 $a $a==5 sqrt(9)
echo statement we've used in
numerous examples cannot be part of a complex expression because it
does not have a return value. The print statement,
on the other hand, can be used as part of complex expression, as it
does have a return value. In all other respects,
echo and print are
identical—they output data.
|
Operators
|
P
|
A
|
|---|---|---|
!, ~, ++,
--, @, (the casting operators)
|
16
|
Right
|
*, /, % |
15
|
Left
|
+, - . |
14
|
Left
|
<<, >> |
13
|
Left
|
<, <=,
>=, >
|
12
|
Non-associative
|
==, != |
11
|
Non-associative
|
& |
10
|
Left
|
^ |
9
|
Left
|
| |
8
|
Left
|
&& |
7
|
Left
|
|| |
6
|
Left
|
? : (conditional operator) |
5
|
Left
|
=, +=, -=,
*=, /=, %=,
^=, .=,
&=, |=
|
4
|
Left
|
And |
3
|
Left
|
Xor |
2
|
Left
|
Or |
1
|
Left
|
if statement is a standard conditional found
in most languages. Here are the two syntaxes for the
if statement:
if(expr) { if(expr): statements statements } elseif(expr): elseif(expr) { statements statements else: } statements else { endif; statements }
if statement causes particular code to be
executed if the expression it acts on is true.
With the first form, you can omit the braces if you only need to
execute a single statement.
switch statement can be used in place of a
lengthy if statement. Here are the two syntaxes
for switch:
switch(expr) { switch(expr): case expr: case expr: statements statements break; break; default: default: statements statements break; break; } endswitch;
case statement is compared
against the switch expression and, if they match,
the code following that particular case is executed. The
break keyword signals the end of a particular
case; it may be omitted, which causes control to flow into the next
case. If none of the case expressions match the
switch expression, the default
case is executed.
while statement is a looping construct that
repeatedly executes some code while a particular expression is
true:
while(
function keyword. For
example:
function soundcheck($a, $b, $c) {
return "Testing, $a, $b, $c";
}
Fatal error: Can't redeclare already declared function in filename on line N
echo soundcheck(4, 5, 6);
soundcheck( ) function optional:
function soundcheck($a=1, $b=2, $c=3) {
return "Testing, $a, $b, $c";
}
global keyword. For example:
function test( ) {
global $var;
echo $var;
}
$var="Hello World";
test( );
$GLOBALS array is an alternative mechanism for
accessing variables in the global scope. This is an associative array
of all the variables currently defined in the global scope:
<FORM ACTION="test.php3" METHOD="POST"> <INPUT TYPE=text NAME=var> </FORM>
$var variable within that file is set to
whatever the user entered in the text field.
http://your.server/test.php3?var=Hello+World
$var variable is set for the
test.php3 page.
<? phpinfo( ) ?>
$HTTP_GET_DATA,
$HTTP_POST_DATA,
$HTTP_COOKIE_DATA, respectively. For example,
here's another way to access the value of the text field in our
form:
echo $HTTP_POST_VARS["var"];
<HTML><HEAD><TITLE>PHP Example</TITLE></HEAD> <BODY> You are using <? echo $HTTP_USER_AGENT ?><BR> and coming from <? echo $REMOTE_ADDR ?> </BODY></HTML>
You are using Mozilla/4.0 (compatible; MSIE 4.01; Windows 98) and coming from 207.164.141.23
<HTML><HEAD><TITLE>Form Example</TITLE></HEAD>
<BODY>
<H1>Form Example</H1>
<?
function show_form($first="", $last="",
$interest=""){
$options = array("Sports", "Business",
"Travel", "Shopping",
"Computers");
if(empty($interest)) $interest=array(-1);
?>
<FORM ACTION="form.php3" METHOD="POST">
First Name:
<INPUT TYPE=text NAME=first
VALUE="<?echo $first?>">
<BR>
Last Name:
<INPUT TYPE=text NAME=last
VALUE="<?echo $last?>">
<BR>
Interests:
<SELECT MULTIPLE NAME=interest[]>
<?
for($i=0, reset($interest);
$i<count($options); $i++){
echo "<OPTION";
if(current($interest)==$options[$i]) {
echo " SELECTED ";
next($interest);
}
echo "> $options[$i]\n";
}
?>
</SELECT><BR>
<INPUT TYPE=submit>
</FORM>
<? }
if(!isset($first)) {
show_form();
}
else {
if(empty($first) || empty($last) ||
count($interest) == 0) {
echo "You did not fill in all the ";
echo "fields, please try again<P>\n";
show_form($first,$last,$interests);
}
else {
echo "Thank you, $first $last, you ";
echo "selected ". join(" and ", $interest);
echo " as your interests.<P>\n";
}
}
?>
</BODY></HTML>int, double,
string, array,
void, and mixed.
mixed means that the argument or return type can
be of any type. Optional arguments are shown in square brackets.
array array(...)int array_walk(array array_arg, string function)int arsort(array array_arg)int asort(array array_arg)int count(mixed var)mixed current(array array_arg)array each(array array_arg)mixed end(array array_arg)void extract(array var_array, int extract_type [, string prefix]) mixed key(array array_arg)int krsort(array array_arg) int ksort(array array_arg)mixed max(mixed arg1 [, mixed arg2 [, ...]])mixed min(mixed arg1 [, mixed arg2 [, ...]])mixed next(array array_arg)mixed pos(array array_arg)current( )mixed prev(array array_arg)array range(int low, int high) mixed reset(array array_arg)int debugger_off(void)int debugger_on(string ip_address)int error_log(string message, int message_type [, string destination] [, string extra_headers])int error_reporting([int level])string get_cfg_var(string option_name)int get_magic_quotes_gpc(void)magic_quotes_gpc
int get_magic_quotes_runtime(void)magic_quotes_runtime
void phpinfo(void)string phpversion(void)int set_magic_quotes_runtime(int new_setting)magic_quotes_runtime and return the previous value
void set_time_limit(int seconds)int short_tags(int state)int closelog(void)void define_syslog_variables(void)int openlog(string ident, int option, int facility)int syslog(int priority, string message)dbase_pack( ).
Unlike with SQL databases, once a dBase file is created, the database
definition is fixed. There are no indexes that speed searching or
otherwise organize your data. Because of these limitations, I
don't recommend using dBase files as your production database.
Choose a real SQL server, such as MySQL or Postgres, instead. PHP
provides dBase support to allow you to import and export data to and
from your web database, as the format is understood by Windows
spreadsheets and organizers. In other words, the import and export of
data is about all that the dBase support is good for.
bool dbase_add_record(int identifier, array data)bool dbase_close(int identifier)bool dbase_create(string filename, array fields)bool dbase_delete_record(int identifier, int record)array dbase_get_record(int identifier, int record)array dbase_get_record_with_names(int identifier, int record)bool checkdate(int month, int day, int year)string date(string format[, int timestamp])array getdate([int timestamp])array gettimeofday(void)string gmdate(string format[, int timestamp])int gmmktime(int hour, int min, int sec, int mon, int mday, int year)string gmstrftime(string format[, int timestamp]) string microtime(void)int mktime(int hour, int min, int sec, int mon, int mday, int year)string strftime(string format[, int timestamp])int time(void)$handle = opendir('.');
while($entry = readdir($handle)) {
echo "$entry<br>\n";
}
closedir($handle);
dir class that represents a
directory. Here's an example of using this object-oriented
approach to reading a directory:
$d = dir("/etc");
echo "Handle: ".$d->handle."<br>\n";
echo "Path: ".$d->path."<br>\n";
while($entry=$d->read( )) {
echo $entry."<br>\n";
}
$d->close( );
read( ) and close(
) methods, the dir class supports a
rewind( ) method.
int chdir(string directory)void closedir([int dir_handle])dir_handle, or a previously opened directory if
not specified
class dir(string directory)int opendir(string directory)dir_handlestring readdir(int dir_handle)dir_handlevoid rewinddir(int dir_handle)dir_handle back to the startstring basename(string path)int chgrp(string filename, mixed group)int chmod(string filename, int mode)int chown(string filename, mixed user)void clearstatcache(void)int copy(string source_file, string destination_file)string dirname(string path)bool diskfree(string path) int fclose(int fp)int feof(int fp)string fgetc(int fp)array fgetcsv(int fp, int length) string fgets(int fp, int length)string fgetss(int fp, int length [, string allowable_tags])array file(string filename [, int use_include_path])int file_exists(string filename)int fileatime(string filename)int filectime(string filename)int filegroup(string filename)int fileinode(string filename)int filemtime(string filename)int fileowner(string filename)int fileperms(string filename)int filesize(string filename)string filetype(string filename)fifo,
char, block,
link, file, or
unknown)
bool flock(int fp, int operation) int fopen(string filename, string mode [, int use_include_path])Header("Content-type: image/gif");
if(!isset($s)) $s=11;
$size = imagettfbbox($s,0,
"/fonts/TIMES.TTF",$text);
$dx = abs($size[2]-$size[0]);
$dy = abs($size[5]-$size[3]);
$xpad=9; $ypad=9;
$im = imagecreate($dx+$xpad,$dy+$ypad);
$blue = ImageColorAllocate($im,0x2c,0x6D,
0xAF);
$black = ImageColorAllocate($im,0,0,0);
$white = ImageColorAllocate($im,255,255,255);
ImageRectangle($im,0,0,$dx+$xpad-1,
$dy+$ypad-1, $black);
ImageRectangle($im,0,0,$dx+$xpad,$dy+$ypad,
$white);
ImageTTFText($im, $s, 0, (int)($xpad/2)+1,
$dy+(int)($ypad/2), $black,
"/fonts/TIMES.TTF", $text);
ImageTTFText($im, $s, 0, (int)($xpad/2),
$dy+(int)($ypad/2)-1, $white,
"/fonts/TIMES.TTF", $text);
ImageGif($im);
ImageDestroy($im);
<IMG> tag like this:
<IMG SRC="button.php3?s=13&text=Help" >.
ImageGif($im) call to
ImagePng($im).
array getimagesize(string filename [, array info])int imagearc(int im, int cx, int cy, int w, int h, int s, int e, int col)int imagechar(int im, int font, int x, int y, string c, int col)int imagecharup(int im, int font, int x, int y, string c, int col)int header(string str)int headers_sent(void) true if headers have already been sent,
false otherwise
array parse_url(string url)string rawurldecode(string str)string rawurlencode(string str)void setcookie(string name [, string value [, int expire [, string path [, string domain [, int secure ]]]]])string urldecode(string str)string urlencode(string str)class apache_lookup_uri(string URI)string apache_note(string note_name [, string note_value])array getallheaders(void)int virtual(string filename)- - with-imap. That
requires the C-client library to be installed. You can get the latest
version from ftp://ftp.cac.washington.edu/imap/.
string imap_8bit(string text)string imap_alerts(void) int imap_append(int stream_id, string folder, string message [, string flags])string imap_base64(string text)string imap_binary(string text)string imap_body(int stream_id, int msg_no [, int options])object imap_bodystruct(int stream_id, int msg_no, int section)object imap_check(int stream_id)void imap_clearflag_full(int stream_id, string sequence, string flag [, int options])int imap_close(int stream_id [, int options])int imap_create(int stream_id, string mailbox)imap_createmailbox( )int imap_createmailbox(int stream_id, string mailbox)int imap_delete(int stream_id, int msg_no)bool imap_deletemailbox(int stream_id, string mailbox)string imap_errors(void) int imap_expunge(int stream_id)array imap_fetch_overview(int stream_id, int msg_no)string imap_fetchbody(int stream_id, int msg_no, int section [, int options])string imap_fetchheader(int stream_id, int msg_no [, int options])object imap_fetchstructure(int stream_id, int msg_no [, int options])http://www.openldap.org for a PHP-compatible
free LDAP implementation.
int ldap_add(int link, string dn, array entry)int ldap_bind(int link [, string dn, string password])int ldap_close(int link)ldap_unbind( )int ldap_connect([string host [, int port]])int ldap_count_entries(int link, int result)int ldap_delete(int link, string dn)string ldap_dn2ufn(string dn)string ldap_err2str(int errno) int ldap_errno(int link) string ldap_error(int link) array ldap_explode_dn(string dn, int with_attrib)string ldap_first_attribute(int link, int result, int ber)int ldap_first_entry(int link, int result)int ldap_free_result(int result)array ldap_get_attributes(int link, int result)string ldap_get_dn(int link, int result)array ldap_get_entries(int link, int result)array ldap_get_values(int link, int result, string attribute)array ldap_get_values_len(int link, int result, string attribute) int ldap_list(int link, string base_dn, string filter [, string attributes])int ldap_mod_add(int link, string dn, array entry) int ldap_mod_del(int link, string dn, array entry) int ldap_mod_replace(int link, string dn, array entry) int abs(int number)double acos(double number)double asin(double number)double atan(double number)double atan2(double y, double x)y/x,
with the resulting quadrant determined by the signs of
y and x
string base_convert(string number, int frombase, int tobase)int bindec(string binary_number)int ceil(double number)double cos(double number)string decbin(int decimal_number)string dechex(int decimal_number)string decoct(int octal_number)double deg2rad(double degrees)double exp(double number)int floor(double number)int hexdec(string hexadecimal_number)