///Writing PHP

Writing PHP

What can PHP do?

System functions available within PHP include creating, opening, reading from, writing to and
closing files on the server, executing system commands, create directories and modify file permissions in
pre-determined directories. PHP can receive and process data from forms, save data to files, send by
email and output a response to the browser. Some installations of PHP can use databases and generate
tables and content in real time and some can also create images on-the-fly.

Other uses of PHP4 include Java and Java Servlets support, XML parsing,
Acrobat PDF file creation, GZip manipulation, DNS and socket use etc.

PHP is cross platform and available for all types of web servers and has a lower memory
requirement than other server-side languages.

PHP output

With or without database access and graphics
capability, PHP is still a useful language for modern web sites.
The spread of XML and WML is a nightmare for designers of conventional
sites. After so much time dealing with multiple browsers
using the idea of cross-brower pages, there are suddenly two new
formats that cannot be combined with HTML. The thought of writing
two or even three identical sites is enough of a problem, without
considering learning XML and WML. XSLT can be used to export
xHTML – reducing duplication, but WML is not so easy. PHP solves these
problems by allowing the designer to create one set of
PHP files that can output WML, XML, XHTML, DHTML, HTML and any future
flavours of the base language, SGML. If it’s a text based markup
language then PHP can output it. With additional libraries, it can even
handle non-text output like PNG and JPEG graphics.

This
set of PHP files demonstrate this capability. The PHP code creates
variables for the links and the page content, including
titles and headings, then PHP code (identical in each page) formats the
bare content in a manner suitable for WML, XML and HTML. In the case of
the CodeHelp site, the HTML is v4 – DHTML using CSS. In fact it uses
the same CSS stylesheets as the rest of the CodeHelp site. It could
just as easily output HTML3 or a frame based site suitable for older
browsers not capable of using CSS.

The
PHP code looks for a WAP device using the HTTP headers, looks for XSLT
by looking for Microsoft Internet Explorer 5
or later and uses HTML for every other case. Preset blocks of code are
then set only if the browser matches and the content of the variables
are inserted into the output. The actual code downloaded to the browser
shows no sign of the PHP behind it. (The use of these
pages to demonstrate WML output is the reason why these pages are
shorter than others on this site. WML has a strict limit on the total
file size of the downloaded WML code.)

PHP and HTTP: headers and variables

PHP files can contain a mixture of code and you can insert php code anywhere in the document. Code sections begin
with

<?php or <script language="php"

Some PHP installations will allow a shortened tag <? but this will clash with
any XML or WML output so check your phpinfo output for "short_open_tag off" before trying XML and PHP. HTML, XML and WML
code can be entered as a PHP variable using

$variable="my content"

If the content includes text quotes (e.g. tag attributes), use the backslash to "escape" the quotation marks – \" e.g.

$html_output="<html> <body> 
<a href=\"test.php\">test</a> </body> </html>";

The Header function can be used to output formats other than the default HTML. For WML use the PHP command:

Header("Content-type:text/vnd.wap.wml");

Only
set the Header once for each possible non-HTML output of the PHP file.
Duplicate Header assignments will generate PHP parsing errors. HTTP
header information is always available in all PHP files – for a full
list see the phpinfo output – so detecting the browser USER_AGENT
setting is straighforward:

$agent = getenv("HTTP_USER_AGENT");

To check for a match with Internet Explorer 5, use a Perl type regular expression:

if (preg_match("/MSIE 5/i", "$agent")) {echo ("$ie5");exit;}

Detect
WML browsers (like WAP phones) through the use of
getenv("HTTP_ACCEPT"). WML browsers set this value to text/vnd.wap.wml
– amongst other settings.

No need for CGI access

PHP can handle forms internally – there is no need to write or setup a Perl
script, no need for cgi-bin access and no need to learn an extra language. You can write a
PHP file to receive the form and process it, or you can store the special PHP variable
called $_SERVER["PHP_SELF"] in a temporary variable (in this case $self = /php/form.php) and
post the form back to the same script! To post a form back to itself, just create a hidden
field in the form. If the variable from that field is NOT set, then the form has not been
submitted. If it is set, the script should go ahead and process the contents of the form.
Consider this form:

<form method="post" action="$self"><div>
Name: <input type="text" name="myname" value="$myname">
<input type="hidden" name="os" value="ds">
<input type=submit value="Go!"></div>
</form>

This code results in the following form: (Check the source of this page for
confirmation.) Enter your name and click Go! for a demonstration.

 

Name:

Enter your name and it will be displayed here once you click Go!

PHP creates matching variables for all input fields in the form where a name is
specified. These variables will be stored in two special arrays – $_POST[] and $_GET[].
GET[] refers to the query string in the URL – the bit after the ?. POST[] contains data
from the submitted form where the method attribute is set to post. To retrieve the values
of the variables, use $variable = POST["variablename"]; In this form, the variable $os
is being used in both the posted form data and the query string, so a little bit of
logic is required to allow the GET[] setting to override the POST[]. This is to allow a
link on this page to reset the form by using the query string and GET[] to clear the $os
variable. If the query string does not contain a value for $os, then $os is set to
the value from the posted form data, if any.

$os = $_GET["os"];
if(!(isset($os))) {
$os = $_POST["os"];
}
$myname = $_POST["myname"];

Note that the myname input has a default value set as $myname. When PHP outputs
this form, it will insert the current value of $myname as the default value for the input
itself. This is very useful for long forms where the visitor forgets to enter
a required field – the rest of the fields can be restored automatically, a kind of
auto-complete or form-memory. The Demo form (with or without cookies) demonstrates the use
of default values by restoring the entire form. All that remains for the sample form on
this page is to add a simple ‘if’ command to check if the form has already been
submitted:

if ($os=="ds") {
echo "Your name is $myname.";}

You don’t have to re-display the form, it all depends on how you use the if
($os="ds") {} test. You can put the test at the top of the file and generate a
completely different page – using the values from the form. The form itself then resides
inside an else {} block – if the os=ds test fails, the else block is executed and the form
is displayed. In effect, one PHP file contains 2 or more pages. This can also be used to
force a reset of the form. Note that if you use default values as a form-memory, when the
visitor clicks your Reset button, the form will NOT be cleared – the Reset button will
simply reset each field to the default value – i.e. it will undo any changes and
re-instate the memorised form. To clear the fields within the form, you can use the
QUERY_STRING – the strange bit at the end of a WWW URL which includes lots of ? & =
and + signs. The os=ds test can be used to clear the entire form by forcing the test to
fail. So even though the form has been submitted, if you submit a different value for os
it will override the value from the previous form and the script will display a new form
with no default values set.

<a href="$self?os=0">Reset form</a>

The query-string is the os=0. Any PHP file can receive a query-string in this
way. The value of the variable will be stored in $_GET[] using the name given in the
query string, so $os is retrieved from $_GET["os"]. So in the PHP file, $os is
set to zero. The os=ds test now fails, so the script outputs a new form – just as if the
form hadn’t been submitted at all. The first time the PHP file is loaded, $os has no
value. If you test for a variable that has no value assigned or has not been created, PHP
will return the same result as if the value was assigned to zero. A better way of
testing for this is to use !(isset($os)). The !(isset()) means to test for the existence
of the variable and if the variable does not exist, return true.
View these tests before and after submitting the form and after resetting the
form.

# no $os variable exists
if (!$os) {echo "true"} # true
if ($os==0) {echo "true"} # true
if (!(isset($))) {echo "os has not been set" } # os has not been set

# create the $os variable and assign zero
# (without clearing any existing setting.)

if (!(isset($os))) { $os=0; }

# test again

if (!$os) {echo "true"} # true
if ($os==0) {echo "true"} # true
if (!(isset($os))) {echo "os has not been set" } # os is set $os = 0

Preventing and solving bugs in PHP

PHP – like most programming languages / scripting
languages – will check for syntax errors itself. Briefly, these consist
of simple typing
mistakes like eco instead of echo; missing {} brackets (construct not
closed properly); missing semi-colons ; at the end of a line; and not
closing
strings properly. Strings are particularly common errors because a lot
of PHP can be echoing HTML to the browser and HTML needs to use quotes
around certain elements. You MUST escape each and every quotation mark
" throughout the echoed code. This is particularly troublesome when
you cannot simply do a search and replace on all " characters – you
need one unescaped " at the start and end of every PHP string!

Logical
errors are harder to spot as PHP may not raise an error at all. The
first one to look at involves each and every division calculation the
script performs. You must ensure that each division operation is
preceded by a check that you are not dividing by zero. Even if your
code doesn’t take
any values directly from the user, it is still worth adding a simple
check for zero:

if ($width==0) {echo "Error: width is zero!";}
else { # perform your division calculation
$height = $area / $width; }

Infinite
loops are seldom programmed directly, more commonly an infinite loop
will result from an erroneous value being entered
into a normally well-behaved loop. Such infinite loops will never exit
and your script will continue to run for as long as the server runs.
On Windows platforms this could lead to a lack of resources and a
system crash. Even on platforms where an enforced time limit
is set for PHP script execution, your visitor may receive no warning or
error message, just a blank screen, so all loops that
take input from outside the script must be protected from erroneous
input. For example, consider this loop – if the
value entered is negative or if some other calculation within the loop
makes $value negative, the loop becomes infinite:

while ($value != 0) {$value--;}

This
error is relatively easy to solve, the while condition needs to be
changed to while ($value > 0) {}. This way, if $value becomes
negative,
the loop will exit. This could, however, cause unexpected effects
elsewhere in the script if $value is used in further calculations that
expect
a positive value. You may need to specifically write an error handler
for situations where $value becomes negative, either resetting the
value
to a positive default or exiting the script safely. Another
consideration is where subsequent code checks to see if $value exists –
if the loop
exits with a negative value instead of zero, the script will believe
the variable exists when it should find the variable empty.

Porting
code or extending an existing script is also a hot-bed of bugs. The
original script may have been written with all kinds of
unwritten assumptions about the values being processed. Changing the
function or extending the capability of the script can cause unexpected
changes in later code. These can be the hardest errors to find because
you must fully understand the previous (working) script before tackling
the
bugs in the extended/ported one. Two rules can protect you here:
Comment your code thoroughly and use sensible variable names! A few
weeks/months
down the line are you really going to understand what $a contains? If
you name it $accepted won’t that be easier? If you add a comment at the
top of the script that explains that $accepted is only to hold either
zero or one, it’ll make life even easier. Don’t go overboard though,
variables like
$boolean_accepted_value_for_register will only increase the rate of
typing errors!

These
pages use "include" files to ensure a consistent feel to each page. The
PHP file itself is not much more than a list of
variables containing the data for each page. The script then ‘includes’
another PHP file which exports the appropriate code, XML, HTML4 or, for
some
pages, WML. These include files can be a source of bugs if you include
a file twice. This may not seem likely, but if you include file1.php in
file2.php,
you may not notice that both file1 and file2 need to include file3.php!
If any functions are declared in the duplicated include file, PHP will
raise an error.
However, even without such an error, the duplicated code could have
unexpected effects. To safeguard against this, take a tip from C++ and
other
programming languages that rely heavily on included files like headers.
Declare a unique variable in the included file and then before
including the file
in another script, check that the variable doesn’t already exist. If it
does, you’ve already included the file. In the above example of files
1, 2 and 3, if you
declare $FILE3INCLUDED=1; in file3.php, then you can check:

if (!$FILE3INCLUDED) {include 'file3.php';}

Also
pay attention to WHERE you put the include ‘myfile.php’; command. PHP
will do two things at the include command: It will close any current
PHP script using ?> and open a new PHP script tag AFTER the included
file. The included file will then INHERIT all variables at the existing
values at that point of the original script. All include files must
therefore open and close the PHP tag as appropriate – or you’re
precious included
code will be output to the browser as text! Secondly, the include
statement must be placed in the original file at the point where all
necessary
variables have been declared and set to necessary values and BEFORE any
code that modifies or unsets those variables.

One final point on include files, some programmers use a common include file called common.inc but not all servers
are set-up to execute .inc files as PHP so if a visitor deliberately types www.yoursite.com/common.inc into the browser,
they could get an eyeful of all your code! It’s safer to use common.php if you want one file to hold certain variables common
to the whole site – that way you can be sure that any such deliberate attempt to peer into your
code will result in a blank screen (or a nasty warning if you choose to put some code in common.php to that effect!)

Checking user input for dubious or erroneous values

When receiving input from users, you must be prepared
for a proportion of visitors who will enter nonsense values either
through
unfamiliarity or malice. If you ask for a number between 1 and 10, you
still need to check that someone hasn’t entered "three" or
-1. With complex data types like dates, always seek to use standard
input fields like lists or radio buttons and checkboxes not text inputs

that way you control the data input format. It’s no fun writing a check
routine to parse dates like 12-9-01, 12 May 99, 12 Apr, 2/2/01 etc.
Also, be prepared for malicious users who may attempt to enter -1e5 in
a text input, or <– #SSI command –>. Very large or very small
numbers
can be used to break your code and corrupt your data. SSI commands
entered in text inputs are a security risk to your server. PHP has a
useful
function to prevent HTML tags like SSI or Javascript from affecting
your script: use the htmlspecialchars() function to change the <>
brackets
into &lt; &gt; markers. This will prevent the content of the
tag from being executed by the browser but will still allow the content
of the
tag to be incorporated into the input. e.g.

<!--#config timefmt='%a, %B %d, %Y' -->
<!--#echo var='LAST_MODIFIED' -->
(This SSI code simply puts the date the file was last modified
into the HTML - works only in HTML files with the
.shtml file extension.)

Whilst
this is safe, it is still intrusive, so to remove the entire contents
of the tag, use a search and replace regular expression,
as in Perl. Use

$myinput = ereg_replace("<.*>","",$myinput);
$myinput = trim($myinput);

In
this example ereg_replace searches the string $myinput for <>
with any number of any kind of characters in between. The entire
match, including the brackets, is then replaced with the empty string.
The second line trims the returned string to remove spaces from the
beginning
and end of the string. If a visitor entered an SSI or Javascript
command into your input and nothing else, the script would now receive
no input at all, allowing you to post an error message about "no
content".

ereg
is also useful for dealing with tainted user input. (Tainted in the
same sense as Perl treats tainted data – data where the formatting and
data type have not been checked as valid.) If you are looking for a
text input from a text field, you can use ereg to look for letters a-z
and A-Z. If you want
a numerical input, ereg can search for characters between 0-9. Failure
to find the right characters can allow you to raise an error without
exposing the
rest of your script to tainted data. Shortcuts are available on some
PHP installations but not all shortcuts are
supported on all servers. To use the full versions:

[a-z] for one lowercase letter
[A-Z] uppercase
[A-Za-z] any letter
[0-9] any single digit (shortcut \d).
[A-Za-z0-9] any letter or digit (shortcut \w)
[ \t\n\r] any whitespace - space, tab, rewline or
return. (shortcut \s)
. any character except a newline
^ match needs to be at the beginning of the string
^[abc] NOTE: this is not the same as [^abc]
$ match needs to be at the end of the string
Z$ matches if the string ends in Z
\ 'escapes' special characters: . * ? + [ ] ( ) { } ^ $ | \
\.$ matches a string ending in a full stop.
.$ matches a string ending in any character except a newline

Use [] brackets to denote the class of character to match or a range. Each [] bracket represents one
character in the matching string and you can specify the specific characters or a range to match:

[abc] or [a-c] matches a, b, or c but not ab, bc or abc. 
[acf] matches a, c or f but not b or e.
[a-f] matches a,b,c,d,e or f.

If [] brackets aren’t used, the characters have to be present in sequence, exactly as in the expression. e.g.

 'one' matches only 'one'.
'abc' matches only 'abc'.
[abc] matches a, b or c but not abc.
'abcd' doesn't match 'abc' or 'dcba'.

Use ^ to negate the match – to return true if the matching characters are absent from that position.

[^abc] any character except a, b or c
[^a-z] any character except a lowercase letter
[^A-Za-z] any character except a letter.
[^A-Za-z0-9] any non-word character (shortcut \W)
[^0-9] any non-digit (shortcut \D)

Be careful with negative matches, [^abc]
matches every other character, from newlines to digits and letters from
d to z as well as from A to Z. Other modifies are | – meaning either
or. e.g. [abc]|[1-5] matches a,b,c or digits 1 to 5. Qualifiers are
also useful
to enhance the match: optional, repeated or once only. ? means that the
preceding character type can occur once or not at all but never more
than once. + means that the preceding character type can occur many
times but must occur at least once. * means the preceding character
type
may be there once, may be repeated or entirely absent.

[abc]?[xyz]+ matches xyz, axyz, ax, x, byz, bzzzz.
The following will NOT match: aay, a, abc, ba, bp, so.

Quantifiers allow you to specify how many characters to match. A single digit means to match exactly that many, no more and
no less. To specify a range, use {,3} to match up to 3 or {3,} to match at least 3. {4,6} matches 4, 5 or 6 characters.

a{2} only matches aa
a{1,2} only matches a or aa
a{2,} matches aa, aaa, or aaaaaa but not a
a{,3} matches a, aa, aaa but not aaaa

For an example of pattern matching, go back to the PHP Form example (4 – PHP Forms) and enter a postal code
instead of a name. Note that the match is not intended to catch every possible UK postal code, it is only an example.

Forms uses the expression:
[A-Za-z]{1,2}[0-9]{1,2} ?[0-9][A-Za-z]{2}

Read remote files, read and write local files on the server

If you don’t need write access to the file or if the file you need is on a remote server, you can load the entire file
into an array, splitting the file at each line break.

$filearray = file("dir/filename");
$filearray = file ("http://www.someothersite.com/dir/file");
if (!($filearray = @file($hostname.$documentname)))
{echo "$fail_message";}

To access the content, process one line at a time.

while (list(,$oneline) = each($filearray)) {
# process the contents of $oneline here
}

For more control over local files, use fopen. This allows the script to open
files in a variety of modes – read-only (r) or read+write(r+) which preserve any existing
content and start reading/writing at the start of the file; write-only (w) or read+write
(w+) which delete all existing content in the file, reading or writing starts with an empty
file; append-only (a) or read and append (a+), existing content is preserved and reading or
writing starts at the end of the file. With w, w+, a or a+ options, if the file does not
exist, PHP will attempt to create it. Make sure the permissions for the directory concerned
are set to allow the server to write the file.

fopen("filename","r+");
# read+write, keep content, start at top of file
if (!$fp = @fopen("$dir\$filename","w"))
die ("Couldn't open file $filename");
# write only to an empty file, delete existing content.)

The file is now open, but a separate operation is needed to read or write to the
file. PHP has a variety of functions that can read individual characters, sets of a fixed
number of characters, or one line at a time. Covering each function in depth is beyond the
scope of this site, particularly as it is well covered in PHP texts (see the CodeHelp books
page). For now, I will just consider fgets() which can be used to read a specified number
of bytes at a time, but which has the flexibility to stop reading when it encounters a new
line or the end of the file. Thus, by choosing a length greater than any single line in the
file, you can use fgets() to read files one line at a time. The advantage over file() is
that fopen() and fgets() can be used together to allow the script to change part of a file.
This snippet of code takes content from one file, adds some content at the beginning and
then completes the output file. The first step, reading content from the temp.php file,
could be done with file(), but fopen() is used here for demonstration purposes.
As a result of using fopen(), filesize() is used to find the complete size of the file and
ftell() to find out where we are within the file. Also note the nesting of the fopen()
commands and the use of two separate file pointers, $fp and $fout to identify the source
and output files respectively.

# read temp.php, write tempinclude=1,
# then insert temp.php into final outputfile
# note: not for use on very small, single line files -
# use fgetc() instead
$maxread=filesize("temp.php");
if (!($fout=fopen($outputfile,"w")))
die ("Cannot create output file.");
fwrite($fout,"<?php\n$tempinclude=1;\n?>");
if (!($fp=fopen("temp.php","r")))
die ("Cannot open temporary file.");
$data = fgets($fp,$maxread);
while ((ftell($fp)<$maxread)) {
fwrite($fout,$data);
$data = fgets($fp,$maxread);
}
fclose($fp);
fclose($fout);

By pattern matching each line, an enhanced script could determine where new
content should be inserted and a simple fwrite() command could be used to insert the
content. This cannot be done with file() alone, as the file is closed as soon as the file()
command returns. fclose() is optional – the file will be closed when the script exits. If
your script needs to do more processing after completing file access, and particularly if
either file opened in the script is to be accessed by another script or user, use
fclose($filepointer); to allow other users, services or scripts to access the file.

Common PHP functions

Introduction to PHP functions.

PHP has a host of ready-made functions to make complex tasks easier. Only the
common functions can be covered on CodeHelp, including arrays, date and time, mysql and
strings. Other functions are already covered in passing during discussion of errors,
tainted data, forms and files. For a full description of these and all the other PHP
functions, one of the PHP texts is
recommended. Functions are available in the following areas:

  • Apache-specific
  • Arrays
  • Aspell
  • Calendar
  • Class/Object
  • Client URL Library
  • Databases – including
    • Database Abstration Layer
    • dBase
    • DBM
    • Informix
    • InterBase
    • Microsoft SQL Server
    • mSQL
    • MySQL
    • Unified ODBC
    • Oracle 8
    • Oracle
    • PostgreSQL
    • Sybase
  • Date and Time
  • Directory
  • DOM XML
  • Error handling and logging
  • Filesystem
  • Forms Data Format document
  • HTTP functions
  • Images
  • Mail
  • Mathematics
  • Miscellaneous
  • Network
  • Output Control
  • PHP Options
  • POSIX
  • Program Execution
  • Pspell
  • Perl-compatible
  • Regular expressions
  • Sessions
  • Strings
  • URL
  • User defined functions
  • Variables
  • WDDX
  • XML Parser
  • Zlib

Building, sorting, reversing and flipping arrays

Array functions

Create and return an array of values:
quicker than using $myarray[0] = "value1" etc.

$array1 = array("value1",4,"value3");
$array2 = array("value1",3,"string value");
$array3 = array("value3","any value");

To create an associative array, use => to link the key to the corresponding
value:

$names_array = array("Bob" => "Jones","Fred" => "Bloggs",
"June" => "Smith")

To help find the differences between two or more arrays, array_diff()
returns an array containing only the values from $array1 that do NOT occur
in any of the other arrays.

$diff_array = array_diff($array1, $array2, $array3);

$diff_array contains only one value, 4 in $diff_array[1]
indicating that the first value $array1[0] = value1 was matched, the
second value $array1[1] = 4 was different and the third value $array1[2]
= value3 was matched.

An array containing names from an address book could contain
firstnames as keys and family names as values – the $names_array above.
Sorting the array using asort(), sorts on the values – the family name. To sort
the array on firstnames, use ksort().

asort($names_array);

sorts the array by the value – familyname. $names_array now contains:

Fred Bloggs
Bob Jones
June Smith

ksort() sorts the array by the key – firstname. $names_array now contains:

Bob Jones
Fred Bloggs
June Smith

To reverse the order, use rsort() for simple arrays and arsort() for associative
arrays. To reverse the order of a ksort() requires two operations – use ksort() as normal
and then use array_reverse() to reverse the ksort. To convert keys into values and the
values into keys, use array_flip().

arsort($names_array);
June Smith
Bob Jones
Fred Bloggs

ksort($names_array);
$names_array = array_reverse($names_array);
June Smith
Fred Bloggs
Bob Jones

$names_array = array_flip($names_array);
Smith June
Bloggs Fred
Jones Bob

Current time, date calculations, timestamp formats

Date and time functions

Unlike Javascript, note that when PHP retrieves the time, it will be
the local server time, not necessarily your local (browser) time. You will
be able to tell if this page is cached if you refresh the page and the values
do not change. Time is usually retrieved as a timestamp – an integer value – and
then processed into whichever values you require:

$timestamp = time() : $timestamp : 1194481656
$local = localtime() :
seconds : $local[0] : 36
minutes : $local[1] : 27
hours (24hr) : $local[2] : 0
day: $local[3] : 8
month (0-11) : $local[4] : 10 (+1 for usual format)
year (+1900) : $local[5] : 107 (+1900 for usual format)
day of week (0-6) : $local[6] : 4
day of year (0-364) : $local[7] : 311
timezone (+/-): $local[8] : 0
getdate($timestamp) :
seconds : $local["seconds"] : 36
minutes : $local["minutes"] : 27
hours : $local["hours"] : 0
mday : $local["mday"] : 8
wday : $local["wday"] : 4
mon : $local["mon"] : 11
year : $local["year"] : 2007
yday : $local["yday"] : 311
weekday : $local["weekday"] : Thursday
month : $local["month"] : November
timestamp : $local[0] : 1194481656

Alternatively, you can convert any timestamp (past,present or future) directly
into a formatted string.
Use either strftime() or date():
%a – abbreviated weekday name according to the current locale :

strftime("%D",$timestamp) : Thu

%A – full weekday name according to the current locale

strftime("%A",$timestamp) : Thursday

%b – abbreviated month name according to the current locale

strftime("%b",$timestamp) : Nov

%B – full month name according to the current locale

strftime("%B",$timestamp) : November

%c – preferred date and time representation for the current locale

strftime("%c",$timestamp) : Thu Nov  8 00:27:36 2007

%C – century number (the year divided by 100 and truncated to an integer, range
00 to 99).

strftime("%C",$timestamp) : 20

Adding an ordinal to the century number

Remember to +1. To add the correct ordinal suffix, you need to play around
with the values to mktime() – creating a false, temporary, timestamp to set the day to the
year+1 – then date("S",$falsetimestamp) can create the
correct ordinal. The $hour, $minute, $second, $month and $year values for mktime()
can be completely arbitrary for the purposes of this conversion.

$temp = strftime("%C",$timestamp);
$temp++;
$a = $temp;
$temp = mktime($hour,$minute,$second,$month,$temp,$year);
$a .= date("S",$temp) . " century";
echo $a;

21st century

%d – day of the month as a decimal number (range 01 to 31)

strftime("%d",$timestamp) : 08

%D – same as %m/%d/%y

strftime("%D",$timestamp) : 11/08/07

%e – day of the month as a decimal number, a single digit is preceded by a
space (range ‘ 1′ to ’31’)

strftime("%e",$timestamp) :  8

%g – like %G, but without the century.

strftime("%g",$timestamp) : 07

%G – The 4-digit year corresponding to the ISO week number (see %V). This has
the same format and value as %Y, except that if the ISO week number belongs to the
previous or next year, that year is used instead.

strftime("%G",$timestamp) : 2007

%h – same as %b

strftime("%h",$timestamp) : Nov

%H – hour as a decimal number using a 24-hour clock (range 00 to 23)

strftime("%H",$timestamp) : 00

%I – hour as a decimal number using a 12-hour clock (range 01 to 12)

strftime("%I",$timestamp) : 12

%j – day of the year as a decimal number (range 001 to 366)

strftime("%j",$timestamp) : 312

%m – month as a decimal number (range 01 to 12)

strftime("%m",$timestamp) : 11

%M – minute as a decimal number

strftime("%M",$timestamp) : 27

%n – newline character

%p – either ‘am’ or ‘pm’ according to the given time value, or the
corresponding strings for the current locale

strftime("%p",$timestamp) : AM

%r – time in a.m. and p.m. notation

strftime("%r",$timestamp) : 12:27:36 AM

%R – time in 24 hour notation

strftime("%R",$timestamp) : 00:27

%S – second as a decimal number

strftime("%S",$timestamp) : 36

%t – tab character

%T – current time, equal to %H:%M:%S

strftime("%T",$timestamp) : 00:27:36

%u – weekday as a decimal number [1,7], with 1 representing Monday. Sun
Solaris seems to start with Sunday as 1.

strftime("%u",$timestamp) : 4

%U – week number of the current year as a decimal number, starting with the
first Sunday as the first day of the first week

strftime("%U",$timestamp) : 44

%V – The ISO 8601:1988 week number of the current year as a decimal number,
range 01 to 53, where week 1 is the first week that has at least 4 days in the current
year, and with Monday as the first day of the week. (Use %G or %g for the year component
that corresponds to the week number for the specified timestamp.)

strftime("%V",$timestamp) : 45

%W – week number of the current year as a decimal number, starting with the
first Monday as the first day of the first week.

strftime("%W",$timestamp) : 45

%w – day of the week as a decimal, Sunday being 0.

strftime("%w",$timestamp) : 4

%x – preferred date representation for the current locale without the time.

strftime("%x",$timestamp) : 11/08/07

%X – preferred time representation for the current locale without the date.

strftime("%X",$timestamp) : 00:27:36

%y – year as a decimal number without a century (range 00 to 99).

strftime("%y",$timestamp) : 07

%Y – year as a decimal number including the century.

strftime("%Y",$timestamp) : 2007

%Z – time zone or name or abbreviation.

strftime("%Z",$timestamp) : UTC

Converting strftime() to GMT with gmstrftime()

For example: gmstrftime("%a %A %x %X %p %b %B %c"); compared with the strftime() version:

Thu Thursday 11/08/07 00:27:36 AM Nov November Thu Nov  8 00:27:36 2007
Thu Thursday 11/08/07 00:27:36 AM Nov November Thu Nov 8 00:27:36 2007

date() and gmdate() use different formatting
instructions to strftime() gmstrftime()!

date() and gmdate() convert the localtime directly to a string, with or
without a separate timestamp – for example: date("a",$timestamp).

date("a") date("A"): am | pm or AM | PM:

am AM

Days: day of month as digit with leading zeroes – d, without zeroes – j,
repeat, this time with an ordinal suffix – jS, 3 letter text – D, or long – l (lowercase
L), numerical day of the week (0=Sunday) – w.

date("d j jS D l w") : 08 8 8th Thu Thursday 4

Months: Short name – M, long name – F, number – n, with zeros – m, total number of days in this month – t

Nov November 11 11 30

Hours and minutes : 12hour format – g, with zeroes – h, 24hr format – G, with zeroes – H, minutes – i, seconds – s

12 12 0 00 27 36

Years: 4 digits – Y, 2 digits – y, current day of the year (0-365) – z

2007 07 311

Timezones: server timezone – T, timezone offset in seconds (+/-) – Z. Divide
by 3600 for hours.

UTC 0 /3600 = 0hour(s)

A complete timestring using date() and then gmdate():

November 8th 2007 12:27:36am  UTC

November 8th 2007 12:27:36am GMT



date("F jS Y g:i:sa T")

PHP string functions

We will be covering the following PHP string functions:

addslashes
chop,
explode,
trim,
compare,
convert . . .

PHP addslashes() – escapes characters like ” ‘ and ‘ to make the string safe for using
in database queries. The corresponding PHP String function is stripslashes()

   This is a test 'string' for the CodeHelp pages.      
addslashes($string);
This is a test \'string\' for the CodeHelp pages.
stripslashes($string);
This is a test 'string' for the CodeHelp pages.

PHP chop() – remove trailing whitespace from the specified string. In the
example, the string is enclosed in [ ] brackets and the background colour is changed
to indicate where the whitespace has been removed by chop().

[   This is a test 'string' for the CodeHelp pages.      ]
chop($string);
[ This is a test 'string' for the CodeHelp pages.]

PHP explode (and corresponding implode) -convert strings into arrays, splitting or
joining using delimiter characters – sometimes spaces, or tabs or markers like # or ~. Use
explode when you want to work on small portions of the string, for example to change just
one portion of the string to capitals (note how the delimiter is removed):

$myarray = explode(" ",$string);
while(list(,$value) = each($myarray)) {
if(ereg("CodeHelp",$value)) {
$value = strtoupper($value);
}
echo $value;
}
Thisisatest'string'fortheCODEHELPpages.

PHP implode – takes an array and converts it into a string, inserting the delimiter
between values from the array (it puts back what explode takes out). Implode is also useful
when opening a file leaves you with an array containing individual lines from the file.
The mplode PHP string function can give you one large string that can be easier to search using ereg() than a
large array. (The delimiter can be more than a single character, it can also be
blank.)

implode("#",$myarray)
###This#is#a#test#'string'#for#the#CodeHelp#pages.######

Unlike chop(), trim() removes whitespace from both ends of the string:

[   This is a test 'string' for the CodeHelp pages.      ]
trim($string);
[This is a test 'string' for the CodeHelp pages.]

There are lots of similar compare functions for strings, incuding case
insensitive strcasecmp(), regular expressions like ereg() and preg() with wildcards, and
the more abstract (including phonetic) comparisons using similar_text(), levenshtein(),
metaphone() and soundex(). strcmp() only returns true if the match is exact:

$string1 = "new string";
$string2 = "old string";
$string3 = "new string";
strcmp($string1,$string2) : -1
strcmp($string1,$string3) : 0
ereg("... string",$string1) : 1
ereg("... string",$string2) : 1
ereg("n.. .tring",$string2) :

To match any special characters in PHP functions like ereg() and preg(),
make sure you escape each one : \. \* \?. For more on wildcard characters,
see 6 – Tainted input data. This is just a quick reminder.
. matches any character except a newline,
* preceding character or group may be omitted or appear once, twice or more.
? preceding character or group may be omitted or may appear once but not twice or more.
+ preceding character or group must be present once but appear twice or more.
^ the beginning of the string.
$ the end of the string.
[abc] any one of the characters a, b, or c can appear once.
[^abc] any character except a, b or c can appear once.
[a-z] one lowercase alphabet character.
(abc) the phrase ‘abc’ may appear once – bac, ab, c or aBc do not match.

htmlspecialchars() makes all the < and > characters safe.
< becomes <, > becomes > and & becomes &. This comment
line is present as <!– comment & –> in the HTML source.

htmlspecialchars($string); : 

As an alternative to ereg_replace(“<.*>“,””,$myinput), (which can
strip out more than you might expect), PHP provides the strip_tags() function that will
remove all HTML and PHP tags from a string. This is important if you are accepting text
input directly into the PHP script – it could otherwise allow visitors to corrupt your
script by entering malicious text.

strip_tags( more content ); :  more content 

Other conversions: (Note that the string itself remains unchanged between
each of these demonstration commands.)

strtoupper($string); : 
THIS IS A TEST 'STRING' FOR THE CODEHELP PAGES.
strtolower($string); :
this is a test 'string' for the codehelp pages.
ucfirst($string); :
This is a test 'string' for the CodeHelp pages.
ucwords($string); :
This Is A Test 'string' For The CodeHelp Pages.
wordwrap($string,8,"\n"); : This is a
test
'string' for
the CodeHelp
pages.

The final conversion requires a change
to the string. These two sentences
are now the string.

nl2br($string); : The final conversion requires a change
to the string. These two sentences
are now the string.

nl2br() changed the newlines in the source code into
tags. This can
be useful in processing some forms or converting email messages into HTML archives.

2010-05-25T22:53:02+00:00 November 11th, 2007|PHP|0 Comments

About the Author:

Leave A Comment