php-doc-en/chapters/tutorial.xml
Philip Olson 48af34847f Removing "autoglobal" in favor of "superglobal" as it's the "official" term.
This should not confuse users because superglobal is used about 4x as often
in the manual, and it's what most people say/write. This old term is leftover
from when these auto super global variables were first introduced.


git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@229400 c90b9560-bf6c-de11-be94-00142212c4b1
2007-02-09 07:28:30 +00:00

549 lines
22 KiB
XML

<?xml version="1.0" encoding="iso-8859-9"?>
<!-- $Revision: 1.46 $ -->
<chapter id="tutorial">
<title>A simple tutorial</title>
<para>
Here we would like to show the very basics of PHP in a short, simple
tutorial. This text only deals with dynamic webpage creation with
PHP, though PHP is not only capable of creating webpages. See
the section titled <link linkend="intro-whatcando">What can PHP
do</link> for more information.
</para>
<para>
PHP-enabled web pages are treated just like regular HTML pages and
you can create and edit them the same way you normally create
regular HTML pages.
</para>
<sect1 id="tutorial.requirements">
<title>What do I need?</title>
<para>
In this tutorial we assume that your server has activated support
for PHP and that all files ending in <filename>.php</filename>
are handled by PHP. On most servers, this is the default extension
for PHP files, but ask your server administrator to be sure. If
your server supports PHP, then you do not need to do anything. Just
create your <filename>.php</filename> files, put them in your
web directory and the server will automatically parse them for you.
There is no need to compile anything nor do you need to install
any extra tools. Think of these PHP-enabled files as simple HTML
files with a whole new family of magical tags that let you do all
sorts of things. Most web hosts offer PHP support, but if your
host does not, consider reading the <ulink url="&url.php.links;">
PHP Links</ulink> section for resources on finding PHP enabled
web hosts.
</para>
<para>
Let us say you want to save precious bandwidth and develop locally.
In this case, you will want to install a web server, such as
<ulink url="&url.apache;">Apache</ulink>, and of course
<ulink url="&url.php.downloads;">PHP</ulink>. You will most likely
want to install a database as well, such as
<ulink url="&url.mysql.docs;">MySQL</ulink>.
</para>
<para>
You can either install these individually or choose a simpler way. Our
manual has <link linkend="install">installation instructions for
PHP</link> (assuming you already have some webserver set up). In case
you have problems with installing PHP yourself, we would suggest you ask
your questions on our <ulink url="&url.php.mailing-lists;">installation
mailing list</ulink>. If you choose to go on the simpler route, then
<ulink url="&url.installkits;">locate a pre-configured package</ulink>
for your operating system, which automatically installs all of these
with just a few mouse clicks. It is easy to setup a web server with PHP
support on any operating system, including MacOSX, Linux and Windows.
On Linux, you may find <ulink url="&url.rpmfind;">rpmfind</ulink> and
<ulink url="&url.rpmfind.pbone;">PBone</ulink> helpful for
locating RPMs. You may also want to visit <ulink
url="&url.apt-get;">apt-get</ulink> to find packages for Debian.
</para>
</sect1>
<sect1 id="tutorial.firstpage">
<title>Your first PHP-enabled page</title>
<para>
Create a file named <filename>hello.php</filename> and put it
in your web server's root directory (<varname>DOCUMENT_ROOT</varname>)
with the following content:
</para>
<para>
<example>
<title>Our first PHP script: <filename>hello.php</filename></title>
<programlisting role="php">
<![CDATA[
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
]]>
</programlisting>
<simpara>
Use your browser to access the file with your web server's URL, ending
with the "/hello.php" file reference. When developing locally this
URL will be something like <literal>http://localhost/hello.php</literal>
or <literal>http://127.0.0.1/hello.php</literal> but this depends on the
web server's configuration. If everything is configured correctly, this
file will be parsed by PHP and the following output will be sent to
your browser:
</simpara>
<screen role="html">
<![CDATA[
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<p>Hello World</p>
</body>
</html>
]]>
</screen>
</example>
</para>
<para>
This program is extremely simple and you really did not need to use
PHP to create a page like this. All it does is display:
<literal>Hello World</literal> using the PHP <function>echo</function>
statement. Note that the file <emphasis>does not need to be executable</emphasis>
or special in any way. The server finds out that this file needs to be interpreted
by PHP because you used the ".php" extension, which the server is configured
to pass on to PHP. Think of this as a normal HTML file which happens to have
a set of special tags available to you that do a lot of interesting things.
</para>
<para>
If you tried this example and it did not output anything, it prompted
for download, or you see the whole file as text, chances are that the
server you are on does not have PHP enabled, or is not configured properly.
Ask your administrator to enable it for you using the
<link linkend="install">Installation</link> chapter
of the manual. If you are developing locally, also read the
installation chapter to make sure everything is configured
properly. Make sure that you access the file via http with the server
providing you the output. If you just call up the file from your file
system, then it will not be parsed by PHP. If the problems persist anyway,
do not hesitate to use one of the many
<ulink url="&url.php.support;">PHP support</ulink> options.
</para>
<para>
The point of the example is to show the special PHP tag format.
In this example we used <literal>&lt;?php</literal> to indicate the
start of a PHP tag. Then we put the PHP statement and left PHP mode by
adding the closing tag, <literal>?&gt;</literal>. You may jump in
and out of PHP mode in an HTML file like this anywhere you want. For more
details, read the manual section on the <link linkend="language.basic-syntax">
basic PHP syntax</link>.
</para>
<note>
<title>A Note on Line Feeds</title>
<para>
Line feeds have little meaning in HTML, however it is still a good idea
to make your HTML look nice and clean by putting line feeds in. A
linefeed that follows immediately after a closing
<literal>?&gt;</literal> will be removed by PHP. This can be extremely
useful when you are putting in many blocks of PHP or include files
containing PHP that aren't supposed to output anything. At the same time
it can be a bit confusing. You can put a space after the closing
<literal>?&gt;</literal> to force a space and a line feed to be output,
or you can put an explicit line feed in the last echo/print from within
your PHP block.
</para>
</note>
<note>
<title>A Note on Text Editors</title>
<para>
There are many text editors and Integrated Development Environments (IDEs)
that you can use to create, edit and manage PHP files. A partial list of
these tools is maintained at <ulink url="&url.phpeditorlist;">PHP Editors
List</ulink>. If you wish to recommend an editor, please visit the above
page and ask the page maintainer to add the editor to the list. Having
an editor with syntax highlighting can be helpful.
</para>
</note>
<note>
<title>A Note on Word Processors</title>
<para>
Word processors such as StarOffice Writer, Microsoft Word and Abiword are
not optimal for editing PHP files. If you wish to use one for this
test script, you must ensure that you save the file as <emphasis>plain
text</emphasis> or PHP will not be able to read and execute the script.
</para>
</note>
<note>
<title>A Note on Windows Notepad</title>
<para>
If you are writing your PHP scripts using Windows Notepad, you will need
to ensure that your files are saved with the .php extension. (Notepad adds
a .txt extension to files automatically unless you take one of the
following steps to prevent it.) When you save the file and are prompted
to provide a name for the file, place the filename in quotes
(i.e. "<filename>hello.php</filename>"). Alternatively, you can click on the
'Text Documents' drop-down menu in the 'Save' dialog box and change the setting
to "All Files". You can then enter your filename without quotes.
</para>
</note>
<para>
Now that you have successfully created a working PHP script, it is
time to create the most famous PHP script! Make a call to the
<function>phpinfo</function> function and you will see a lot of useful
information about your system and setup such as available
<link linkend="language.variables.predefined">predefined variables</link>,
loaded PHP modules, and <link linkend="configuration">configuration</link>
settings. Take some time and review this important information.
</para>
<para>
<example>
<title>Get system information from PHP</title>
<programlisting role="php">
<![CDATA[
<?php phpinfo(); ?>
]]>
</programlisting>
</example>
</para>
</sect1>
<sect1 id="tutorial.useful">
<title>Something Useful</title>
<para>
Let us do something more useful now. We are going to check
what sort of browser the visitor is using.
For that, we check the user agent string the browser
sends as part of the HTTP request. This information is stored in a <link
linkend="language.variables">variable</link>. Variables always start
with a dollar-sign in PHP. The variable we are interested in right now
is <varname>$_SERVER['HTTP_USER_AGENT']</varname>.
</para>
<note>
<para>
<link linkend="reserved.variables.server">$_SERVER</link> is a
special reserved PHP variable that contains all web server information.
It is known as a superglobal. See the related manual page on
<link linkend="language.variables.superglobals">superglobals</link>
for more information. These special variables were introduced in PHP
<ulink url="&url.php.release4.1.0;">4.1.0</ulink>. Before this time, we used
the older <varname>$HTTP_*_VARS</varname> arrays instead,
such as <varname>$HTTP_SERVER_VARS</varname>. Although deprecated,
these older variables still exist. (See also the note on
<link linkend="tutorial.oldcode">old code</link>.)
</para>
</note>
<para>
To display this variable, you can simply do:
</para>
<para>
<example>
<title>Printing a variable (Array element)</title>
<programlisting role="php">
<![CDATA[
<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>
]]>
</programlisting>
<para>
A sample output of this script may be:
</para>
<screen role="html">
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
</screen>
</example>
</para>
<para>
There are many <link linkend="language.types">types</link> of
variables available in PHP. In the above example we printed
an <link linkend="language.types.array">Array</link> element.
Arrays can be very useful.
</para>
<para>
<varname>$_SERVER</varname> is just one variable that PHP automatically
makes available to you. A list can be seen in the
<link linkend="reserved.variables">Reserved Variables</link> section
of the manual or you can get a complete list of them by looking at
the output of the <function>phpinfo</function> function used in the
example in the previous section.
</para>
<para>
You can put multiple PHP statements inside a PHP tag and create
little blocks of code that do more than just a single echo.
For example, if you want to check for Internet Explorer you
can do this:
</para>
<para>
<example>
<title>Example using <link linkend="language.control-structures">control
structures</link> and <link linkend="language.functions">functions</link></title>
<programlisting role="php">
<![CDATA[
<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
echo 'You are using Internet Explorer.<br />';
}
?>
]]>
</programlisting>
<para>
A sample output of this script may be:
</para>
<screen role="html">
<![CDATA[
You are using Internet Explorer.<br />
]]>
</screen>
</example>
</para>
<para>
Here we introduce a couple of new concepts. We have an
<link linkend="control-structures.if">if</link> statement.
If you are familiar with the basic syntax used by the C
language, this should look logical to you. Otherwise, you
should probably pick up an introductory PHP book and read the first
couple of chapters, or read the <link linkend="langref">Language
Reference</link> part of the manual. You can find a list of PHP books
at <ulink url="&url.php.books;">&url.php.books;</ulink>.
</para>
<para>
The second concept we introduced was the <function>strpos</function>
function call. <function>strpos</function> is a function built into
PHP which searches a string for another string. In this case we are
looking for <literal>'MSIE'</literal> (so-called needle) inside
<varname>$_SERVER['HTTP_USER_AGENT']</varname> (so-called haystack). If
the needle is found inside the haystack, the function returns the position
of the needle relative to the start of the haystack. Otherwise, it
returns &false;. If it does not return &false;, the <link
linkend="control-structures.if">if</link> expression evaluates to &true;
and the code within its {braces} is executed. Otherwise, the code is not
run. Feel free to create similar examples,
with <link linkend="control-structures.if">if</link>,
<link linkend="control-structures.else">else</link>, and other
functions such as <function>strtoupper</function> and
<function>strlen</function>. Each related manual page contains examples
too. If you are unsure how to use functions, you will want to read both
the manual page on <link linkend="about.prototypes">how to read a
function definition</link> and the section about
<link linkend="language.functions">PHP functions</link>.
</para>
<para>
We can take this a step further and show how you can jump in and out
of PHP mode even in the middle of a PHP block:
</para>
<para>
<example>
<title>Mixing both HTML and PHP modes</title>
<programlisting role="php">
<![CDATA[
<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
<h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>
<?php
} else {
?>
<h3>strpos() must have returned false</h3>
<p>You are not using Internet Explorer</p>
<?php
}
?>
]]>
</programlisting>
<para>
A sample output of this script may be:
</para>
<screen role="html">
<![CDATA[
<h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>
]]>
</screen>
</example>
</para>
<para>
Instead of using a PHP echo statement to output something, we jumped out
of PHP mode and just sent straight HTML. The important and powerful point
to note here is that the logical flow of the script remains intact. Only
one of the HTML blocks will end up getting sent to the viewer depending on
the result of <function>strpos</function>. In other words, it depends on
whether the string <literal>MSIE</literal> was found or not.
</para>
</sect1>
<sect1 id="tutorial.forms">
<title>Dealing with Forms</title>
<para>
One of the most powerful features of PHP is the way it handles HTML
forms. The basic concept that is important to understand is that any
form element will automatically be available to your PHP
scripts. Please read the manual section on
<link linkend="language.variables.external">Variables from outside
of PHP</link> for more information and examples on using forms
with PHP. Here is an example HTML form:
</para>
<para>
<example>
<title>A simple HTML form</title>
<programlisting role="html">
<![CDATA[
<form action="action.php" method="post">
<p>Your name: <input type="text" name="name" /></p>
<p>Your age: <input type="text" name="age" /></p>
<p><input type="submit" /></p>
</form>
]]>
</programlisting>
</example>
</para>
<para>
There is nothing special about this form. It is a straight HTML form
with no special tags of any kind. When the user fills in this form
and hits the submit button, the <filename>action.php</filename> page
is called. In this file you would write something like this:
</para>
<para>
<example>
<title>Printing data from our form</title>
<programlisting role="php">
<![CDATA[
Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.
]]>
</programlisting>
<para>
A sample output of this script may be:
</para>
<screen role="html">
<![CDATA[
Hi Joe. You are 22 years old.
]]>
</screen>
</example>
</para>
<para>
Apart from the <function>htmlspecialchars</function> and
<literal>(int)</literal> parts, it should be obvious what this does.
<function>htmlspecialchars</function> makes sure any characters that are
special in html are properly encoded so people can't inject HTML tags
or Javascript into your page. For the age field, since we know it is a
number, we can just <link linkend="language.types.typecasting">convert</link>
it to an <type>integer</type> which will automatically get rid of any
stray characters. You can also have PHP do this for you automatically by
using the <link linkend="ref.filter">filter</link> extension.
The <varname>$_POST['name']</varname> and <varname>$_POST['age']</varname>
variables are automatically set for you by PHP. Earlier we
used the <varname>$_SERVER</varname> superglobal; above we just
introduced the <link linkend="reserved.variables.post">$_POST</link>
superglobal which contains all POST data. Notice how the
<emphasis>method</emphasis> of our form is POST. If we used the
method <emphasis>GET</emphasis> then our form information would live in
the <link linkend="reserved.variables.get">$_GET</link> superglobal instead.
You may also use the <link linkend="reserved.variables.request">$_REQUEST</link>
superglobal, if you do not care about the source of your request data. It
contains the merged information of GET, POST and COOKIE data. Also see the
<function>import_request_variables</function> function.
</para>
<para>
You can also deal with XForms input in PHP, although you will find yourself
comfortable with the well supported HTML forms for quite some time.
While working with XForms is not for beginners, you might be interested
in them. We also have a <link linkend="features.xforms">short introduction
to handling data received from XForms</link> in our features section.
</para>
</sect1>
<sect1 id="tutorial.oldcode">
<title>Using old code with new versions of PHP</title>
<para>
Now that PHP has grown to be a popular scripting language, there are
a lot of public repositories and libraries containing code you can reuse.
The PHP developers have largely tried to preserve backwards compatibility,
so a script written for an older version will run (ideally) without changes
in a newer version of PHP. In practice, some changes will usually be needed.
</para>
<para>
Two of the most important recent changes that affect old code are:
<itemizedlist>
<listitem>
<simpara>
The deprecation of the old <varname>$HTTP_*_VARS</varname> arrays
(which need to be indicated as global when used inside a function or
method). The following
<link linkend="language.variables.superglobals">superglobal arrays</link>
were introduced in PHP <ulink url="&url.php.release4.1.0;">4.1.0</ulink>.
They are: <varname>$_GET</varname>, <varname>$_POST</varname>,
<varname>$_COOKIE</varname>, <varname>$_SERVER</varname>,
<varname>$_FILES</varname>, <varname>$_ENV</varname>,
<varname>$_REQUEST</varname>, and <varname>$_SESSION</varname>. The
older <varname>$HTTP_*_VARS</varname> arrays, such as
<varname>$HTTP_POST_VARS</varname>, still exist as they have since PHP 3.
&avail.register-long-arrays;
</simpara>
</listitem>
<listitem>
<simpara>
External variables are no longer registered in the global scope by
default. In other words, as of PHP
<ulink url="&url.php.release4.2.0;">4.2.0</ulink> the PHP directive
<link linkend="ini.register-globals">register_globals</link> is
<emphasis>off</emphasis> by default in &php.ini;. The preferred
method of accessing these values is via the superglobal arrays mentioned
above. Older scripts, books, and tutorials may rely on this
directive being on. If it were on, for example, one could use
<varname>$id</varname> from the URL
<literal>http://www.example.com/foo.php?id=42</literal>. Whether on
or off, <varname>$_GET['id']</varname> is available.
</simpara>
</listitem>
</itemizedlist>
For more details on these changes, see the section on
<link linkend="language.variables.predefined">predefined variables</link>
and links therein.
</para>
</sect1>
<sect1 id="tutorial.whatsnext">
<title>What's next?</title>
<para>
With your new knowledge you should be able to understand most of
the manual and also the various example scripts available in the
example archives. You can also find other examples on the php.net
websites in the links section:
<ulink url="&url.php.links;">&url.php.links;</ulink>.
</para>
<para>
To view various slide presentations that show more of what PHP can do,
see the PHP Conference Material Sites: <ulink url="&url.php.conf;">
&url.php.conf;</ulink> and <ulink url="&url.php.talks;">&url.php.talks;
</ulink>
</para>
</sect1>
</chapter>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->