Job
interview Questions & answers
PHP
PHP Questions and Answers
How To Append New Data to the End of a File?
If you have an existing file, and
want to write more data to the end of the file, you can use the
fopen($fileName, "a") function. It opens the specified file, moves
the file pointer to the end of the file, and returns a file handle. The second
argument "a" tells PHP to open the file for appending. Once the file
is open, you can use other functions to write data to the file through this
file handle. Here is a PHP script example on how to use fopen() for appending:
<?php
$file =
fopen("/temp/cgi.log", "a");
fwrite($file,"Remote host:
64.233.179.104.\r\n");
fclose($file);
$file =
fopen("/temp/cgi.log", "a");
fwrite($file,"Query string:
cate=102&order=down〈=en.\r\n");
fclose($file);
?>
This script will write the following
to the file:
Remote host: 64.233.179.104.
Query string:
cate=102&order=down〈=en.
As you can see, file cgi.log opened
twice by the script. The first call of fopen() actually created the file. The
second call of fopen() opened the file to allow new data to append to the end
of the file.
How To Read One Line of Text
from a File?
If you have a text file with
multiple lines, and you want to read those lines one line at a time, you can
use the fgets() function. It reads the current line up to the "\n"
character, moves the file pointer to the next line, and returns the text line
as a string. The returning string includes the "\n" at the end. Here
is a PHP script example on how to use fgets():
<?php
$file =
fopen("/windows/system32/drivers/etc/services", "r");
while ( ($line=fgets($file)) !==
false ) {
$line = rtrim($line);
print("$line\n");
# more statements...
}
fclose($file);
?>
This script will print:
# This file contains port numbers
for well-known services
echo 7/tcp
ftp 21/tcp
telnet 23/tcp
smtp 25/tcp
...
Note that rtrim() is used to remove
"\n" from the returning string of fgets().
How To Read One Character from a
File?
If you have a text file, and you
want to read the file one character at a time, you can use the fgetc()
function. It reads the current character, moves the file pointer to the next
character, and returns the character as a string. If end of the file is
reached, fgetc() returns Boolean false. Here is a PHP script example on how to
use fgetc():
<?php
$file =
fopen("/windows/system32/drivers/etc/services", "r");
$count = 0;
while ( ($char=fgetc($file)) !==
false ) {
if ($char=="/") $count++;
}
fclose($file);
print("Number of /:
$count\n");
?>
This script will print:
Number of /: 113
Note that rtrim() is used to remove
"\n" from the returning string of fgets().
What's Wrong with "while
($c=fgetc($f)) {}"?
If you are using "while
($c=fgetc($f)) {}" to loop through each character in a file, the loop may
end in the middle of the file when there is a "0" character, because
PHP treats "0" as Boolean false. To properly loop to the end of the
file, you should use "while ( ($c=fgetc($f)) !== false ) {}". Here is
a PHP script example on incorrect testing of fgetc():
<?php
$file =
fopen("/temp/cgi.log", "w");
fwrite($file,"Remote host:
64.233.179.104.\r\n");
fwrite($file,"Query string:
cate=102&order=down〈=en.\r\n");
fclose($file);
$file =
fopen("/temp/cgi.log", "r");
while ( ($char=fgetc($file)) ) {
print($char);
}
fclose($file);
?>
This script will print:
Remote host: 64.233.179.1
As you can see the loop indeed
stopped at character "0".
How To Read a File in Binary Mode?
If you have a file that stores
binary data, like an executable program or picture file, you need to read the
file in binary mode to ensure that none of the data gets modified during the
reading process. You need to:
Open the file with fopen($fileName,
"rb").Read data with fread($fileHandle,$length).Here is a PHP script
example on reading binary file:
<?php
$in =
fopen("/windows/system32/ping.exe", "rb");
$out =
fopen("/temp/myPing.exe", "w");
$count = 0;
while (!feof($in)) {
$count++;
$buffer = fread($in,64);
fwrite($out,$buffer);
}
fclose($out);
fclose($in);
print("About
".($count*64)." bytes read.\n");
?>
This script will print:
About 16448 bytes read.
This script actually copied an
executable program file ping.exe in binary mode to new file. The new file
should still be executable. Try it: \temp\myping capptitudebank.blogspot.com.
How To Write a String to a File with
a File Handle?
If you have a file handle linked to
a file opened for writing, and you want to write a string to the file, you can
use the fwrite() function. It will write the string to the file where the file
pointer is located, and moves the file pointer to the end of the string. Here
is a PHP script example on how to use fwrite():
<?php
$file =
fopen("/temp/todo.txt", "w");
fwrite($file,"Download PHP
scripts at capptitudebank.blogspot.com.\r\n");
fwrite($file,"Download Perl
scripts at capptitudebank.blogspot.com.\r\n");
fclose($file);
?>
This script will write the following
to the file:
Download PHP scripts at capptitudebank.blogspot.com.
Download Perl scripts at capptitudebank.blogspot.com.
How To Write a String to a File
without a File Handle?
If you have a string, want to write
it to a file, and you don't want to open the file with a file handle, you can
use the file_put_contents(). It opens the specified file, writes the specified
string, closes the file, and returns the number of bytes written. Here is a PHP
script example on how to use file_put_contents():
<?php
$string = "Download PHP scripts
at capptitudebank.blogspot.com.\r\n";
$string .= "Download Perl
scripts at capptitudebank.blogspot.com.\r\n";
$bytes =
file_put_contents("/temp/todo.txt", $string);
print("Number of bytes written:
$bytes\n");
?>
This script will print:
Number of bytes written: 89
If you look at the file todo.txt, it
will contain:
Download PHP scripts at capptitudebank.blogspot.com.
Download Perl scripts at capptitudebank.blogspot.com.
How To Write an Array to a File without
a File Handle?
If you have an array, want to write
it to a file, and you don't want to open the file with a file handle, you can
use the file_put_contents(). It opens the specified file, writes all values
from the specified string, closes the file, and returns the number of bytes
written. Here is a PHP script example on how to use file_put_contents():
<?php
$array["one"] =
"Download PHP scripts at capptitudebank.blogspot.com.\r\n";
$array["two"] =
"Download Perl scripts at capptitudebank.blogspot.com.\r\n";
$bytes =
file_put_contents("/temp/todo.txt", $array);
print("Number of bytes written:
$bytes\n");
?>
This script will print:
Number of bytes written: 89
If you look at the file todo.txt, it
will contain:
Download PHP scripts at
http://capptitude.blogspot.com
Download Perl scripts at
http://capptitude.blogspot.com
How To Read Data from Keyborad
(Standard Input)?
If you want to read data from the
standard input, usually the keyboard, you can use the
fopen("php://stdin") function. It creates a special file handle linking
to the standard input, and returns the file handle. Once the standard input is
opened to a file handle, you can use fgets() to read one line at a time from
the standard input like a regular file. Remember fgets() also includes
"\n" at the end of the returning string. Here is a PHP script example
on how to read from standard input:
<?php
$stdin =
fopen("php://stdin", "r");
print("What's your
name?\n");
$name = fgets($stdin);
print("Hello $name!\n");
fclose($stdin);
?>
This script will print:
What's your name?
Leo
Hello Leo
!
"!" is showing on the next
line, because $name includes "\n" returned by fgets(). You can use
rtrim() to remove "\n".
If you are using your script in a
Web page, there is no standard input.
If you don't want to open the
standard input as a file handle yourself, you can use the constant STDIN
predefined by PHP as the file handle for standard input.
How To Open Standard Output as a
File Handle?
If you want to open the standard
output as a file handle yourself, you can use the fopen("php://stdout")
function. It creates a special file handle linking to the standard output, and
returns the file handle. Once the standard output is opened to a file handle,
you can use fwrite() to write data to the starndard output like a regular file.
Here is a PHP script example on how to write to standard output:
<?php
$stdout =
fopen("php://stdout", "w");
fwrite($stdout,"To
do:\n");
fwrite($stdout,"Looking for PHP
hosting provider!\n");
fclose($stdout);
?>
This script will print:
What's your name?
To do:
Looking for PHP hosting provider!
If you don't want to open the
standard output as a file handle yourself, you can use the constant STDOUT
predefined by PHP as the file handle for standard output.
If you are using your script in a
Web page, standard output is merged into the Web page HTML document.
print() and echo() also writes to
standard output.
How To Create a Directory?
You can use the mkdir() function to
create a directory. Here is a PHP script example on how to use mkdir():
<?php
if (file_exists("/temp/download"))
{
print("Directory already
exists.\n");
} else {
mkdir("/temp/download");
print("Directory
created.\n");
}
?>
This script will print:
Directory created.
If you run this script again, it
will print:
Directory already exists.
How To Remove an Empty Directory?
If you have an empty existing
directory and you want to remove it, you can use the rmdir(). Here is a PHP
script example on how to use rmdir():
<?php
if
(file_exists("/temp/download")) {
rmdir("/temp/download");
print("Directory
removed.\n");
} else {
print("Directory does not
exist.\n");
}
?>
This script will print:
Directory removed.
If you run this script again, it
will print:
Directory does not exist.
How To Remove a File?
If you want to remove an existing
file, you can use the unlink() function. Here is a PHP script example on how to
use unlink():
<?php
if
(file_exists("/temp/todo.txt")) {
unlink("/temp/todo.txt");
print("File removed.\n");
} else {
print("File does not
exist.\n");
}
?>
This script will print:
File removed.
If you run this script again, it
will print:
File does not exist.
How To Copy a File?
If you have a file and want to make
a copy to create a new file, you can use the copy() function. Here is a PHP
script example on how to use copy():
<?php
unlink("/temp/myPing.exe");
copy("/windows/system32/ping.exe",
"/temp/myPing.exe");
if
(file_exists("/temp/myPing.exe")) {
print("A copy of ping.exe is
created.\n");
}
?>
This script will print:
A copy of ping.exe is created.
How To Dump the Contents of a
Directory into an Array?
If you want to get the contents of a
directory into an array, you can use the scandir() function. It gets a list of
all the files and sub directories of the specified directory and returns the
list as an array. The returning list also includes two specify entries: (.) and
(..). Here is a PHP script example on how to use scandir():
<?php
mkdir("/temp/download");
$array["one"] =
"Download PHP scripts at capptitudebank.blogspot.com.\r\n";
$array["two"] =
"Download Perl scripts at capptitudebank.blogspot.com.\r\n";
$bytes =
file_put_contents("/temp/download/todo.txt", $array);
$files =
scandir("/temp/download");
print_r($files);
?>
This script will print:
Array
(
[0] => .
[1] => ..
[2] => todo.txt
)
How To Read a Directory One Entry at
a Time?
If you want to read a directory one
entry at a time, you can use opendir() to open the specified directory to
create a directory handle, then use readdir() to read the directory contents
through the directory handle one entry at a time. readdir() returns the current
entry located by the directory pointer and moves the pointer to the next entry.
When end of directory is reached, readdir() returns Boolean false. Here is a
PHP script example on how to use opendir() and readdir():
<?php
mkdir("/temp/download");
$array["one"] =
"Download PHP scripts at capptitudebank.blogspot.com.\r\n";
$array["two"] =
"Download Perl scripts at capptitudebank.blogspot.com.\r\n";
$bytes =
file_put_contents("/temp/download/todo.txt", $array);
print("List of files:\n");
$dir = opendir("/temp/download");
while ( ($file=readdir($dir)) !==
false ) {
print("$file\n");
}
closedir($dir);
?>
This script will print:
List of files:
.
..
todo.txt
How To Get the Directory Name out of
a File Path Name?
If you have the full path name of a
file, and want to get the directory name portion of the path name, you can use
the dirname() function. It breaks the full path name at the last directory path
delimiter (/) or (\), and returns the first portion as the directory name. Here
is a PHP script example on how to use dirname():
<?php
$pathName =
"/temp/download/todo.txt";
$dirName = dirname($pathName);
print("File full path name:
$pathName\n");
print("File directory name:
$dirName\n");
print("\n");
?>
This script will print:
File full path name:
/temp/download/todo.txt
File directory name: /temp/download
How To Break a File Path Name into
Parts?
If you have a file name, and want to
get different parts of the file name, you can use the pathinfo() function. It
breaks the file name into 3 parts: directory name, file base name and file
extension; and returns them in an array. Here is a PHP script example on how to
use pathinfo():
<?php
$pathName =
"/temp/download/todo.txt";
$parts = pathinfo($pathName);
print_r($parts);
print("\n");
?>
This script will print:
Array
(
[dirname] => /temp/download
[basename] => todo.txt
[extension] => txt
)
How To Create a Web Form?
If you take input data from visitors
on your Web site, you can create a Web form with input fields to allow visitors
to fill in data and submit the data to your server for processing. A Web form
can be created with the <FORM> tag with some input tags. The &FORM
tag should be written in the following format:
<form action=processing.php
method=get/post>
......
</form>
Where "processing.php"
specifies the PHP page that processes the submitted data in the form.
What Are Form Input HTML Tags?
HTML tags that can be used in a form
to collect input data are:
<SUBMIT ...> - Displayed as a
button allow users to submit the form.<INPUT TYPE=TEXT ...> - Displayed
as an input field to take an input string.<INPUT TYPE=RADIO ...> -
Displayed as a radio button to take an input flag.<INPUT TYPE=CHECKBOX
...> - Displayed as a checkbox button to take an input flag.<SELECT
...> - Displayed as a dropdown list to take input selection.<TEXTAREA
...> - Displayed as an input area to take a large amount of input text.
How To Generate a Form?
Generating a form seems to be easy.
You can use PHP output statements to generate the required <FORM> tag and
other input tags. But you should consider to organized your input fields in a
table to make your form looks good on the screen. The PHP script below shows
you a good example of HTML forms:
<?php
print("<html><form
action=processing_forms.php method=post>");
print("<table><tr><td
colspan=2>Please enter and submit your"
." comments about
PICKZYCenter.com:</td></tr>");
print("<tr><td>Your
Name:</td>"
."<td><input type=text
name=name></td></tr>\n");
print("<tr><td>Comments:</td>"
."<td><input type=text
name=comment></td></tr>\n");
print("<tr><td colspan=2><input
type=submit><td></tr></table>\n");
print("</form></html>\n");
?>
If you save this script as a PHP
page, submit_comments.php, on your Web site, and view this page, you will see a
simple Web form.
Where Is the Submitted Form Data
Stored?
When a user submit a form on your
Web server, user entered data will be transferred to the PHP engine, which will
make the submitted data available to your PHP script for processing in
pre-defined arrays:
$_GET - An associate array that
store form data submitted with the GET method.$_POST - An associate array that
store form data submitted with the POST method.$_REQUEST - An associate array
that store form data submitted with either GET or POST method. $_REQUEST also
contains the cookie values received back from the browser.How To Retrieve the
Submitted Form Data?
The best way to retrieve the form
data submitted by your visitor is to use the $_REQUEST array. The keys in this
array will be the field names defined in form. The values in this array will be
the values entered by your visitor in the input fields. The PHP script below,
processing_forms.php, shows you how to retrieve form data submitted with the
PHP page presented in the previous tutorial exercise:
<?php
$name = $_REQUEST['name'];
$comment = $_REQUEST['comment'];
print("<html><pre>");
print("You have submitted the
following information:\n");
print(" Name = $name\n");
print(" Comments =
$comment\n");
print("Thank you!\n");
print("</pre></html>\n");
?>
If you copy both scripts,
submit_comments.php and processing_forms.php, to your Web server, and submit
some data like: "Bill Bush" and "Nice site.", you will get
something like:
You have submitted the following
information:
Name = Bill Bush
Comments = Nice site.
What Happens If an Expected Input
Field Was Not Submitted?
Obviously, if an expected input
field was not submitted, there will no entry in the $_REQUEST array for that
field. You may get an execution error, if you are not checking the existence of
the expected entries in $_REQUEST. For example, if you copy
processing_forms.php to your local Web server, and run your browser with
http://localhost/processing_forms.php?name=Joe, you will an error page like
this:
You have submitted the following
information:
Name = Joe
Comments =
Thank you!
PHP Notice: Undefined index:
comment in
...\processing_forms.php on line 3
How To Avoid the Undefined Index
Error?
If you don't want your PHP page to
give out errors as shown in the previous exercise, you should consider checking
all expected input fields in $_REQUEST with the isset() function as shown in
the example script below:
<?php
if (isset($_REQUEST['name'])) {
$name = $_REQUEST['name'];
} else {
$name = "";
}
if (isset($_REQUEST['comment'])) {
$comment = $_REQUEST['comment'];
} else {
$comment = "";
}
print("<html><pre>");
print("You have submitted the
following information:\n");
print(" Name = $name\n");
print(" Comments =
$comment\n");
print("Thank you!\n");
print("</pre></html>\n");
?>
How To List All Values of Submitted
Fields?
If you want list all values of
submitted fields, you can write a simple loop to retrieve all entries in the
$_REQUEST array. Below is an improved version of processing_forms.php to list
all submited input values:
<?php
print("<html><pre>");
$count = count($_REQUEST);
print("Number of values:
$count\n");
foreach ($_REQUEST as
$key=>$value) {
print(" $key = $value\n");
}
print("</pre></html>\n");
?>
If you test this with
submit_comments.php on your Web server, you will get something like:
Number of values: 2
name = Pickzy Center
comment = Good job.
What Are the Input Values of SELECT
Tags?
SELECT tags are used in forms to
provide dropdown lists. Entris in a dropdown list are defined by OPTION tags,
which can provide input values in two ways:
Implicit value - Provided as
<OPTION>input_value</OPTION>, where input_value will be used as
both the dropdown entry and the input value if this entry is selected.Explicit
value - Provided as <OPTION
VALUE=input_value>display_value</OPTION>, where display_value will be
used as the download entry, and input_value will be used as the input value if
this entry is selected.The sample PHP script page below is a modified version
of submit_comments.php that has one SELECT tag named as "job" using
implicit input values and another SELECT tag named s "site" using
explicit input values:
<?php
print("<html><form
action=processing_forms.php method=post>");
print("<table><tr><td
colspan=2>Please enter and submit your"
." comments about
PICKZYCenter.com:</td></tr>");
print("<tr><td>Your
Name:</td>"
."<td><input type=text
name=name></td></tr>\n");
print("<tr><td>Your
Job Title:</td>"
."<td><select
name=job>"
."<option>Developer</option>"
."<option>QA
Engineer</option>"
."<option>DBA</option>"
."<option>Other</option>"
."</select></td></tr>\n");
print("<tr><td>Rate
This Site:</td>"
."<td><select
name=rate>"
."<option
value=3>Good</option>"
."<option
value=2>Average</option>"
."<option
value=1>Poor</option>"
."</select></td></tr>\n");
print("<tr><td>Comments:</td>"
."<td><input type=text
name=comment></td></tr>\n");
print("<tr><td
colspan=2><input
type=submit><td></tr></table>\n");
print("</form></html>\n");
?>
If you submit the form with this
page, you will get something like this:
Number of values: 4
name = Joe
job = Developer
rate = 3
comment = I like it.
How To Specify Input Values for
Radio Buttons?
Radio buttons can be used in a form
for two situations:
As a single switch - One <INPUT
TYPE=RADIO ...> tag, with no input value specified. When submitted with
button pushed down, you will receive a value of "on". When submitted
with button not pushed, this field will not be submitted.As a group of
exclusive selections - Multiple <INPUT TYPE=RADIO ...> tags with the same
field name with different input values specified in the "value"
attribute. When submitted, only one input value that associated with pushed
button will be submitted.The sample PHP script page below is a modified version
of submit_comments.php that has one group of exclusive radio buttons named as
"job" and single switch named as "rate":
<?php
print("<html><form
action=processing_forms.php method=post>");
print("<table><tr><td
colspan=2>Please enter and submit your"
." comments about
PICKZYCenter.com:</td></tr>");
print("<tr><td>Your
Name:</td>"
."<td><input type=text
name=name></td></tr>\n");
print("<tr><td>Your
Job Title:</td>"
."<td><input
type=radio name=job value=dev>Developer "
."<input type=radio name=job
value=sqa>QA Engineer "
."<input type=radio name=job
value=dba>DBA "
."<input type=radio name=job
value=other>Other "
."</td></tr>\n");
print("<tr><td>Like
Site:</td>"
."<td><input
type=radio name=rate></td></tr>\n");
print("<tr><td>Comments:</td>"
."<td><input type=text
name=comment></td></tr>\n");
print("<tr><td
colspan=2><input
type=submit><td></tr></table>\n");
print("</form></html>\n");
?>
If you submit the form with this
page, you will get something like this:
Number of values: 4
name = Sue
job = sqa
rate = on
comment = Will visit
PICKZYCenter.com again.
How To Specify Input Values for
Checkboxes?
Checkboxes can be used in a form for
two situations:
As a single switch - One <INPUT
TYPE=CHECKBOX ...> tag, with no input value specified. When submitted with
button pushed down, you will receive a value of "on". When submitted
with button not pushed, this field will not be submitted.As a group of multiple
selections - Multiple <INPUT TYPE=CHECKBOX ...> tags with the same field
name with different input values specified in the "value" attribute.
When submitted, input values that associated with checked boxes will be
submitted.The sample PHP script page below is a modified version of
submit_comments.php that has one group of multiple checkboxes and single
switch:
<?php
print("<html><form
action=processing_forms.php method=post>");
print("<table><tr><td
colspan=2>Please enter and submit your"
." comments about
PICKZYCenter.com:</td></tr>");
print("<tr><td>Your
Name:</td>"
."<td><input type=text
name=name></td></tr>\n");
print("<tr><td>Site
Visited:</td><td>"
."<input type=checkbox
name=site value=dev>Dev PICKZY Center "
."<input type=checkbox
name=site value=sqa>SQA PICKZY Center "
."<input type=checkbox
name=site value=dba>DBA PICKZY Center "
."</td></tr>\n");
print("<tr><td>Like
Site:</td>"
."<td><input
type=checkbox name=rate></td></tr>\n");
print("<tr><td>Comments:</td>"
."<td><input type=text
name=comment></td></tr>\n");
print("<tr><td
colspan=2><input
type=submit><td></tr></table>\n");
print("</form></html>\n");
?>
If you submit the form with this
page, you will get something like this:
Number of values: 4
name = Peter
site = dba
rate = on
comment = All good sites
But there is a problem with script
in processing_forms.php. It picks up only one of the input values selected from
the checkbox group. See the next tip for solutions.
How To Retrieve Input Values for
Checkboxes Properly?
If multiple input values are
submitted with the same field name, like the case of a group of checkboxes, you
should add ([]) to the end of the field name. This tells the PHP engine that
multiple values are expected for this field. The engine will then store the
values in an indexed array, and put the array as the "value" in
$_REQUEST. In order to retrieve multiple values of checkboxes properly, you
need to treat $_REQUEST[field_name] as an array. The following PHP script is an
enhanced version of processing_forms.php that handles multiple values properly:
<?php
print("<html><pre>");
$count = count($_REQUEST);
print("Number of values:
$count\n");
foreach ($_REQUEST as
$key=>$value) {
if (is_array($value)) {
print("
$key is an array\n");
for ($i = 0; $i < count($value);
$i++) {
print("
".$key."[".$i."] = ".$value[$i]."\n");
}
} else {
print("
$key = $value\n");
}
}
print("</pre></html>\n");
?>
Now you need to modify the
submit_comments.php as:
<?php
print("<html><form
action=processing_forms.php method=post>");
print("<table><tr><td
colspan=2>Please enter and submit your"
." comments about
PICKZYCenter.com:</td></tr>");
print("<tr><td>Your
Name:</td>"
."<td><input type=text
name=name></td></tr>\n");
print("<tr><td>Site
Visited:</td><td>"
."<input type=checkbox
name=site[] value=dev>Dev PICKZY Center, "
."<input type=checkbox
name=site[] value=sqa>SQA PICKZY Center, "
."<input type=checkbox
name=site[] value=dba>DBA PICKZY Center "
."</td></tr>\n");
print("<tr><td>Like
Site:</td>"
."<td><input
type=checkbox name=rate></td></tr>\n");
print("<tr><td>Comments:</td>"
."<td><input type=text
name=comment></td></tr>\n");
print("<tr><td
colspan=2><input
type=submit><td></tr></table>\n");
print("</form></html>\n");
?>
If you test the form by selecting two
checkboxes, you will get something like this:
Number of values: 4
name = Mary
site is an array
site[0] = dev
site[1] = sqa
rate = on
comment = Good sites for developers.
How To Supply Default Values for
Text Fields?
If you want to provide a default value
to a text field in your form, you need to pay attention to following notes:
The default value should be provided
in the 'VALUE=default_value' attribute in the <INPUT TYPE=TEXT ...>
tag.The length of the default value should be less than the max length
specified in the "MAXLENGTH=nnn" attribute. If you provide default
value longer than the max length, the default value will be truncated when
submitted.You should put the default value inside double-quotes as
'VALUE="$default_value"' to protect spaces.You must apply
htmlspecialchars() translation function to the default value to protect HTML
sensitive characters, like double quotes.The PHP script below is a modified
version of submit_comments.php with a default value in the "comment"
field:
<?php
$comment = 'I want to say:
"It\'s a good site! :->"';
$comment =
htmlspecialchars($comment);
print("<html><form
action=processing_forms.php method=post>");
print("<table><tr><td
colspan=2>Please enter and submit your"
." comments about
PICKZYCenter.com:</td></tr>");
print("<tr><td>Your
Name:</td>"
."<td><input type=text
name=name></td></tr>\n");
print("<tr><td>Comments:</td>"
."<td><input type=text
name=comment value=\"$comment\" size=40>"
."</td></tr>\n");
print("<tr><td
colspan=2><input type=submit><td></tr></table>\n");
print("</form></html>\n");
?>
If you view this PHP page, you will
a form with default value nicely displayed in the comment field. If you submit
the form, you will get something like this:
Number of values: 2
name = Alan
comment = I want to say:
\"It\'s a good site! :->\"
Notice that special characters are
protected with slashes when form is submitted. See the next tip on how to
remove slashes.
How To Remove Slashes on Submitted
Input Values?
By default, when input values are
submitted to the PHP engine, it will add slashes to protect single quotes and
double quotes. You should remove those slashes to get the original values by
applying the stripslashes() function. Note that PHP engine will add slashes if
the magic_quotes_gpc switch is turned off. The PHP script below is an enhanced
version of processing_forms.php with slashes removed when magic_quotes_gpc is
turned on:
<?php
print("<html><pre>");
$count = count($_REQUEST);
print("Number of values:
$count\n");
foreach ($_REQUEST as
$key=>$value) {
if (is_array($value)) {
print(" $key is an
array\n");
for ($i = 0;
$i < count($value); $i++) {
$sub_value = $value[$i];
if (get_magic_quotes_gpc()) {
$sub_value =
stripslashes($sub_value);
}
print("
".$key."[".$i."] = ".$sub_value."\n");
}
} else {
if
(get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
print(" $key = $value\n");
}
}
print("</pre></html>\n");
?>
Now if you submit the same data
again as in the previous exercise, you will get the original values as:
Number of values: 2
name = Alan
comment = I want to say: "It's
a good site! :->"
How To Support Multiple Submit
Buttons?
Sometimes, you may need to give
visitors multiple submit buttons on a single form to allow them to submit the
form for different purposes. For example, when you show your customer a
purchase order in a Web form, you may give your customer 3 submit buttons as
"Save", "Copy", and "Delete". You can do this by
adding "name" and "value" attributes to the <INPUT
TYPE=submit ...> tags to differentiate the buttons. The following PHP script
is a modified version of submit_comments.php with 3 submit buttons:
<?php
$comment = 'I want to say:
"It\'s a good site! :->"';
$comment =
htmlspecialchars($comment);
print("<html><form
action=processing_forms.php method=post>");
print("<table><tr><td
colspan=2>Please enter and submit your"
." comments about
PICKZYCenter.com:</td></tr>");
print("<tr><td>Your
Name:</td>"
."<td><input type=text
name=name></td></tr>\n");
print("<tr><td>Comments:</td>"
."<td><input type=text
name=comment value=\"$comment\" size=40>"
."</td></tr>\n");
print("<tr><td
colspan=2>"
.'<input type=submit name=submit
value="Submit now">'
.'<input type=submit name=submit
value="Save only">'
.'<input type=submit name=submit
value="Cancel">'
."<td></tr></table>\n");
print("</form></html>\n");
?>
If you view this PHP page, you will
see 3 buttons. If submit the form by clicking the "Save only" button,
you will get something like this:
Number of values: 3
name = Peter
comment = I want to say: "It's
a good site! :->"
submit = Save only
Obviously, different code logics
should be written based on the received value of the "submit" field.
How To Support Hidden Form Fields?
Hidden fields are special fields in
a form that are not shown on the Web page. But when the form is submitted,
values specified in the hidden fields are also submitted to the Web server. A
hidden field can be specified with the <INPUT TYPE=HIDDEN ...> tag. The
PHP script below shows you a good example:
<?php
print("<html><form
action=processing_forms.php method=post>");
print("<input type=hidden
name=module value=FAQ>\n");
print("<table><tr><td
colspan=2>Please enter and submit your"
." comments about
PICKZYCenter.com:</td></tr>");
print("<tr><td>Your
Name:</td>"
."<td><input type=text
name=name></td></tr>\n");
print("<tr><td>Comments:</td>"
."<td><input type=text
name=comment size=40>"
."</td></tr>\n");
print("<tr><td
colspan=2>"
.'<input type=submit name=submit
value="Submit">'
."<td></tr></table>\n");
print("</form></html>\n");
?>
If you submit this form, you will
get something like this:
Number of values: 4
module = FAQ
name = Peter
comment = Thanks for the good tips.
submit = Submit
How To Generate and Process a Form
with the Same Script?
In previous exercises, a Web form is
generated by one script, and processed by another script. But you could write a
single script to do both. You just need to remember to:
Use same script name as the form
generation script in the "action" attribute in the <FORM>
tag.Write two sections in the script: one for form generation, the other for
form processing.Check one expected input to determine which section to use.The
PHP script below shows you a good example:
<?php
if (!isset($_REQUEST['submit'])) {
generatingForm();
} else {
processingForm();
}
function generatingForm() {
print("<html><form
action=submit_comments.php method=post>");
print("<input type=hidden
name=module value=FAQ>\n");
print("<table><tr><td
colspan=2>Please enter and submit your"
." comments about
PICKZYCenter.com:</td></tr>");
print("<tr><td>Your
Name:</td>"
."<td><input type=text
name=name></td></tr>\n");
print("<tr><td>Comments:</td>"
."<td><input type=text
name=comment size=40>"
."</td></tr>\n");
print("<tr><td
colspan=2>"
.'<input type=submit name=submit
value="Submit">'
."<td></tr></table>\n");
print("</form></html>\n");
}
function processingForm() {
print("<html><pre>");
$count = count($_REQUEST);
print("Number of values:
$count\n");
foreach ($_REQUEST as
$key=>$value) {
if (is_array($value)) {
print(" $key is an
array\n");
for ($i = 0; $i < count($value);
$i++) {
$sub_value = $value[$i];
if (get_magic_quotes_gpc()) {
$sub_value =
stripslashes($sub_value);
}
print("
".$key."[".$i."] = ".$sub_value."\n");
}
} else {
if
(get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
print(" $key = $value\n");
}
}
print("</pre></html>\n");
}
?>
If you save this script as
submit_comments.php on your Web server, and submit this form, you will get
something like this:
Number of values: 4
module = FAQ
name = Ray
comment = Good site for beginners.
submit = Submit
How To Submit Values without a Form?
If you know the values you want to
submit, you can code the values in a hyper link at the end of the URL. The
additional values provided at the end of a URL is called query string. There
are two suggestions on how to use query strings to submit values to the
receiving script page:
Code values in the same way as the
form method GET as: url?name=value&name=value... This allows the receiving
script to retrieve input values in the $_REQUEST array or $_GET array.Code
values in your own wan as: url?your_values_in_your_format. The receiving script
needs to pick up the input values in $_SERVER['QUERY_STRING'].Here is a simple
script page that shows you two hyper links with query strings in different
formats:
<?php
print("<html>");
print("<p>Please click
the links below"
." to submit comments about
PICKZYCenter.com:</p>");
print("<p>"
.'<a
href="processing_forms.php?name=Guest&comment=Excellent">'
."It's an excellent
site!</a></p>");
print("<p>"
.'<a href="processing_forms.php?Visitor,Average">'
."It's an average
site.</a></p>");
print("</html>");
?>
If you copy this script as
submit_comments.php to your Web server, and click the first link, you will get:
Number of values: 2
name = Guest
comment = Excellent
If you click the second link, the
current processing_forms.php will not pick up input values from $_REQUEST
properly as showb below:
Number of values: 1
Visitor,Average =
How To Retrieve the Original Query
String?
If you have coded some values in the
URL without using the standard form GET format, you need to retrieve those
values in the original query string in $_SERVER['QUERY_STRING']. The script
below is an enhanced version of processing_forms.php which print the original
query string:
<?php
print("<html><pre>");
print(" query_string =
{$_SERVER['QUERY_STRING']}\n");
$count = count($_REQUEST);
print("Number of values:
$count\n");
foreach ($_REQUEST as
$key=>$value) {
if (is_array($value)) {
print(" $key is an
array\n");
for ($i = 0; $i < count($value);
$i++) {
$sub_value = $value[$i];
if (get_magic_quotes_gpc()) {
$sub_value =
stripslashes($sub_value);
}
print("
".$key."[".$i."] = ".$sub_value."\n");
}
} else {
if
(get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
print(" $key = $value\n");
}
}
print("</pre></html>\n");
?>
How To Protect Special Characters in
Query String?
If you want to include special
characters like spaces in the query string, you need to protect them by
applying the urlencode() translation function. The script below shows how to
use urlencode():
<?php
print("<html>");
print("<p>Please click
the links below"
." to submit comments about
PICKZYCenter.com:</p>");
$comment = 'I want to say:
"It\'s a good site! :->"';
$comment = urlencode($comment);
print("<p>"
."<a href=\"processing_forms.php?name=Guest&comment=$comment\">"
."It's an excellent
site!</a></p>");
$comment = 'This visitor said:
"It\'s an average site! :-("';
$comment = urlencode($comment);
print("<p>"
.'<a
href="processing_forms.php?'.$comment.'">'
."It's an average site.</a></p>");
print("</html>");
?>
If you copy this script as
submit_comments.php to your Web server, and click the first link, you will get:
query_string =
name=Guest&comment=
I+want+to+say%3A+%22It%27s+a+good+site%21+%3A-%3E%22
Number of values: 2
name = Guest
comment = I want to say: "It's
a good site! :->"
If you click the second link, you
will get:
query_string
=
This+visitor+said%3A+%22It%27s+an+average+site%21+%3A-%28%22
Number of values: 1
This_visitor_said:_\"It\'s_an_average_site!_:-(\"
=
Now you know that urlencode() all
special characters into HEX numbers. To translate them back, you need to apply
urldecode().
How To Support Multiple-Page Forms?
If you have a long form with a lots
of fields, you may want to divide the fields into multiple groups and present
multiple pages with one group of fields on one page. This makes the a long form
more user-friendly. However, this requires you to write good scripts that:
When processing the first page and
other middle pages, you must keep those input values collected so far in the
session or as hidden values in the next page form.When processing the last
page, you should collect all input values from all pages for final process,
like saving everything to the database.What Is a Cookie?
A cookie is a small amount of
information sent by a Web server to a web browser and then sent back unchanged
by the browser each time it accesses that server. HTTP cookies are used for
authenticating, tracking, and maintaining specific information about users,
such as site preferences and the contents of their electronic shopping carts.
The term "cookie" is derived from "magic cookie", a
well-known concept in computing which inspired both the idea and the name of
HTTP cookies.
A cookie consists of a cookie name
and cookie value. For example, you can design a cookie with a name of
"LoginName" and a value of "PICKZYCenter".
How To Send a Cookie to the Browser?
If you want to sent a cookie to the
browser when it comes to request your PHP page, you can use the setcookie( )
function. Note that you should call setcookie() function before any output
statements. The following script shows you how to set cookies:
<?php
setcookie("LoginName","PICKZYCenter");
setcookie("PreferredColor","Blue");
print("2 cookies were
delivered.\n");
?>
How To Receive a Cookie from the
Browser?
If you know that a cookie has been
sent to the browser when it was visiting the server previously, you can check
the built-in $_COOKIE array, which contains all cookies that were sent by the
server previously. The script below shows you how to pickup one cookie from the
$_COOKIE and loop through all cookies in $_COOKIE:
<?php
if
(isset($_COOKIE["LoginName"])) {
$loginName =
$_COOKIE["LoginName"];
print("Received a cookie named
as LoginName: ".$loginName."\n");
} else {
print("Did not received any
cookie named as LoginName.\n");
}
print("All cookies
received:\n");
foreach ($_COOKIE as $name =>
$value) {
print " $name = $value\n";
}
If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!
0 comments:
Have any question? Feel Free To Post Below: