Professional Documents
Culture Documents
I. PHP and Web Forms: UNIT-4 Advanced PHP Programming
I. PHP and Web Forms: UNIT-4 Advanced PHP Programming
I. PHP and Web Forms: UNIT-4 Advanced PHP Programming
A Simple Example
II. Working with Files
The following script renders a form that
prompts the user for his name and e-mail 1. The Concept of a Resource
address. Once completed and submitted,
the script (named subscribe.php) displays The term resource is commonly used to
this information back to the browser refer to any entity from which an input or
window. output stream can be initiated.
Standard input or output, files, and network
<?php sockets are all examples of resources.
// If the name field is filled in
if (isset($_POST['name'])) 2. Recognizing Newline Characters
{ The newline character, represented by the
$name = $_POST['name']; \n character sequence (\r\n on Windows),
$email = $_POST['email']; denotes the end of a line within a file.
printf("Hi %s! <br />", $name); 3. Recognizing the End-of-File Character
printf("The email address is %s <br />", The feof() function determines whether a
$email); resource’s EOF has been reached. It is used
} quite commonly in file I/O operations. Its
?> prototype follows:
<form action="subscribe.php"
method="post"> int feof(string resource)
<p>
Name:<br /> An example follows:
<input type="text" id="name" <?php
name="name" size="20" maxlength="40" /> // Open a text file for reading purposes
</p> $fh = fopen('/www/data/users.txt', 'r');
<p>
Email Address:<br />
// While the end-of-file hasn't been pointer to the beginning of the file. If
reached, retrieve the next line the file does not exist, attempt to
while (!feof($fh)) echo fgets($fh); create it.
The fopen() function binds a file to a a+ Read and write. The file pointer is
handle. placed at the end of the file. If the file
does not exist, attempt to create it.
Its prototype follows: This process is known as appending to
the file.
resource fopen(string resource, string
mode [, int use_include_path [, resource x Create and open the file for writing
context]]) only. If the file exists, fopen() will fail
and an error of level E_WARNING will
While fopen() is most commonly used to be generated.
open files for reading and manipulation, it’s
also capable of opening resources via a x+ Create and open the file for writing
number of protocols, including HTTP, and writing. If the file exists, fopen()
HTTPS, and FTP. will fail and an error of level
E_WARNING will be generated.
The mode, assigned at the time a resource
is opened, determines the level of access
available to that resource. If the resource is found on the local file
system, PHP expects it to be available by
Mode Description the path prefacing it.
R Read-only. The file pointer is placed at Alternatively, you can assign fopen()’s
the beginning of the file. use_include_path parameter the value of 1,
which will cause PHP to look for the
r+ Read and write. The file pointer is resource within the paths specified by the
placed at the beginning of the file. include_path configuration directive.
Translating Web Sites with Gettext Common Country and Language Code
Gettext (www.gnu.org/software/gettext), Combinations
one of the many great projects created and Combination Locale
maintained by the Free Software pt_BR Brazil
Foundation, consists of a number of utilities fr_FR France
useful for internationalizing and localizing de_DE Germany
software. Over the years it’s become a de en_GB Great Britain
facto standard solution for maintaining he_IL Israel
translations for countless applications and it_IT Italy
web sites. PHP interacts with gettext es_MX Mexico
through a namesake extension, meaning es_ES Spain
you need to download the gettext utility en_US United States
and install it on your system. If you’re
running Windows,download it from Presents a simple example that seeks to
http://gnuwin32.sourceforge.net and make translate the string Enter your email
sure you update the PATH environment address: to its Italian equivalent.
variable to point to the installation
directory. <?php
Because PHP’s gettext extension isn’t // Specify the target language
enabled by default, you probably need to $language = 'it_IT';
reconfigure PHP. If you’re on Linux, you can // Assign the appropriate locale
enable it by rebuilding PHP with the --with- setlocale(LC_ALL, $language);
gettext option. On Windows, just // Identify the location of the translation
uncomment the php_gettext.dll line found files
in the php.ini file. bindtextdomain('messages',
'/usr/local/apache/htdocs/locale');
Step 1: Update the Web Site Scripts
// Tell the script which domain to search %>xgettext -n *.php
within when translating text
textdomain('messages'); The -n option results in the file name and
?> line number being included before each
<form action="subscribe.php" string entry in the output file. By default,
method="post"> the output file is named messages.po,
<?php echo gettext("Enter your e-mail although you can change this using the --
address:"); ?><br /> default-domain=FILENAME option.
<input type="text" id="email"
name="email" size="20" maxlength="40" A sample output file follows:
value="" /> # SOME DESCRIPTIVE TITLE.
<input type="submit" id="submit" # Copyright (C) YEAR THE PACKAGE'S
value="Submit" /> COPYRIGHT HOLDER
</form> # This file is distributed under the same
license as the PACKAGE package.
Step 2: Create the Localization Repository # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
Next, you need to create the repository #
where the translated files will be stored. #, fuzzy
One directory should be created for each msgid ""
language/country code combination, and msgstr ""
within that directory you need to create "Project-Id-Version: PACKAGE VERSION\n"
another directory named LC_MESSAGES. So "Report-Msgid-Bugs-To: \n"
if you plan on localizing the web site to "POT-Creation-Date: 2010-05-16 13:13-
support English (the default), German, 0400\n"
Italian, and Spanish, the directory structure
would look like this:
locale/ "PO-Revision-Date: YEAR-MO-DA
de_DE/ HO:MI+ZONE\n"
LC_MESSAGES/ "Last-Translator: FULL NAME
it_IT/ <EMAIL@ADDRESS>\n"
LC_MESSAGES/ "Language-Team: LANGUAGE
es_ES/ <LL@li.org>\n"
LC_MESSAGES/ "MIME-Version: 1.0\n"
"Content-Type: text/plain;
Step 3: Create the Translation Files charset=CHARSET\n"
Next, you need to extract the translatable "Content-Transfer-Encoding: 8bit\n"
strings from the PHP scripts. You do so with #: homepage.php:12
the xgettext command, which is a utility msgid "Subscribe to the newsletter:"
bundled with gettext. Executing the msgstr ""
following command will cause xgettext to #: homepage.php:15
examine all of the files found in the current msgid "Enter your e-mail address:"
directory ending in .php, producing a file msgstr ""
consisting of the desired strings to #: contact.php:12
translate: msgid "Contact us at info@example.com!"
msgstr "" For example, suppose you are a United
States–based organization providing an
Step 4: Translate the Text essential subscription based service to a
Open the messages.po file residing in the variety of international corporations. When
language directory you’d like to translate, it is time to renew subscriptions, a special
and translate the strings by completing the message is displayed at the top of the
empty msgstr entries that correspond to an browser that looks like this:
extracted string. Then replace the
placeholders represented in all capital Your subscription ends on 3-4-2011. Renew
letters with information pertinent to your soon to avoid service cancellation.
application.
For the United States–based users, this date
Step 5: Generate Binary Files means March 4, 2011. However, for
The final required preparatory step involves European users, this date is interpreted as
generating binary versions of the April 3, 2011. The result could be that the
messages.po files, which will be used by European users won’t feel compelled to
gettext. This is done with the msgfmt renew the service until the end of March,
command. Navigate to the appropriate and therefore will be quite surprised when
language directory and execute the they attempt to log in on March 5. This is
following command: just one of the many issues that might arise
%>msgfmt messages.po due to confusion over data representation.
Executing this command produces a file You can eliminate such inconsistencies by
named messages.mo, which is what gettext localizing the information so that it appears
will ultimately use for the translations. exactly as the user expects. PHP makes this
a fairly easy task, done by setting the locale
Step 6: Set the Desired Language Within using setlocale(), and then using functions
Your Scripts such as money_format(), number_format(),
To begin taking advantage of your localized and strftime() per usual to output the data.
strings, all you need to do is set the locale For example, suppose you want to render
using setlocale() and call the the renewal deadline date according to the
bindtextdomain() and textdomain() user’s locale.
functions. The end result is the ability to use Just set the locale using setlocale(), and run
the same code source to present your web the date through strftime() (also taking
site in multiple languages. advantage of strtotime() to create the
appropriate timestamp) like this:
Localizing Dates, Numbers, and
Times <?php
The setlocale() function can also affect how setlocale(LC_ALL, 'it_IT');
PHP renders dates, numbers, and times. printf("Your subscription ends on %s",
This is important because of the variety of strftime('%x', strtotime('2011-03-04')));
ways in which this often crucial data is ?>
represented among different countries. This produces the following:
Your subscription ends on 04/03/2011 $locale['thousands_sep']));
?>
The same process applies to formatting
number and monetary values. For instance, This produces the following result:
the United States uses a comma as the (it_IT) Total hours spent commuting
thousands separator; Europe uses a period, 4532,23
a space, or nothing at all for the same (en_US) Total hours spent commuting
purpose. Making matters more confusing, 4,532.23
the United States uses a period for the
decimal separator and Europe uses a
comma for this purpose. As a result, the
following numbers are ultimately
considered identical:
• 523,332.98
• 523 332.98
• 523332.98
• 523.332,98
<?php
setlocale(LC_ALL, 'it_IT');
$locale = localeconv();
printf("(it_IT) Total hours spent commuting
%s <br />",
number_format(4532.23, 2,
$locale['decimal_point'],
$locale['thousands_sep']));
setlocale(LC_ALL, 'en_US');
$locale = localeconv();
printf("(en_US) Total hours spent
commuting %s",
number_format(4532.23, 2,
$locale['decimal_point'],