; www
Documents
Resources
Learning Center
Upload
Plans & pricing Sign in
Sign Out
Your Federal Quarterly Tax Payments are due April 15th Get Help Now >>

www

VIEWS: 0 PAGES: 75

  • pg 1
									Begin with PHP 1                                         IOPROG




     Begin with PHP 1

       The Core Elements

       Table of Contents

       Client-side and server-side scripting                2
       What is PHP?                                         4
       What is needed to get started?                       5
       Publicering på webbhotell/webbserver                 5
       PHP IDE: Why use one and which to choose             7
       Changing webserver root folder                       7
       Creating the first PHP-enabled script                9
       PHP Core Essentials                                 13
       Functions                                           28
       Using PHP from Commandline                          34
       Input to web browser - PHP Forms and User Input     37
       FileHandling in common                              56
       CRUD – Create, Read, Update, Delete Application     60
       PHP and flat text file CRUD Application             60
       Common Concepts about HTML Forms                    67




                                           1
Begin with PHP 1                                                                                              IOPROG


Client-side and server-side scripting

                                        1
      Client                                                             Web
                                                                        Server
                                        2
                           3
                                        Html page with client
              Script                     side script returned
              interp
               reter

  5                        4


            Html
            page



      1.    A user clicks on a link. His web browser sends the request for the web page e.g.
            http://localhost/test.html
      2.     The web server gets the request for test.html. It is an html page and so the server doesn't need to do
            anything with it other than return it to the client.
      3.     The client detects the presence of client side script and passes the script to the interpreter. The choice of
            interpreter will depend on what type of script we are dealing with (JavaScript, Flash, . . .).
      4.     The interpreter executes the command and places the result into an HTML page.
      5.     The HTML page is displayed at the client.




                                            1
           Client                                                           Web
                                                                           Server

                                                                       2

                                                                           Script
                                                                           page

                                            5
                                                                       3

                                                    Html          4         Script
                                                    page                   interpr
                                                                             eter




      1.    A user clicks on a link .His web browser sends the request for the web page e.g.
            http://localhost/test.php.



                                                              2
Begin with PHP 1                                                                                          IOPROG


   2.    The web server gets the request for test.php. It knows that .php files are handled by the PHP Interpreter
        (by the file extension .php) so it tells PHP to deal with it.
   3.    test.php is a PHP script that contains commands. The commands are passed to the interpreter. The
        choice of interpreter will depend on what type of script we are dealing with.
   4.   The interpreter places the result into an HTML page.
   5.    The HTML page is returned to the client.

        Use of Server Side Scripts

         Server side scripts are used to perform tasks such as build Web pages and access databases.

        Use of Client Side Scripts

         Client side scripts can be used to validate data, control page navigation and create special formatting on

         the Web page.

        Server Side Scripting Languages

         Server side scripting languages include PHP, ASP (Active Server Pages) and C/C++.

        Client Side Scripting Languages

         Client side scripting languages include JavaScript, Flash and ActiveX.




        Considerations

        Server side scripts will run regardless what Web browser is used or what settings are enabled on the client
        machine. Client side scripts will only work if the correct software is installed on the client machine and the
        proper settings are enabled in the Web browser.




                                                           3
Begin with PHP 1                                                                                           IOPROG


What is PHP?

PHP stands for PHP Hypertext Preprocessor.

PHP is a general-purpose scripting language that is especially suited to server-side Wed development where PHP
generally runs on a Web server. Any PHP code in a requested file is executed by the PHP runtime, usually to create
dynamic Web page content or dynamic images used on Web sites or elsewhere. It can also be used for command-
line scripting and client-side GUi applications. PHP acts primarily as a filter, taking input from a file or stream
containing text and/or PHP instructions and outputting another stream of data; most commonly the output will be
HTML.

PHP is server-side:
Your browser doesn't realise the pages it is viewing are initially written with PHP. All it receives is an HTML page -
as complex or as simple as you want.

PHP is HTML-embedded:
A PHP page can be simply an HTML page with a little PHP sprinkled here and there. The PHP bits are parsed
("translated") by the server. The HTML code on the page is sent directly to the browser.

A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere
in the document.

On servers with shorthand support enabled you can start a scripting block with <? and end with ?>.
For maximum compatibility, it is recommended to use the standard form (<?php) rather than the shorthand form.




                                                           4
Begin with PHP 1                                                                                    IOPROG


What is needed to get started?

Web Hotel/Web Server

An user account with a web server area with an environment to develope and publish scripts: PHP scripting
language and a database server MySQL (or other).


Publicering på webbhotell/webbserver

<Webbhotell> hemsida: XXX.XXX.XX

Länkar -> Egen hemsida -> ”Skapa/ändra konto”

                                                                                                        Internet




       Lokal dator                                                   Webbhotell
       Folder/filstruktur                                            Webbserveryta




                              Utforskaren/Explorer

                                 ftp://xxx.xxx.xx


                                 Inloggningsfönster




        C:\.....                    Copy & Paste                      privat/

        H:\.....                                                      public_html/




                     WinSCP (välj SFTP eller SCP, port 22)

                                  Inloggningsfönster




                                    Copy, .., Edit, ..



                                                       5
Begin with PHP 1                                                            IOPROG




                   FileZilla (välj SFTP eller SCP, port 22)

                                  cpanel


Publicering version 0

                                                    privat/

C:\                                                 public_html/

H:\..\Inl_uppg1\Facts.html

       \Inl_uppg1\images\globen-white.jpg

       \www\*.php                                   public_html/www/*.php



Webbläsare

xxxxxxx.xxx.se/Facts.html                           xxxxxxx.xxx.se/www/*.php



Publicering version 1

Användning av public_html/index.html



Databasserver MySQL

“Det finns även en MySQL-databas kopplad till ditt konto. Den
har samma användarnamn och lösenord som ditt vanliga konto
på hem.thg.se. Du kan administrera den via “phpmyadmin.xxx.xx”




                                           6
Begin with PHP 1                                                                                         IOPROG


Complete and ready-to-use environments for PHP developers.

EasyPHP is a WAMP package including the scripting language PHP, the web server Apache, the SQL server
MySQL, as well as easy development tools such as the database manager PhpMyAdmin and the debugger
Xdebug. Nothing to configure. It's already done! EasyPHP is portable.

You can install it on your system or on a USB drive and develop or present locally your PHP code, projects,
websites, scripts, applications...

Other alternatives: WAMP runs on Windows, XAMPP is multi-platform. Aside from that it's a matter of personal
preference. They both provide you with an Apache-MySQL-PHP environment that runs pretty much the same under
both systems.

Installation of EASYPHP, WAMP or XAMMP

EasyPHP: Navigate to this link: http://www.easyphp.org/

WAMP: Navigate to this link: http://www.wampserver.com/en/

XAMMP: Navigate to this link: http://www.apachefriends.org/en/xampp-windows.html#1168


PHP IDE: Why use one and which to choose
Navigate to this link to get a test of PHP IDEs.

http://www.smashingmagazine.com/2009/02/11/the-big-php-ides-test-why-use-oneand-which-to-choose/

Using an IDE: NetBeans 7.0

Navigate to this link to get a NetBeans PHP quickstart tutorial: http://netbeans.org/kb/docs/php/quickstart.html

Using a native Texteditor and Command line “IDE”

See the technique and recommendations in the chapter “Creating the first PHP-enabled script” later on.


Changing webserver root folder
Easy-PHP

Navigate to the link: http://www.easyphp.org/introduction.php

You must place your files either in the directory "www" or an alias that you have created, so that PHP can interpret
your PHP pages. To view your pages, select "local Web" or an Alias on the "Administration" page.

WAMP

Navigate to the link: http://www.tagbytag.org/tutorials/getting-started/web-design-software/wamp-guide

The default root folder for the WAMP installation is the directory “www”. Change the line DocumentRoot
"C:/Program Files/wamp/www/" in the Apache configuration file httpd.conf.




                                                          7
Begin with PHP 1                                                                                       IOPROG


XAMPP

Navigate to the link: http://www.apachefriends.org/en/xampp-windows.html#1168


The main directory for all WWW documents is \xampp\htdocs. If you put a file "test.html" in this directory, you can
access it with the URI "http://localhost/test.html".


A new subdirectory for your web?

Just make a new directory (e.g. "new") inside the directory “\www” or "\xampp\htdocs" (best without whitespaces
and only ASCII), create a test file in this directory and access it with "http://localhost/new/test.php".


IP Address and Port listened to by Apache

Configure the IP address and port for the webserver (Apache) in the configuration file httpd.conf available in the
user interface for Easy-PHP, WAMP or XAMPP environments. If the Windows webserver IIS is installed on the
computer there could be collision with the “standard” port 80. In case the port listened to can be changed to 8080
or 8888 in the htppd.conf file in the entry “Listen”.




                                                         8
Begin with PHP 1                                                                                          IOPROG


Creating the first PHP-enabled script

Output to web browser - PHP inside HTML or PHP HTML-embedded

Create this text file named PHP_in_HTML.html or PHP_in_HTML.php with an ordinary editor. This is an .html file
with PHP embedded with the <?php ?> start-and end tag.

Example PHP 1

<html>
<title>PHP in HTML or HTML with PHP or PHP HTML-embedded</title>
<body>
  <h1>An ordinary HTML h1 tag</h1>

  <?php
    //PHP code here
  ?>

  <p>An ordimary HTML p tag</p>

  <?php
     //More PHP code
  ?>
</body>
</html>

Use your web browser to access the file with your web server's URL, ending with the PHP_in_HTML.html or
PHP_in_HTML.php file reference. When developing locally this URL will be something like
http://localhost/PHP_in_HTML..html/.php or http://127.0.0.1/HPH_in_HTML.html/.php. Depending on the
Easy_PHP, WAMP och XAMMP environment and on the web server configuration the navigation address must/could
include a port address like http://127.0.0.1:8888/PHP_in_HTML.php/.html or
http://127.0.0.1:8080/PHP_in_HTML.php/.html. Also depending and the webserver root folder this folder e.g.
www must/could be added like http://127.0.0.1:8888/www/PHP_in_HTML.php/.html or
http://127.0.0.1:8080/www/PHP_in_HTML.php/.html. If everything is configured correctly, this file will be
parsed by HTTP/web server and the following output will be sent to your browser:



An ordinary HTML h1 tag
An ordinary HTML p tag

Another way to use HTML with PHP is by using print() or echo() functions. By using those methods you can
include the HTML inside of the PHP tags.

print() is not actually a real function (it is a language construct) so you are not required to use parentheses with
its argument list.

echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it.


echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This
short syntax only works with the short_open_tag configuration setting enabled.

If you have PHP inserted into your HTML and want the web browser to interpret it correctly, then you must save the
file with a .php extension, instead of the standard .html extension.




                                                           9
Begin with PHP 1                                                                                          IOPROG


Example PHP 2

Create a file named Hello.php and put it in your web server's root directory (DOCUMENT_ROOT) with
the following content:
<html>
 <head>
  <title>PHP Hello</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'; ?>
 <?php print '<p>Hello World twice</p>'; ?>
 <?php print 'Hello World third time'; ?>
 <?php print 'Hello World forth time <br>'; ?>
 <?php
   //A comment
   print "Hello World fifth time";
 ?>
 </body>
</html>

The following output will be sent to your browser:

<html>
 <head>
  <title>PHP Hello</title>
 </head>
 <body>
 <p>Hello World</p>
 <p>Hello World twice</p>
 Hello World third time
 Hello World forth time <br>
 Hello World fifth time
 </body>
</html>

The output in the browser:

Hello World

Hello World twice

Hello World third time Hello World forth time
Hello World fifth time

Notice the use of the <br> tag.

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: Hello World using the PHP echo() or print() statement. Note that the file does not need to be executable 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.

Each statement ends with a semi-colon ";".
When inside PHP tags, you can add comments:
/* comment */
# comment
// comment
(everything until the end of the line will be ignored in the two last cases; in the first case, the comment can span
multiple lines).

You can switch from PHP to HTML and back just about anywhere. Make your experiences!




                                                          10
Begin with PHP 1                                                                                      IOPROG


Creating a PHP-enabled script with color
The BlueYellow.html file below is a common one-column web page layout designed with XHTML/HTML and
ordinary CSS. You can load it in a web browser and run/render it in the web browser without any interference of
PHP script.

Whenever the web browser and web server communicates, it does so using HTTP "Hypertext Transfer Protocol".
HTTP is a request/response protocol, which means your computer sends a request for some file (e.g. "Get me the
file 'home.html'"), and the web server sends back a response ("Here's the file", followed by the file itself).

<html>
<head>

<style type="text/css">

* {margin:0px; padding:0 px}

#container {
   position:static;
   width:1200px;
}

#header {
  position:absolute;
  top:0px;
  left:0px;
  height:100px;
  width: 1200px;
  background:yellow; color:blue; padding:10px; text-align:center;
  /*border-bottom:5px solid red;*/}

#navigation {
  position: absolute;
  top: 100px;
  left: 0px;
  height: 100px;
  width: 1200px;
  bottom: 500px;
  background:blue; color:yellow; padding:10px; text-align:center;}

#content {
  position:absolute;
  top: 200px;
  left: 0px;
  height: 350px;
  width: 1200px;
  bottom: 150px;
  background:yellow; color:blue; padding:10px;text-align:center }

#footer {
  position:absolute;
  top: 550px;
  bottom: 0px;
  left: 0px;
  width: 1200px;
  background:blue;color:yellow; padding:10px; text-align:center;}

</style>

</head>

<body>
  <div id="container">
  <!--<div id="wrapper">-->
    <div id="header">
               #Header
    </div>
     <div id="navigation">
        #Nav

                                                        11
Begin with PHP 1                                                                                    IOPROG

    </div>
    <div id="content">
               #Content
    </div>
    <div id="footer">
        #Footer
    </div>
  </div>

</body>
</html>



The output of BlueYellow.html in a web browser is




We can call this file BlueYello.php. But this time the web browser must communicate (via the URL) with a web
server (web hotel) that is running the PHP environment.

We could also use a specific .php-file, for example One_column_layout.php, with the content

<?php

include_once "BlueYellow.html";

?>
and sent this to web servers (web hotels) URL in the web browser. The output will be the same.

The include_once() or include() statement includes and evaluates the specified file during the execution of the
PHP script. This statement will be used in a common way int the following chapters.




                                                       12
Begin with PHP 1                                                                                          IOPROG


PHP Core Essentials

Variables
In PHP, all variable names begin with a dollar sign ($). The $ is followed by an alphabetic character or an
underscore, and optionally followed by a sequence of alphanumeric characters and underscores. There is no limit on
the length of a variable. Variable names in PHP are case-sensitive. Here are some examples:

$i
$counter
$firstName
$_TEMP


In PHP, unlike in many other languages, you do not have to explicitly declare variables. PHP automatically declares
a variable the first time a value is assigned to it. PHP variables are untyped; you can assign a value of any type to a
variable.

Dynamic Variables
Sometimes it is useful to set and use variables dynamically. Normally, you assign a variable like this:
$var = "hello";
Now let's say you want a variable whose name is the value of the $var variable. You can do that like this:
$$var = "World";
PHP parses $$var by first dereferencing the innermost variable, meaning that $var becomes "hello". The expression
that is left is then $"hello", which is just $hello. In other words, we have just created a new variable named hello
and assigned it the value "World". You can nest dynamic variables to an infinite level in PHP, although once you get
beyond two levels, it can be very confusing for someone who is trying to read your code.
There is a special syntax for using dynamic variables inside quoted strings in PHP:
echo "Hello ${$var}";

Data Types

PHP provides four (scalar) primitive data types: integers, floating point numbers, boolean and strings. In addition,
there are two compound data types: arrays and objects. There are also two special types: resource and NULL.


Integers
Integers are whole numbers. The range of integers in PHP is equivalent to the range of the long data type in C. On
32-bit platforms, integer values can range from -2,147,483,648 to +2,147,483,647. PHP automatically converts
larger values to floating point numbers if you happen to overflow the range. An integer can be expressed in decimal
(base-10), hexadecimal (base-16), or octal (base-8). For example:

$decimal=16;
$hex=0x10;
$octal=020;


Floating Point Numbers
Floating point numbers represent decimal values. The range of floating point numbers in PHP is equivalent to the
range of the double type in C. On most platforms a double can range from 1.7E-308 to 1.7E+308. A double may be
expressed either as a regular number with a decimal point or in scientific notation. For example:

$var=0.017;
$var=17.0E-3

Note that PHP also has a set of functions known as the BC (binary calculator) functions. These functions can
manipulate arbitrary precision numbers. If you are dealing with very large numbers or numbers that require a high
degree of precision, you should use these functions.

Boolean
A boolean can be either TRUE or FALSE. To explicitly convert a value boolean use the (bool) or (boolean) casts.
However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator,
function or control structure requires a boolean argument.

When converting to Boolean the following values are considered FALSE:




                                                          13
Begin with PHP 1                                                                                             IOPROG


        the boolean FALSE itself
        the integer 0 (zero)
        the float 0.0 (zero)
        the empty string, and the string "0"
        an array with zero elements
        an object with zero member variables
        the special type NULL (including unset variables)

Every other value is considered TRUE. -1 is considered TRUE, like any other non-zero (whether negative or positive)
number!

Strings
A string is a sequence of characters. A string can be delimited by single quotes or double quotes:

'PHP is cool'
"Hello, World!"

Concatenation Operator

There is only one string operator in PHP.

The concatenation operator (.) is used to put two string values together. To concatenate two string variables
together, use the concatenation operator:

<?php
   $txt1="Hello World!";
   $txt2="What a nice day!";
   print $txt1 . " " . $txt2;
?>


The output of the code above will be: Hello World! What a nice day!

If we look at the code above you see that we used the concatenation operator two times. This is because we had to
insert a third string (a space character), to separate the two strings.

strlen() function

The strlen() function is used to return the length of a string.

<?php
   print    strlen("Hello world!");
?>


The output of the code above will be: 12

The length of a string is often used in loops or other functions, when it is important to know when the string ends.
(i.e. in a loop, we would want to stop the loop after the last character in the string).

strpos() function

The strpos() function is used to search for character within a string.


If a match is found, this function will return the position of the first match. If no match is found, it will return FALSE.

<?php
   print strpos("Hello world!","world");
?>

The output of the code above will be: 6

                                                            14
Begin with PHP 1                                                                                               IOPROG


The position of the string "world" in our string is position 6. The reason that it is 6 (and not 7), is that the first
position in the string is 0, and not 1.

ord()

Returns the ASCII value of the first character of a string (or indexed character in a string)

<?php
$kod = "IBM";

$i = 1;
echo ord($kod[$i]);
?>

Output: 66


chr()

$kod = "IBM";

$i = 1;

echo chr(ord($kod[$i])+1);


Output: C


Double-quoted strings are subject to variable substitution and escape sequence handling, while single quotes are
not. For example:

$a="World";
print "Hello\t$a\n";

This displays "Hello" followed by a tab and then "World" followed by a newline. In other words, variable
substitution is performed on the variable $a and the escape sequences are converted to their corresponding
characters. Contrast that with:

print 'Hello\t$a\n';

In this case, the output is exactly "Hello\t$a\n". There is no variable substitution or handling of escape
sequences.

The following table shows the escape sequences understood by PHP:

Escape Sequence Meaning
\n                 Newline
\t                 Tab
\r                 Carriage return
\\                 Backslash
\$                 Dollar sign




                                                            15
Begin with PHP 1                                                                                        IOPROG


Arrays
An array is a compound data type that can contain, indexed either numerically or with strings values or multiple
data values. For example, an array of strings can be written like this:

$var[0]="Hello";
$var[1]="World";

Note that when you assign array elements like this, you do not have to use consecutive numbers to index the
elements.
As a shortcut, PHP allows you to add an element onto the end of an array without specifying an index. For example:

$var[] ="Test";

PHP picks the next logical numerical index. In this case, the "Test" element is given the index 2 in our $var array:
if the array has non-consecutive elements, PHP selects the index value that is one greater than the current highest
index value. This auto-indexing feature is most useful when dealing with multiple-choice

HTML <SELECT> form

elements, as we'll see in a later example.
Although we have called strings a primitive data type, it is actually possible to treat a string as a compound data
type, where each character in the string can be accessed separately. In other words, you can think of a string as an
array of characters, where the first character is at index 0. Thus, you can pick the third character out of a string
with:

$string[2]


Numerical Arrays
In a numeric array the array elements are stored with a numeric index/key.

The index can be automatically assigned, starting with 0 (zero):

$employee = array(”Nisse Hult”, ”Kalle Kula”, ”Hasse Hacker”);


The index can also be manually assigned:
$employee[0]=”Nisse Hult”;
$employee[1]=”Kalle Kula”;
$employee[2]=”Hasse Hacker”;

All datatypes can be used as array element/member values:

$gravity=array(9.85, 9.80, 9.81, 9.88,9.79);

$gravity[0]=9.85;
$gravity[1]=9.80;
$gravity[2]=9.81;
$gravity[3]=9.88;
$gravity[4]=9.79;

PHP has an excellent print_r() function that outputs human-readable information about a variable and it is
especially useful for quickly debugging or viewing array contents.


The output of the $employee array in a web browser is:

Array ( [0] => Nisse Hult [1] => Kalle Kula [2] => Hasse Hacker )

The output of the $gravity array in a web browser is:

Array ( [0] => 9.85 [1] => 9.8 [2] => 9.81 [3] => 9.88 [4] => 9.79 )

The above array information displays the key/value pairs of the array clearly.

The $gravity array can also be assigned as


                                                         16
Begin with PHP 1                                                                                          IOPROG

$gravity=array(0=>9.85, 1=>9.80, 2=>9.81, 3=>9.88, 4=>9.79);

Associative Arrays
Arrays can also be indexed/keyed using strings; these kinds of arrays are called associative arrays :

$employee['VD']="Nisse Hult";
$employee['Ekonomichef']="Kalle Kula";
$employee["Expert"]="Hasse Hacker";

The output of the $employee array in a web browser is:

Array ( [VD] => Nisse Hult [Ekonomichef] => Kalle Kula [Expert] => Hasse Hacker )


$gravity['Stockholm']=9.85;
$gravity['Göteborg']=9.80;
$gravity['Malmö']=9.81;
$gravity["Kiruna"]=9.88;
$gravity["Abisko"]=9.79;

The output of the $gravity array in a web browser is:

Array ( [Stockholm] => 9.85 [Göteborg] => 9.8 [Malmö] => 9.81 [Kiruna] => 9.88 [Abisko] => 9.79 )


count(), sizeof() , strlen()

PHP provides two methods of counting the members in an array: count() and sizeof().

The sizeof() function is an alias of the count() function. This means it is exactly the same in every way, except
its name. The choice of which one you use is yours, do you want to "count" the members in an array, or want to
know the "sizeof" the array.

The statement echo count($gravity); gives the value 5.

The statement print sizeof($gravity); gives the value 3.
PHP provides several ways to traverse an array: for, while, foreach, iterators

This will be discussed later on in connection to the chapter Control Structures, see Example PHP 6.


Objects
An object is a compound data type that can contain any number of variables and functions. Starting with PHP 5,
the object model was rewritten to allow for better performance and more features. This was a major change from
PHP 4. PHP 5 has a full object model. Among the features in PHP 5 are the inclusions of visibility, abstract and final
classes and methods. Here's a simple example:

class Test
{
   var $str = "Hello World";
   function init($str)
   {
      $this->str = $str;
   }
}

$class = new Test;
print $class->str;
$class->init("Hello");
print $class->str;

This code creates a Test object using the new operator. Then it sets a variable called str within the object. In
object-speak, a variable in an object is known as a property of that object. The test object also defines a function,
known as a method, called init(). This method uses the special-purpose $this variable to change the value of the
str property within that object.




                                                          17
Begin with PHP 1                                                                                          IOPROG


Boolean Values
Every value in PHP has a boolean truth value (true or false) associated with it. This value is typically used in
control structures, like if/else and for. The boolean value associated with a data value is determined as follows:
For an integer or floating point value, the boolean value is false if the value is 0; otherwise the boolean value
is true.
For a string value, the boolean value is false if the string is empty; otherwise the boolean value is true.
For an array, the boolean value is false if the array has no elements; otherwise the boolean value is true.
For an object, the boolean value is false if the object has no defined variables or functions; otherwise the
boolean value is true.
For an undefined object (a variable that has not been defined at all), the boolean value is false.
PHP has two built-in keywords, true and false, where true represents the integer value 1 and false represents
the empty string.

Type Casting
Variables in PHP do not need to be explicitly typed. PHP sets the type when a variable is first used in a script. You
can explicitly specify a type using C-style casting. For example:

$var = (int) "123abc";

Without the (int) in this example, PHP creates a string variable. With the explicit cast, however, we have created
an integer variable with a value of 123. The following table shows the available cast operators in PHP:

Operators               Function
(int), (integer)        Cast to an integer
(real), (double), (float) Cast to a floating point number
(string)                Cast to a string
(array)                 Cast to an array
(object)                Cast to an object

Although they are not usually needed, PHP does provide the following built-in functions to check variable types in
your program: gettype( ), is_long( ), is_double( ), is_string( ), is_array( ), and is_object( ).


Expressions
An expression is the basic building block of the language. Anything with a value can be thought of as an expression.
Examples include:
5
5+5
$a
$a==5
sqrt(9)

By combining many of these basic expressions, you can build larger and more complex expressions.
Note that the echo statement we've used in numerous examples cannot be part of a complex expression because
it does not have a return value. The print statement, on the other hand, can be used as part of complex
expression, as it does have a return value. In all other respects, echo and print are identical--they output data.

Operators
Expressions are combined and manipulated using operators. The following table shows the operators available in
PHP, along with their precedence (P) and associativity (A). The following table lists the operators from highest to
lowest precedence. These operators should be familiar to you if you have any C, Java, or Perl experience.

Operators                                   P   A
!, ~, ++, --, @, (the casting operators)    16 Right
*, /, %                                     15 Left
+, - .                                      14 Left
<<, >>                                      13 Left
<, <=, >=, >                                12 Non-associative
==, !=                                      11 Non-associative


                                                            18
Begin with PHP 1                                                                                         IOPROG


&                                         10 Left
^                                         9    Left
|                                         8    Left
&&                                        7    Left
||                                        6    Left
? : (conditional operator)                5    Left
=, +=, -=, *=, /=, %=, ^=, .=, &=, |= 4        Left
And                                       3    Left
Xor                                       2    Left
Or                                        1    Left


Control Structures
The control structures in PHP are very similar to those used by the C language. Control structures are used to
control the logical flow through a PHP script. PHP's control structures have two syntaxes that can be used
interchangeably. The first form uses C-style curly braces to enclose statement blocks, while the second style uses a
more verbose syntax that includes explicit ending statements. The first style is preferable when the control
structure is completely within a PHP code block. The second style is useful when the construct spans a large section
of intermixed code and HTML. The two styles are completely interchangeable, however, so it is really a matter of
personal preference which one you use.

if
The if statement is a standard conditional found in most languages. Here are the two syntaxes for the if
statement:


if(expr)                if(expr):
{                          statements
   statements           elseif(expr):
}                           statements
elseif(expr)            else:
{                           statements
   statements           endif;
}
else
{
   statements
}

The if statement causes particular code to be executed if the expression it acts on is true. With the first form, you
can omit the braces if you only need to execute a single statement.
switch
The switch statement can be used in place of a lengthy if statement. Here are the two syntaxes for switch:

switch(expr)                 switch(expr):
{                              case expr:
   case expr:                     statments
     statements                   break;
     break;                    default:
   default:                       statements
     statements                   break;
     break;                    endswitch;
}

The expression for each case statement is compared against the switch expression and, if they match, the code
following that particular case is executed. The break keyword signals the end of a particular case; it may be
omitted, which causes control to flow into the next case. If none of the case expressions match the switch
expression, the default case is executed.




                                                         19
Begin with PHP 1                                                                                       IOPROG


Example PHP 3

Finding the weekday (0 – 6) and weekday name (Sunday – Saturday) of a certain date.

<html>
<body>

<?php
   //Zeller's formula
   //Julius Christian Johannes Zeller (24 June 1822, Mühlhausen am Neckar – 31 May 1899,
   //Cannstatt) was a German mathematician.
   //http://en.wikipedia.org/wiki/Calculating_the_day_of_the_week


   $yy = 11;
   $mm = 2;
   $dd = 7;

   if ($mm < 3) {$yy--; $mm += 12;}
   $yy += 2000;
   $sum = 1 + $dd + (2*$mm) + (3*($mm+1))/5 + $yy + ($yy/4) - ($yy/100) + ($yy/400);
   $sum %= 7;

   switch ($sum)
   {
      case 0:
         print "Sunday";
         break;
      case 1:
         print "Monday";
         break;
      case 2:
         print "Tuesday";
         break;
      case 3:
         print "Wednesday";
         break;
      case 4:
         print "Thursday";
         break;
      case 5:
         print "Friday";
         break;
      case 6:
         print "Saturday";
         break;
      default:
         print "Invalid day";
   }
   ?>

</body>
</html>


while
The while statement is a looping construct that repeatedly executes some code while a particular expression is
true:

while(expr)               while(expr):
{                            statements
   statements             endwhile;
}

The while expression is checked before the start of each iteration. If the expression evaluates to true, the code
within the loop is executed. If the expression evaluates to false, however, execution skips to the code immediately
following the while loop. Note that you can omit the curly braces with the first form of the while statement if you
only need to execute a single statement.



                                                        20
Begin with PHP 1                                                                                          IOPROG


It is possible to break out of a running loop at any time using the break keyword. This stops the current loop and, if
control is within a nested set of loops, the next outer loop continues. It is also possible to break out of many levels
of nested loops by passing a numerical argument to the break statement (break n) that specifies the number of
nested loops it should break out of. You can skip the rest of a given loop and go onto the next iteration by using the
continue keyword. With continue n, you can skip the current iterations of the n innermost loops.

Example PHP 4
A table converting Celsius degrees to Fahrenheit degress.

<?php
   print "<table border=\"1\" align=\"center\">";
   print "<tr><th>Celsius</th>";
   print "<th>Fahenheit</th></tr>";
   while ( $tempC <= 100 )
   {
      print "<tr><td>";
      print $tempC;
      print "</td><td>";
      print (9.0/5.0)*$tempC + 32;
      print "</td></tr>";
      $tempC = $tempC + 10;
   }
   print "</table>";
?>

The output is:




do/while
The do/while statement is similar to the while statement, except that the conditional expression is checked at the
end of each iteration instead of before it:

do
{
   statements
} while(expr);

Note that due to the order of the parts of this statement, there is only one valid syntax. If you only need to execute
a single statement, you can omit the curly braces from the syntax. The break and continue statements work with
this statement in the same way that they do with the while statement.

for
A for loop is a more complex looping construct than the simple while loop:

for(start_expr; cond_expr; iter_expr)
{
   statements
}

for(start_expr; cond_expr; iter_expr):
   statements
endfor;




                                                          21
Begin with PHP 1                                                                                         IOPROG


A for loop takes three expressions. The first is the start expression; it is evaluated once when the loop begins. This
is generally used for initializing a loop counter. The second expression is a conditional expression that controls the
iteration of the loop. This expression is checked prior to each iteration. The third expression, the iterative
expression, is evaluated at the end of each iteration and is typically used to increment the loop counter. With the
first form of the for statement, you can omit the braces if you only need to execute a single statement.
The break and continue statements work with a for loop like they do with a while loop, except that continue
causes the iterative expression to be evaluated before the loop conditional expression is checked.


Example PHP 5
Here is the same table as in Example PHP 3, now executed with a for-loop.

<?php
   print "<table border=\"1\" align=\"center\">";
   print "<tr><th>Celsius</th>";
   print "<th>Fahenheit</th></tr>";
   for ($tempC = 10; $tempC <= 100; $tempC += 10)
   {
      print "<tr><td>";
      print $tempC;
      print "</td><td>";
      print (9.0/5.0)*$tempC + 32;
      print "</td></tr>";
      $tempC = $tempC + 10;
   }
   print "</table>";
?>

The output is the same as in Example PHP 3 above.

Example PHP 6

$gravity=array(9.85, 9.80, 9.81, 9.88,9.79);

<?php
//$size = sizeof($gravity);
$size = strlen($gravity);
for( $i=0; $i<$size; $i++ )
{
   echo $gravity[$i].'<br />';
}
?>

<?php
$size = sizeof( $gravity );
$i = 0;
while( $i < $size )
{
  echo $gravity[$i].'<br />';
  $i++;
}
?>

<?php
$i=0;
do
{
  echo $gravity[$i].'<br />';
  $i++;
} while($i <= sizeof($gravity));
?>

<?php
foreach( $gravity as $g )
{
  echo $g.'<br />';
}
?>



                                                         22
Begin with PHP 1                                                                                         IOPROG


In a web browser:

9.85
9.8
9.81
9.88
9.79
<?php
$employee[0]="Nisse Hult";
$employee[1]="Kalle Kula";
$employee[2]="Hasse Hacker"

$size = sizeof( $employee );
for( $i=0; $i<$size; $i++ )
{
   echo $employee[$i].'<br />';
}
?>

<?php
$size = sizeof( $employee );
$i = 0;
while( $i < $size )
{
  echo $employee[$i].'<br />';
  $i++;
}
?>

<?php
$i=0;
do
{
  echo $employee[$i].'<br />';
  $i++;
} while($i <= sizeof($employee));
?>

<?php
$employee['VD']="Nisse Hult";
$employee['Ekonomichef']="Kalle Kula";
$employee["Expert"]="Hasse Hacker";

// $employee = array("VD"=>"Nisse Hult", 'Ekonomichef'=>'Kalle kula', "Expert"=>"Hasse Hacker");

foreach( $employee as $empl )
{
   echo $empl.'<br />';
}
?>

In a web browser:

Nisse Hult
Kalle Kula
Hasse Hacker

Up to this point the arrays that have been accessed have echo'ed or prnted the value. The array key or index has
only be used as an identifier for the value. Quite often, when traversing an array, you will need to access the array
key itself, along with the value. These key=>value pairs are most common when accessing database results. A
database result set is an array of key=> pairs with the database table column name as the key. This means the
array is an associative array.


<?php
$age;
$age["Nisse"]     =   "28";
$age["Kalle"]     =   "16";
$age["Allan"]     =   "35";
$age["Ture"]      =   "46";
$age["Martha"]    =   "34";

                                                         23
Begin with PHP 1                                                                                          IOPROG


foreach( $age as $key => $value)
{
   print "Name: $key, Age: $value <br />";
}
?>

The output is:

Name:   Nisse, Age: 28
Name:   Kalle, Age: 16
Name:   Allan, Age: 35
Name:   Ture, Age: 46
Name:   Martha, Age: 34


list() - Returns the assigned array

In fact, you can use a mix of numerical and string indices with a single array. That is because internally PHP treats
all arrays as hash tables and the hash, or index, can be whatever you want.
All arrays in PHP can be traversed safely with the following mechanism:

while(list($key,$value)= each($array))
{
   echo "array[$key]=$value<br>\n";
}

This is the most common way to loop through each element of an array, whether it is a linear or an associative
array. PHP provides a number of array manipulation functions.

<?php
$gravity['Stockholm']=9.85;
$gravity['Göteborg']=9.80;
$gravity['Malmö']=9.81;
$gravity["Kiruna"]=9.88;
$gravity["Abisko"]=9.79;

while(list($key,$value) = each($gravity))
{
   echo "gravity[$key]=$value<br>\n";
}
?>

The output is:

gravity[Stockholm]=9.85
gravity[Göteborg]=9.8
gravity[Malmö]=9.81
gravity[Kiruna]=9.88
gravity[Abisko]=9.79

<?php
$employee['VD']="Nisse Hult";
$employee['Ekonomichef']="Kalle Kula";
$employee["Expert"]="Hasse Hacker";

while(list($key,$value) = each($employee))
{
   echo "employee[$key]=$value<br>\n";
}
?>

The output is:

employee[VD]=Nisse Hult
employee[Ekonomichef]=Kalle Kula
employee[Expert]=Hasse Hacker




                                                          24
Begin with PHP 1                                                                                      IOPROG


Built-in sorting an Array


PHP provides many built-in different ways of sorting arrays. Array can be sorted by key or by value. The order can
be natural of reverse or even case sensitive.


The PHP sort() function will sort an array by case.

<?php
$age["Nisse"]    =   "28";
$age["Kalle"]    =   "16";
$age["Allan"]    =   "35";
$age["Ture"]     =   "46";
$age["Martha"]   =   "34";

sort( $age );

foreach( $age as $key=>$a )
{
  echo $key.' - '.$a.'<br />';
}

?>

The output in a web browser:

0   -   16
1   -   28
2   -   34
3   -   35
4   -   46

Not so good! The associated key has been changed to a numeric key! Use the asort() function instead!

The output in a web browser:

Kalle - 16
Nisse - 28
Martha - 34
Allan - 35
Ture - 46


Sort by key – Reverse sort
PHP also allows you to sort the array by its index, instead of by the value. The function for this is ksort().
Arrays may be sorted in reverse order by key or by value. The reverse sorting compliments to the above sort() and
ksort() functions are rsort() and krsort().

<?php
ksort($age);

foreach($age as $key=>$a )
{
  echo $key.' - '.$a.'<br />';
}
?>

The output in a web browser:

Allan - 35
Kalle - 16
Martha - 34
Nisse - 28
Ture - 46




                                                        25
Begin with PHP 1                                                                                      IOPROG


Add an Element To an Array

A new array member, or multiple members, may be added, or "pushed" onto the end of the array. The function for
this is array_push().This new additions to the array have begun numerical indexes.
There exists a second method creating an array member. By directly specifying the new array value.
<?php

$age["Nisse"]    =   "28";
$age["Kalle"]    =   "16";
$age["Allan"]    =   "35";
$age["Ture"]     =   "46";
$age["Martha"]   =   "34";

$age['Hasse'] = '39';
$age['Sven'] = '62';

foreach( $age as $key=>$a )
{
  echo $key.' - '.$a.'<br />';
}

?>

The output in a web browser

Nisse - 28
Kalle - 16
Allan - 35
Ture - 46
Martha - 34
Hasse - 39
Sven - 62


Delete an Array Element


Deleting an array element is using the function unset().

<?php
unset($age["Ture"]);
?>


PHP provides a method to "pop" the last member of the array off the stack. The array_pop() function has the
single

task of this and cannot be used to delete other array members, only the last one.

Multi Dimension Arrays

A multi-dimensional array is an array of arrays. This means each value of an array can be another array. An array
key cannot be an array. An array may contain a mixture of string values and array values.

<?php
$families = array
(
  "Nisse Hult"=>array
  (
    "Hugo",
    "Karl",
    "Anna"
  ),
  "Ture Turen"=>array
  (
    "Sven"
  ),


                                                        26
Begin with PHP 1                                                         IOPROG

  "Kalle Anka"=>array
  (
    "Knatte",
    "Fnatte",
    "Tjatte"
  )
);

print_r($families);
?>
The output is:

Array (
   [Nisse Hult] => Array ( [0] => Hugo [1] => Karl [2] => Anna )
   [Ture Turen] => Array ( [0] => Sven )
   [Kalle Anka] => Array ( [0] => Knatte [1] => Fnatte [2] => Tjatte )
)




                                               27
Begin with PHP 1                                                                                         IOPROG


Functions
A powerful feature of PHP (as in all programming languages) comes from its functions. A function is a named
sequence of code statements that can optionally accept parameters and return a value. A function call is an
expression that has a value; its value is the returned value from the function. Functions are written mainly because
of reusability.(Write once and use forever). Functions are easy to manage, simple to read.


Built-in Functions
PHP provides a large number (more than 700) of internal functions. For a complete reference and examples of the
built-in functions, visit the link //. . . . .

User-defined Function.
PHP also supports user-definable functions. To define a function, use the function keyword.
Syntax:

function functionName()
{
   //Code to be executed;
   //return value/variable; //Optional return statement
}


PHP function guidelines:


        Give the function a name that reflects what the function does
        The function name can start with a letter or underscore (not a number)

function getArea($r)
{
   $area = $r*$r*pi();
   //$area = $r*$r*M_PI;
   return $area;
}

When you define a function, you need to be careful what name you give it. In particular, you need to make sure
that the name does not conflict with any of the internal PHP functions. If you do use a function name that conflicts
with an internal function, you get the following error:
Fatal error: Can't redeclare already declared function in filename on line N
After you define a function, you call it by passing in the appropriate arguments.

Example Function 1
<?php

     function getArea($r)
     {
        $area = $r*$r*pi();
        //$area = $r*$r*M_PI;
        return $area;
     }

     $r1 = 1.1;
     $area1; $area2;

     //Use HTML tag <br /> for outputing of newline on the browser
     $area1 = getArea($r1);
     print "Area1 = " . $area1 . "<br />";

     $area2 = getArea(2.2);
     print "Area2 = " . $area2 . "<br />";

     print "Area3 = " . getArea(3.3);
?>


The output is:

Area1 = 3.8013271108437

                                                         28
Begin with PHP 1                                                                                             IOPROG

Area2 = 15.205308443375
Area3 = 34.211943997593

You can also create functions with optional parameters. To do so, you set a default value for each optional
parameter in the definition, using C++ style. For example, here's how to make all the parameters to the
getArea() function optional:

function getArea($r = 5.5)
{
   $area = $r*$r*pi();
   //$area = $r*$r*M_PI;
   return $area;
}


Call the function:

print "Area with optional parameter value= " . getArea() . "<br />";

The output is:

Area with optional parameter value = 95.033177771091


Variable Scope
The scope of a variable refers to where in a program the variable is available. If a variable is defined in the main
part of a PHP script (i.e., not inside a function or a class), it is in the global scope. Note that global variables are
only available during the current request. The only way to make variables in one page available to subsequent
requests to another page is to pass them to that page via cookies, GET method data, or PUT method data. To
access a global variable from inside a function, you need to use the global keyword. For example:

function test()
{
   global $var;
   echo $var;
}
$var="Hello World";
test();

The $GLOBALS array is an alternative mechanism for accessing variables in the global scope. This is an associative
array of all the variables currently defined in the global scope:

function test()
{
   echo $GLOBALS["var"];
}
$var="Hello World";
test();

Every function has its own scope. When you create a variable inside of a function, that variable has local scope. In
other words, it is only available within the function. In addition, if there is a global variable with the same name as
a variable within a function, any changes to the function variable do not affect the value of the global variable.
When you call a function, the arguments you pass to the function (if any) are defined as variables within the
function, using the parameter names as variable names. Just as with variables created within a function, these
passed arguments are only available within the scope of the function.

Passing Arguments
There are two ways you can pass arguments to a function: by value and by reference. To pass an argument by
value, you pass in any valid expression. That expression is evaluated and the value is assigned to the corresponding
parameter defined within the function. Any changes you make to the parameter within the function have no effect
on the argument passed to the function. For example:

function triple($x)
{
   $x=$x*3;
   return $x;
}
$var=10;

                                                            29
Begin with PHP 1                                                                                          IOPROG

$triplevar=triple($var);

In this case, $var evaluates to 10 when triple() is called, so $x is set to 10 inside the function. When $x is tripled,
that change does not affect the value of $var outside the function.
In contrast, when you pass an argument by reference, changes to the parameter within the function do affect the
value of the argument outside the scope of the function. That's because when you pass an argument by reference,
you must pass a variable to the function. Now the parameter in the function refers directly to the value of the
variable, meaning that any changes within the function are also visible outside the function. For example:

function triple($x)
{
   $x=$x*3;
   return $x;
}
$var=10;
triple(&$var);

The & that precedes $var in the call to triple() causes the argument to be passed by reference, so the end result
is that $var ends up with a value of 30.


Example Function 2
Call by value. A copy of the variables are passed as parameters. The original values are not effected.

<?php
   function add($n1, $n2)
   {
      $sum = $n1 + $n2;
      return $sum;
   }

     print " Addition = " .addthem(123,321);
?>

Example Function 3
Call by reference. Address of variables are passed as parameters, hence original value may be changed.

<?php
   function swap(&$n1, &$n2)
   {
      $temp=$n1;
      $n1=$n2;
      $n2=$temp;
   }

     $a=11;
     $b=33;
     print "Before swap : a= ".$a ." and b = $b<br/>";
     swap($a,$b);
     print"After swap : a= ".$a ." and b = $b<br/>";
?>


Example Function 4
Make a function for coding a string by replacing the characters with a character with an ASCII-code some units
smaller or larger and send it back as a reference parameter.

<?php

function kryptering(&$str)
{
  $size = strlen($str);
  for ($i=0; $i < $size; $i++)
  {
    $char = $str[$i];
    $iChar = ord($char) - 1;
    $cCoded = chr($iChar);
    echo $cCoded;
  }
}

                                                          30
Begin with PHP 1                                                                                            IOPROG

$kod = "IBM";

kryptering($kod);
?>
The output is:
HAL



Static Variables
PHP supports declaring local function variables as static. A static variable retains its value between function calls,
but is still accessible only from within the function it is declared in. Static variables can be initialized and this
initialization only takes place the first time the static declaration is executed. Static variables are often used as
counters, as in this example:

function hitcount()
{
   static $count = 0;

    if ($count == 0)
    {
       print "This is the first time this page";
       print " has been accessed";
    }
    else
    {
       print "This page has been accessed $count";
       print " times";
    }
    $count++;
}

Web-Related Variables
PHP automatically creates global variables for all the data it receives in an HTTP request. This can include GET data,
POST data, cookie data, and environment variables. Say you have an HTML form that looks as follows:

<FORM ACTION="test.php" METHOD="POST">
<INPUT TYPE=text NAME=var>
</FORM>

When the form is submitted to the test.php file, the $var variable within that file is set to whatever the user
entered in the text field.

A variable can also be set in a URL like this:

http://your.server/test.php3?var=Hello+World

When the request for this URL is processed, the $var variable is set for the test.php page.
Any environment variables present in your web server's configuration are also made available, along with any CGI-
style variables your web server might set. The actual set of variables varies between different web servers. The
best way to get a list of these variables is to use PHP's special information tag. Put the following code in a page and
load the page in your browser:

<? phpinfo() ?>

You should see a page with quite a bit of information about PHP and the machine it is running on. There is a table
that describes each of the extensions currently enabled in PHP. Another table shows the current values of all the
various configuration directives from your php.ini file. Following those two tables are more tables showing the
regular environment variables, the special PHP internal variables, and the special environment variables that your
web server has added. Finally, the HTTP request and response headers for the current request are shown.
Sometimes it is convenient to create a generic form handler, where you don't necessarily know all the form element
names. To support this, PHP provides GET, POST, and cookie associative arrays that contain all of the data passed to
the page using the different techniques. These arrays are named $HTTP_GET_DATA, $HTTP_POST_DATA,
$HTTP_COOKIE_DATA, respectively. For example, here's another way to access the value of the text field in our form:

echo $HTTP_POST_VARS["var"];




                                                           31
Begin with PHP 1                                                                                         IOPROG


PHP sets global variables in a particular order. By default, global variables are set first from GET data, then from
POST data, and then finally from cookie data. This means that if you have a form with a field named var that uses
the GET method and a cookie with a var value, there is just one global variable named $var that has the value of
the cookie data. Of course, you can still get at the GET data through the $HTTP_GET_DATA array. The default order
can be defined with the gpc_order directive in the php.ini file.



Predefined Variables

PHP provides a large number of predefined variables to all scripts. The variables represent everything from external
variables to built-in environment variables, last error messages to last retrieved headers. Navigate to the link
http://www.php.net/manual/en/reserved.variables.php


        Superglobals — Superglobals are built-in variables that are always available in all scopes
        $GLOBALS — References all variables available in global scope
        $_SERVER — Server and execution environment information
        $_GET — HTTP GET variables
        $_POST — HTTP POST variables
        $_FILES — HTTP File Upload variables
        $_REQUEST — HTTP Request variables
        $_SESSION — Session variables
        $_ENV — Environment variables
        $_COOKIE — HTTP Cookies
        $php_errormsg — The previous error message
        $HTTP_RAW_POST_DATA — Raw POST data
        $http_response_header — HTTP response headers
        $argc — The number of arguments passed to script
        $argv — Array of arguments passed to script


Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a
script. There is no need to do global $variable; to access them within functions or methods. These superglobal
variables are:


        $GLOBALS
        $_SERVER
        $_GET
        $_POST
        $_FILES
        $_COOKIE
        $_SESSION
        $_REQUEST
        $_ENV




Example Function 4
$_SERVER is an associative array (as all of the predefined global variables) containing information such as headers,
paths, and script locations. The entries in this array are created by the web server .
Here is a simple page that prints out the browser string and the IP address of the HTTP request with the associative
index HTTP_USER_AGENT and REMOTE_ADDR.

<HTML><HEAD><TITLE>PHP Example Function 4</TITLE></HEAD>
<BODY>
You are using
<?php
   print $_SERVER['HTTP_USER_AGENT'];
?>

                                                         32
Begin with PHP 1                                                                                   IOPROG

<BR>
and coming from
<?php
   print $_SERVER['REMOTE_ADDR'];
?>
</BODY></HTML>

The output is:

You are using Mozilla/5.0 (Windows; U; Windows NT 6.1; sv-SE; rv:1.9.2.13) Gecko/20101203
Firefox/3.6.13 and coming from 127.0.0.1


Magic Functions/Methods
The function names __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep,
__wakeup, __toString, __invoke, __set_state and __clone are magical in PHP classes. You cannot have functions
with these names in any of your classes unless you want the magic functionality associated with them.
PHP reserves all function names starting with __ as magical. It is recommended that you do not use
function names with __ in PHP unless you want some documented magic functionality.




                                                      33
Begin with PHP 1                                                                                          IOPROG


Using PHP from Command line
The PHP environment can be used directly from the command line in the operating system like all other programs.
After setting the environment variable to the location of the CLI (Command Line Interface) program, php.exe in
Windows, the PHP command line options can be shown.
From a command line shell, Windows Command Prompt or Cygwin Shell, you can give the command php –h to get
all the PHP command line options

bash-3.2$ php -h
Usage: php [options]     [-f] <file> [--] [args...]
       php [options]     -r <code> [--] [args...]
       php [options]     [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
       php [options]     [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
       php [options]     -- [args...]
       php [options]     -a

  -a                 Run interactively
  -c   <path>|<file> Look for php.ini file in this directory
  -n                 No php.ini file will be used
  -d   foo[=bar]     Define INI entry foo with value 'bar'
  -e                 Generate extended information for debugger/profiler
  -f   <file>        Parse and execute <file>.
  -h                 This help
  -i                 PHP information
  -l                 Syntax check only (lint)
  -m                 Show compiled in modules
  -r   <code>        Run PHP <code> without using script tags <?..?>
  -B   <begin_code> Run PHP <begin_code> before processing input lines
  -R   <code>        Run PHP <code> for every input line
  -F   <file>        Parse and execute <file> for every input line
  -E   <end_code>    Run PHP <end_code> after processing all input lines
  -H                 Hide any passed arguments from external tools.
  -s                 Output HTML syntax highlighted source.
  -v                 Version number
  -w                 Output source with stripped comments and whitespace.
  -z   <file>        Load Zend extension <file>.

  args...              Arguments passed to script. Use -- args when first argument
                       starts with - or script is read from stdin

  --ini                Show configuration file names

  --rf   <name>        Show   information about   function <name>.
  --rc   <name>        Show   information about   class <name>.
  --re   <name>        Show   information about   extension <name>.
  --ri   <name>        Show   configuration for   extension <name>.

bash-3.2$

The command php –v gives the PHP version.

bash-3.2$ php -v
PHP 5.3.5 (cli) (built: Jan 6 2011 17:54:09)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
bash-3.2$


One of the first nice things the programmer discovers is a powerful interactive shell where you can try in little time
some line of code, and see the result printed on the standard output. Unfortunately PHP does not have support for
such a nice feature. There is the command line option -a, but it's very basic, and not that useful. Also what makes
php -a not so useful is the fact that PHP is a language for web applications: often the program output is html code,
so, doesn't it make sense that a PHP shell will run on the web?.
Unfortunately php -a needs readline functionality which isn’t available on Windows or Mac OS X. (No, of course
readline is available, but you have to compile PHP yourself to use it.)

The readline functions implement an interface to the GNU Readline library. These are functions that provide editable
command lines. An example being the way Bash allows you to use the arrow keys to insert characters or scroll
through command history. Because of the interactive nature of this library, it will be of little use for writing Web



                                                          34
Begin with PHP 1                                                                                        IOPROG


applications, but may be useful when writing scripts used from a command line. Note: This extension is not
available on Windows platforms.

There are a couple of “an interactive command line shell for PHP” on the freeware market.


Stream In, Stream Out

PHP's CLI interface have three "streams" with which you can interact.

php://stdin (read)
php://stdout (write)
php://stderr (write)


With the PHP CLI binary, these three streams are automatically available, identified with the constants STDIN,
STDOUT and STDERR respectively.


Example PHP Commandline 1
//StremOut.php
//Run with: php StreamOut.php
<?php
   $i = 0;
   while ( $i < 10 )
   {
      // Write some output
      fwrite(STDOUT, $i."\n");
      sleep(1);
      $i++;
   }
?>


Example PHP Commandline 2

To be able to read input from the script's user, you can use STDIN combined with fgets(), fread(), fscanf() or
fgetc(). For example:

//StreamIn.php
//Run with: php StreamIn.php
<?php
   fwrite(STDOUT, "Please enter your name\n");

     // Read the input
     $name = fgets(STDIN);

     fwrite(STDOUT, "Hello $name");

     // Exit correctly
     exit(0);
?>



Example Commandline 3

STDIN can also be used in a menu.

//CommandlineMenu.php
//Run with: php CommandlineMenu.php
<?php
fwrite(STDOUT, "Give color(enter the letter and press return)\n");




                                                         35
Begin with PHP 1                                               IOPROG

// An array of choice to color
$colors = array
(
   'R'=>'Red',
   'G'=>'Green',
   'B'=>'Blue',
);

// Display the choices
foreach ( $colors as $choice => $color )
{
   fwrite(STDOUT, "\t$choice: $color\n");
}

fwrite(STDOUT, "q: Quit\n");


// Loop until they enter 'q' for Quit
do
{
   // A character from STDIN, ignoring whitespace characters
   do
   {
       $selection = fgetc(STDIN);
   } while ( trim($selection) == '' );

   if ( array_key_exists($selection,$colors) )
   {
       fwrite(STDOUT, "You picked {$colors[$selection]}\n");
   }

} while ( $selection != 'q' );

exit(0);
?>

The output is like:

bash-3.2$ php CommandlineMenu.php
//CommandlineMenu.php
//Run with: php CommandlineMenu.php
Give color (enter the letter and press return)
R: Red
G: Green
B: Blue
q: Quit
R
You picked Red
G
You picked Green
B
You picked Blue
q
bash-3.2$




                                                 36
Begin with PHP 1                                                                                        IOPROG


Input to web browser - PHP Forms and User Input
When we want to have user input PHP needs to have an HTML form gather information from a website's visitor and
then use PHP to do process that information.
In the end of this document there is a chapter called “Common concepts about HTML Forms” discussing the
common tags for HTML Forms

Creating the XHTML/HTML code for the form

A form begins and ends with a <form> tag. The form tag surrounds all the inputs as well as gives instructions about
how and where to submit the form. As an example, let's start creating a form in a file named myform.php.


<form action="MyForm.php" method="post">
  <!-- form fields and attributes -->
</form>


The "action" attribute specifies what page to submit the form to. Many times, the action will be the same page as
the form.

The "method" attribute indicates how the form is submitted. There are two methods: "get" and "post". Most of the
time, forms will use the "post" method. More on get and post .

The ”name” attribute names the element so that it may be referred to from style sheets or scripts. Note. This
attribute has been included for backwards compatibility. Applications should use the id attribute to identify
elements.

The ”submit” attribute: when a form is submitted to a PHP script, the information from that form is automatically
made available to the script.

Add some input text to the form. Add a text field that asks for your favorite car and a submit button to submit the
form.


<form action="MyForm.php" method="post">
  Which is your favorite car?
  <input type="text" name="formCar" maxlength="50">
  <input type="submit" name="formSubmit" value="Submit">
</form>


Invoke this filename in the addressfield in a web browser with the URL to a web server and the response back is:




Nothing happens when the Submit button is pressed!



Using a common file for both the PHP logic block and the HTML content/form block

One of the predefined/global variables we have mentioned earlier is $_SERVER. This variable is an associative
array and it stores information about your server and execution environment information.

$_SERVER[] Variable
$_SERVER['PHP_SELF'] array element points out the filename of the currently executing script. For example, if you
use the file <www address>/index.php, the $_SERVER['PHP_SELF'] variable would be /index.php. This is
relative to the document root. This is useful to referring HTML forms and other element.




                                                         37
Begin with PHP 1                                                                                         IOPROG


<form> </form> tag
In the <form> </form> tag the action attribute specifies where to send the form-data when a form is submitted,
e.g. to the file UserInput.php.

The method attribute in the <form> </form> tag specifies how to send the form-data. There are two ways the
browser client can send information to the web server. The POST method transfers information via HTTP headers.
The information is encoded as described in case of GET method and put into a header called QUERY_STRING. The
GET method sends the encoded user information appended to the page request. The page and the encoded
information are separated by the ? character.

<html>
<body>

   <form action="UserInput.php" method="post">
   </form>

</body>
</html>


If you use and output the PHP variable/array element $_SERVER['PHP_SELF'] in the action attribute

<form action="<?php print $_SERVER[PHP_SELF]; ?>" method=”post”>
</form>

you can include the code in the PHP file as a PHP block in the same file.

<input type=”. . . . . “ name=”. . . . .” /> tag
In the <input type="text" name=”element name”/> tag, the type=”text” attribute and value defines a one-line
input field that a user can enter text into. The name attribute specifies a name for an input element/variable. More
discussion about the type attribute is found in the chapter “Common concepts about HTML Form” in the end of
this document.

The <input type="submit" name=”submit” value=”Click”/> tag defines a submit button that sends form data to
a server. The name attribute specifies the element/variable name for the submit button and the value attribute
specifies the name/user activity for the button.

Functions boolean isset(), boolean empty(), void unset()

bool isset ( mixed var [, mixed var [, mixed ...]])
void unset ( mixed var [, mixed var [, mixed ...]])
bool empty ( mixed var)


There are three very basic functions that help you use variables, and these are isset(), empty(), and unset().
Isset() and empty() are almost opposites, but not quite - isset() will return true if a variable, passed in as its
only parameter, has been set in the script already, whereas empty(), which also takes a variable as its sole
parameter, will return true if the variable has a false value. This is not the same thing!

To illustrate the difference consider the variable $x being set to false - isset() would return true because $x is a
variable that has a value, and empty() would also return true because $x’s value is false. To check for "variable not
set", use the not operator !, as in if (!isset($x)). Unset() removes an existing variable entirely, so that
isset() will return false. That variable can be recreated later on in the script, however. Use unset() when you
want to delete a variable.


Controlling script execution

void exit ( [mixed status])
mixed eval ( [string code_string])
void die ( [mixed status])

Two simple functions give your scripts much more power: exit() and eval() - both are very easy. Exit() takes
just one optional parameter, and terminates execution of the script immediately. If you pass a parameter, this is


                                                         38
Begin with PHP 1                                                                                              IOPROG


used as the script exit code, and, if it is a string, is printed out. Note that the function die() is an alias of the
exit() function and works the same way. Eval() is another function that takes one string parameter, but it
executes that string as if it were PHP code.


Example Forms 1
Some time we have to check the existence of a variable before using it for our further processing. We can use the
boolean function isset() to evaluate that the submit element/variable has been set with the if statement


if (isset($_POST['submit'])) { . . . . .   )

If separate variable $submit has been assigned for the array variable $_POST[‘submit’], the isset() condition
can be written as if (isset($submit)) { . . . . . }


Example Forms 2
Here is the file UserInput.php that contains both the PHP logic block and the HTML content/form block. This
example just ask for the Name and Age for the user.

<html>
<body>

<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="post">
   Name: <input type="text" name="fName" />
   Age: <input type="text" name="age" />
   <input type="submit" name=”submit” value=”Click”/>
</form>

<?php
   if(isset($_POST['submit']))
   {
      print “This PHP block contains the PHP code in the same file as the HTML block”;
   }
?>

</body>
</html>


HTTP/HTML GET and POST methods

There are two ways the browser client can send information to the web server.


         The GET Method
         The POST Method



The $_POST Variable
The built-in $_POST associative array variable is used to collect values from a form sent with method="post".
Information sent from a form with the POST method is invisible to others and has no limits on the amount of
information to send.
Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the
post_max_size in the php.ini file).
When to use method="post"?
Information sent from a form with the POST method is invisible to others and has no limits on the amount of
information to send.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

The $_GET Variable
The built-in $_GET associative array variable is used to collect values from a form sent with method="get".
Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's
address bar) and has limits on the amount of information to send.
When to use method="get"?
When using method="get" in HTML forms, all variable names and values are displayed in the URL.
Note: This method should not be used when sending passwords or other sensitive information!


                                                            39
Begin with PHP 1                                                                                       IOPROG


However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in
some cases.
Note: The get method is not suitable for very large variable values. It should not be used with values exceeding
2000 characters.

The $_REQUEST Variable
The PHP built-in $_REQUEST associative array variable contains the contents of both $_GET, $_POST, and $_COOKIE.
The $_REQUEST function can be used to collect form data sent with both the GET and POST methods.



Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme,
name/value pairs are joined with equal signs and different pairs are separated by the ampersand.


name1=value1&name2=value2&name3=value3


Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced
with a hexadecimal values. After the information is encoded it is sent to the server.

The GET Method

The GET method sends the encoded user information appended to the page request. The page and the encoded
information are separated by the ? character.


http://www.test.com/index.htm?name1=value1&name2=value2


       The GET method produces a long string that appears in your server logs, in the browser's Location: box.
       The GET method is restricted to send upto 1024 characters only.
       Never use GET method if you have password or other sensitive information to be sent to the server.
       GET can't be used to send binary data, like images or word documents, to the server.
       The data sent by GET method can be accessed using QUERY_STRING environment variable.
       The PHP provides $_GET associative array to access all the sent information using GET method.


Example Forms 3
Try out following example by putting the source code in test.php script.
<?php
  if( $_GET["name"] || $_GET["age"] )
  {
     echo "Welcome ". $_GET['name']. "<br />";
     echo "You are ". $_GET['age']. " years old.";
     exit();
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="GET">
  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />
  <input type="submit" />
  </form>
</body>
</html>




                                                        40
Begin with PHP 1                                                                                    IOPROG


The POST Method

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET
method and put into a header called QUERY_STRING.


       The POST method does not have any restriction on data size to be sent.
       The POST method can be used to send ASCII as well as binary data.
       The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using
        Secure HTTP you can make sure that your information is secure.
       The PHP provides $_POST associative array to access all the sent information using GET method.


Example Forms 4
Try out following example by putting the source code in test.php script.


<?php
  if( $_POST["name"] || $_POST["age"] )
  {
     echo "Welcome ". $_POST['name']. "<br />";
     echo "You are ". $_POST['age']. " years old.";
     exit();
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="POST">

  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />

  <input type="submit" />
  </form>
</body>
</html>


The $_REQUEST variable

The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss
$_COOKIE variable when we will explain about cookies.

The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST
methods.


Example Forms 5
Try out following example by putting the source code in test.php script.


<?php
  if( $_POST["name"] || $_POST["age"] )
  {
     echo "Welcome ". $_POST['name']. "<br />";
     echo "You are ". $_POST['age']. " years old.";
     exit();
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="POST">

  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />

  <input type="submit" />
  </form>


                                                         41
Begin with PHP 1                                                                                         IOPROG


</body>
</html>


Example Forms 6
The built-in $_POST associative array variable is used to collect values from a form sent with method="post". This
example is a continuation of the last example Example Forms 4.

html>
<body>
<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="post">
   Name: <input type="text" name="fName" />
   Age: <input type="text" name="age" />
   <input type="submit" name=”submit” value=”Click”/>
</form>
</body>
</html>

We want to catch the "fName" and "age" inputs that we have specified in our HTML form. Using an associative array
we can get this information from the $_POST.
The proper way to get this information would be to create two new variables, $fname and $age and set them equal
to the values that have been "posted". This is done in the file PHP block in the UserInput.php file with both the
HTML and PHP block.

//UserInput.php
<?php
  if( $_POST["name"] || $_POST["age"] )
  {
     echo "Welcome ". $_POST['name']. "<br />";
     echo "You are ". $_POST['age']. " years old.";
     exit();
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="POST">

  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />

  <input type="submit" />
  </form>
</body>


</html>When a user fills out the form above and click on the submit button (or the Return key in the input
textfield), the form data is sent to the PHP block in the "UserInput.php" file. The file can now use the $_POST
function to collect form data (the names of the form fields will automatically be the keys in the $_POST array):


The output could be something like this:




Example Forms 7
The built-in $_GET associative array variable is used to collect values from a form sent with method="get".

//UserInput.php
<html>
<body>
<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="get">
   Name: <input type="text" name="fName" />
   Age: <input type="text" name="age" />
   <input type="submit" name="submit" value="Click"/>


                                                         42
Begin with PHP 1                                                                                       IOPROG

</form>
</body>
</html>

<?php
if(isset($_GET['submit']))
{
   $fName = $_GET['fName'];
   $age = $_GET['age'];

     print "Welcome " . $fName . " <br />";
     print "You are " . $age . " years old. <br />";
}
?>



The output could be something like this:




Using separate files for the PHP logic block and the HTML content/form block

Example Forms 8
The built-in $_POST associative array variable is used to collect values from a form sent with method="post".
The HTML content/form is now located in a separate file e.g. “UserInputForm.html”. In the <form> </form> tag
the action attribute now is specifies to where to send the form-data when the form is submitted, e.g. to the file
UserInputSeparate.php.

The file UserInputForm.html looks like this:

<html>
<body>
   <form action="UserInputSeparate.php" method="post">
      Name: <input type="text" name="fName" />
      Age: <input type="text" name="age" />
      <input type="submit" name=”submit” value=”Click”/>
   </form>
</body>
</html>

When a user fills out the form above and click on the submit button, the form data is sent to the PHP file, called
"UserInput.php". The file can now use the $_POST function to collect form data (the names of the form fields will
automatically be the keys in the $_POST array):

The file "UserInputSeparate.php" looks like this:

<?php
//if(isset($_POST['submit']))
//{
   $fName = $_POST['fName'];
   $age = $_POST['age'];

   print "Welcome " . $fName . " <br />";
   print "You are " . $age . " years old. <br />";
//}
?>


                                                        43
Begin with PHP 1                                                                                       IOPROG


The isset() condition is not needed in this case.

The output is the same as above:




Welcome Nisse Hult!
You are 38 years old.


Example Forms 9
The built-in $_GET associative array variable is used to collect values from a form sent with method="get".
The HTML content/form is now located in a separate file e.g. “UserInputForm.html”. In the <form> </form> tag
the action attribute now is specifies to where to send the form-data when the form is submitted, e.g. to the file
UserInputSeparate.php.
The file UserInputForm.html looks like this:

<html>
<body>
   <form action="UserInputSeparate.php" method="get">
      Name: <input type="text" name="fName" />
      Age: <input type="text" name="age" />
      <input type="submit" name=”submit” value=”Click”/>
   </form>
</body>
</html>


The "UserInputSeparate.php" file can now use the $_GET function to collect form data (the names of the form
fields will automatically be the keys in the $_GET array).

The file UserInputSeparate.php looks like this:

<?php
//if(isset($_GET['submit']))
//{
   $fName = $_GET['fName'];
   $age = $_GET['age'];

   print "Welcome " . $fName . " <br />";
   print "You are " . $age . " years old. <br />";
//}
?>

The isset() condition is not needed in this case.

When the user clicks the "Submit" button, the URL sent to the server could look something like this:
http://127.0.0.1:8888/UserInputSeparate.php?fName=Nisse&age=38&submit=Click


Output is the same as above:




                                                        44
Begin with PHP 1                                                                                        IOPROG




User input validation
User input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and
reduces the server load. You should consider server validation if the user input will be inserted into a database. A
good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The
user will then get the error messages on the same page as the form. This makes it easier to discover the error.

Example Forms 10
User input for function calls like getArea() in Example Function 1. Use a common file for both the PHP logic
block and the HTML content/form block, e.g. GetAreaInput.php.

<html>
<body>
<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="post">
   Radius: <input type="text" name="radius" />
   <input type="submit" name="submit" value="Get radius (Click or Return)"/>
</form>
</body>
</html

<?php
if(isset($_POST['submit']))
{
   //Added statement from Form input
   $radius = $_POST['radius'];

     function getArea($r = 5.5)
     {
        $area = $r*$r*pi();
        //$area = $r*$r*M_PI;
        return $area;
     }

     $r1 = 1.1;
     $area1; $area2;

     //Use HTML tag <br /> for outputing of newline on the browser
     print "<br />";

     $area1 = getArea($r1);
     print "Area1 = " . $area1 . "<br />";

     $area2 = getArea(2.2);
     print "Area2 = " . $area2 . "<br />";

     print "Area3 = " . getArea(3.3). "<br />";

     print "Area4 with otional parameter value = " . getArea(). "<br />";

     //Added statement from Form input
     print "Area5 from GetAreaInput Form = " . getArea($radius) . "<br />";
}
?>

The output is:



                                                         45
Begin with PHP 1                                                                                IOPROG




Area1 = 3.8013271108437
Area2 = 15.205308443375
Area3 = 34.211943997593
Area4 with otional parameter value = 95.033177771091
Area 5 from GetAreaInput Form = 307.90749597834


Example Forms 11
User input for function calls like getArea() in Example Function 1

Make the input from a separate HTML content/form in file “GetAreaInputForm.html” and a separate PHP logic
block file “GetAreaInputSeparate.php”.

<html>
<body>
<form action="GetAreaInputSeparate.php" method="post">
   Radius: <input type="text" name="radius" />
   <input type="submit" name=”submit” value="Get radius (Click or Return)"/>
</form>
</body>
</html

Make the call to the function getArea() in the file “getAreaInputSeparate.php”

<?php
//Added statement from Form input
$radius = $_POST['radius'];

function getArea($r = 5.5)
{
  $area = $r*$r*pi();
  //$area = $r*$r*M_PI;
  return $area;
}

$r1 = 1.1;
$area1; $area2;


//Use HTML tag <br /> for outputing of newline on the browser
$area1 = getArea($r1);
print "Area1 = " . $area1 . "<br />";

$area2 = getArea(2.2);
print "Area2 = " . $area2 . "<br />";

print "Area3 = " . getArea(3.3). "<br />";

print "Area4 with otional parameter value = " . getArea(). "<br />";

//Added statement from Form input
print "Area5 from GetAreaInputForm = " . getArea($radius) . "<br />";
?>




The output is



                                                        46
Begin with PHP 1                                                                                         IOPROG

Area1 = 3.8013271108437
Area2 = 15.205308443375
Area3 = 34.211943997593
Area4 with otional parameter value = 95.033177771091
Area 5 from GetAreaInput Form = 307.90749597834

Session

HTTP is a stateless protocol. This description recognizes the lack of association between any two HTTP requests.
Because the protocol does not provide any method that the client can use to identify itself, the server cannot
distinguish between clients.

While the stateless nature of HTTP has some important benefits—after all, maintaining state requires some
overhead—it presents a unique challenge to developers who need to create stateful web applications. With no way
to identify the client, it is impossible to determine whether the user is already logged in, has items in a shopping
cart, or needs to register.

Session is an extension of the HTTP protocol. Session support in PHP consists of a way to preserve certain data
across subsequent accesses. This enables you to build more customized applications and increase the appeal of
your web site. (Cookies is another solution of this state management mechanism. )


Starting a session (and removing a session)

boolean session_start ( void )

A session is a combination of a server-side file containing all the data you wish to store, and a client-side cookie
containing a reference to the server data. The file and the client-side cookie are created using the function
session_start() - it has no parameters, but informs the server that sessions are going to be used.
When you call session_start(), PHP will check to see whether the visitor sent a session cookie - if it did, PHP will
load the session data. Otherwise, PHP will create a new session file on the server, and send an ID back to the visitor
to associate the visitor with the new file. Because each visitor has their own data locked away in their unique
session file, you need to call session_start() before you try to read session variables - failing to do so will mean
that you simply will not have access to their data. Furthermore, as session_start() needs to send the reference
cookie to the user's computer, you need to have it before the body of your web page - even before any spaces.

Removing a specific value from a session is as simple as using the function unset(), just as you would for any
other variable.

boolean session_destroy(void) removes all session data stored on your hard disk, leaving you with a clean
slate.


Adding session data

All your session data is stored in the session superglobal array, $_SESSION, which means that each session variable
is one element in that array, combined with its value. Adding variables to this array is done in the same way as
adding variables to any array, with the added the bonus that session variables will still be there when your user
browses to another page.

To set a session variable, use syntax like this:
$_SESSION['randomNumber'] = rand(0, 99); // Store session data
Before you can add any variable to a session, you need to have already called the session_start() function.

Example Forms 12
This example contains a simple game NumberGuess that plays a guessing game with the user. The program will
choose a random number between 0 and 99 (or optional) and the user will try to guess it. The program tells the
user whether the guess is high or low or correct.

The action parameter to the tag in HTML should not reference the PHP function you want to run. Action should refer
to a page on the web server that will process the form input and return new HTML to the user. This can be the
same location as the PHP script that outputs the form, or some people prefer to make a separate PHP file to handle
actions.


                                                         47
Begin with PHP 1                                                                    IOPROG


The basic process is the same either way:
Generate HTML form to the user.
User fills in the form, clicks submit.
The form data is sent to the locations defined by action on the server.
The script validates the data and does something with it.
Usually a new HTML page is returned.

<?php
session_start();
if(isset($_POST['submit']))

{
     $numberIn = $_POST['numberIn'];

     $secretNumber = $_SESSION['randomNumber'];
     //print "Random number = ". $secretNumber . "Should not be exposed in a real
                                                game!"; //Retrieve data
     $_SESSION['trialNumber']++;

     printForm();
     numberGuess($numberIn, $secretNumber);
}
else
{
   print "Numberguess!";
   $_SESSION['randomNumber'] = rand(0, 99); // Store session data
   //print "Random number = ". $_SESSION['randomNumber']; //Retrieve data
   $_SESSION['trialNumber'] = 0; // Store session data

    printForm();
}

function printForm()
{
   print '<form name="UserInput" method="post" action="">
          Guess: <input type="text" name="numberIn" />
          <input type="submit" name="submit" value="Guess"/>
          </form>';
   //If using " " around the print statement, use \"
   //instead of " inside the print statement
}

function numberGuess($n, $sN)
{
   if ($n == $sN)
   {
      print "Congratulations! " . $_SESSION['trialNumber'] . " try/tries";
   }
   elseif ($n < $sN)
   {
      print "Try higher" . "<br />";
   }
   else
   {
      print "Try lower" . "<br />";
   }
}
?>


The output is like this:




And it can end up like this:




                                                         48
Begin with PHP 1                                                                                         IOPROG



Example Forms 13

This is the game Master Mind in a simplified textual version.
1) Implement a function secretDigits(&$f) that create a “secret” four-digit integer, $f[], with all digits different,
that is between 1023 and 9876. The parameter $f must be a reference parameter.

Use the function
  rand(0,9)
to generate random numbers between 0 and 9.

2) The player (user of the program) shall guess this four-digit number by getting the following help from the
program:
- every digit with correct value and correct place is notated with a C(orrect).
- every digit with correct value but on wrong place is notated with a D(igit).
Example:
Generated “secret” number:             3614
Player is answered:                    5318
Help from the program:                 -DC-

Implement a function guessDigits(&$g) for the guessed number $g[]. The parameter $g must be a reference
parameter.
Hints for this method are given separate!

3) Implement a function controlOfDigits($f, $g) that handles the player’s guess and print out helpmessages
according to the rules in 2).

4) The function play() is a proposal to a method that handles the guessing in the game. The global/session
variable counter is counting the number of tries the player needs.

 function play()
 {
   if(isset($_POST['submit']))
   {
       $_SESSION['counter']++;
       $fourDigits = $_SESSION['fourDigits'];

       $this->printForm();
       $guessedDigits = $_POST['numberIn'];

       echo '<br>';
       $this->controlOfDigits($fourDigits,$guessedDigits);
   }
   else
   {
     $_SESSION['counter'] = 0;

       $this->secretDigits($fourDigits);
       $_SESSION['fourDigits'] = $fourDigits;

       $this->printForm();
   }
 }
The form for input for the players guesses is handle of this function printForm()

function printForm()
{
   print '<form name="" method="post" action="">
          Guess: <input type="text" name="numberIn" />
          <input type="submit" name="submit" value="Guess"/>
          </form>';
}

Output:




                                                         49
Begin with PHP 1                                                                                    IOPROG




Example Forms 14

A common area of using array is in sorting application. This example generates random integer numbers in an
array, sorts the numbers with a Bubble sort algoritm and prints out the sorted array.

<?php
function bubbleSort(&$a, $n)
{
  for ($i=0; $i < $n-1; $i++)
    for ($j = $n -1; $j >= $i + 1; $j--)
      if ( $a[$j-1] > $a[$j])
      {
        $temp = $a[$j-1];
        $a[$j-1] = $a[$j];
        $a[$j] = $temp;
      }
}

function printNumbers($a, $n)
{
   for ($i=0; $i < $n; $i++)
   {
     echo $a[$i] . " ";
     if (($i % 9 ==0) && ($i>0))
       echo "<br>";
   }
}

function numberGenerator(&$a, $n)
{
  for ($i=0; $i < $n-1; $i++)
    $a[$i] = rand(0,999);
}


function printForm()
{
   print '<form name="UserInput" method="post" action="">
          Quantity: <input type="text" name="quantity" />
          <input type="submit" name="submit" value="Sort"/>
          </form>';
}

function getTimeInSeconds()
{
  $time = microtime();
  $time = explode(' ', $time);
  $time = $time[1] + $time[0];


                                                       50
Begin with PHP 1                                                                                     IOPROG

    return $time;
}

//$quantity = 1000;

printForm();
if(isset($_POST['submit']))
{
    $quantity = $_POST['quantity'];

     numberGenerator($numbers, $quantity);
     //echo "Before sorting: ". "<br>";
     //printNumbers($numbers, $quantity);

     $start = getTimeInSeconds();

     bubbleSort($numbers, $quantity);

     $finish = getTimeInSeconds();

     $result = round(($finish - $start), 1);
     echo 'Sorting time '.$result .' seconds.'."\n";

     //echo "After sorting: ". "<br>";
     //printNumbers($numbers, $quantity);
}
?>



The function uses the built-in function microtime() to measure the sorting time.
microtime() returns the current Unix timestamp with microseconds. This function is only available on operating
systems that support the gettimeofday() system call.


Output:




Example Forms 15
Built-in string functions.

The PHP built-in manual is available on the link

http://www.php.net/manual/en/index.php

http://www.php.net/manual/en/funcref.php

http://www.php.net/manual/en/refs.basic.text.php

http://www.php.net/manual/en/book.strings.php

Navigate to the link

http://www.php.net/manual/en/ref.strings.php

for PHP string functions. One of them is uwwords() which gives uppercase the   first character of each word in a
string
http://www.php.net/manual/en/function.ucwords.php




                                                       51
Begin with PHP 1                                                                                       IOPROG


Both the PHP-code and the html-code are in the same file: StringFunction.php

<?php
if(isset($_POST['t1']))
{
   $st=$_POST['t1'];
   echo "String in Proper Case:<b> ";
   echo (ucwords(strtolower($st)));
   echo "</b><br/>String $st has <b>". strlen( $st ) ."</b> characters<br/>";
   echo "String in Lower case <b>" . strtolower($st)."</b><br/>";
   echo "String in Upper case <b>" . strtoupper($st)."</b><br/>";
   echo "String Reversed <b>" . strrev($st)."</b><br/>";
}
?>

<html>
<body bgcolor='#cccfaa'>
<form name='StringFunction.php' method='post'>
   Enter any String:<input type='text' name='t1' />
   <input type='submit' value='String functions' />
</form>
</body>
</html>

strlen( $st ) : returns no. of characters in a String
strtolower( $st ) : returns lowercase String
strtoupper( $st ) : returns uppercase String
strrev( $st ) : returns reverse of a String




The output is:




Example Forms 16
Number of visits. Global variable $_COOKIE.
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer.
Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both
create and retrieve cookie values.

<?php
  if ( !(isset( $_COOKIE['numberOfVisits'] ) ) )
  {
      setcookie( "numberOfVisits",1, time()+3600);
      echo "<h2 style='font-family:verdana'>Welcome ! It's first visit</h2>";
  }
  else
  {
      setcookie( "numberOfVisits",++$_COOKIE['numberOfVisits'], time()+3600);

       echo      "<h2 style='font-family:verdana'>Welcome ! It's "
                  .$_COOKIE['numberOfVisits']." visit</h2>";
  }
?>




                                                        52
Begin with PHP 1                                                                  IOPROG


Example Form 17
<?php

// This is a simple script to calculate the difference between two dates
// and express it in years, months and days
//
// use as in: "my daughter is 4 years, 2 month and 17 days old" ... :-)
//
// Feel free to use this script for whatever you want
//
// configure the base date here
$base_day              = 1;           // no leading "0"
$base_mon              = 1;           // no leading "0"
$base_yr               = 2000;        // use 4 digit years!

// get the current date (today) -- change this if you need a fixed date
$current_day          = date ("j");
$current_mon          = date ("n");
$current_yr           = date ("Y");

// and now .... calculate the difference! :-)

// overflow is always caused by max days of $base_mon
// so we need to know how many days $base_mon had
$base_mon_max         = date ("t",mktime (0,0,0,$base_mon,$base_day,$base_yr));

// days left till the end of that month
$base_day_diff                = $base_mon_max - $base_day;

// month left till end of that year
// substract one to handle overflow correctly
$base_mon_diff                = 12 - $base_mon - 1;

// start on jan 1st of the next year
$start_day            = 1;
$start_mon            = 1;
$start_yr             = $base_yr + 1;

// difference to that 1st of jan
$day_diff      = ($current_day - $start_day) + 1;     // add today
$mon_diff      = ($current_mon - $start_mon) + 1;     // add current month
$yr_diff       = ($current_yr - $start_yr);

// and add the rest of $base_yr
$day_diff      = $day_diff + $base_day_diff;
$mon_diff      = $mon_diff + $base_mon_diff;

// handle overflow of days
if ($day_diff >= $base_mon_max)
{
       $day_diff = $day_diff - $base_mon_max;
       $mon_diff = $mon_diff + 1;
}

// handle overflow of years
if ($mon_diff >= 12)
{
       $mon_diff = $mon_diff - 12;
       $yr_diff = $yr_diff + 1;
}

// the results are here:

// $yr_diff    --> the years between the two dates
// $mon_diff   --> the month between the two dates
// $day_diff   --> the days between the two dates



// simple output of the results


                                                53
Begin with PHP 1                                                                                       IOPROG

print "The difference between <b>".$base_yr."-".$base_mon."-".$base_day."</b> ";
print "and <b>".$current_yr."-".$current_mon."-".$current_day."</b> is:";
print "<br><br>";

// this is just to make it look nicer
$years = "years";
$days = "days";
if ($yr_diff == "1") $years = "year";
if ($day_diff == "1") $days = "day";

// here we go
print $yr_diff." ".$years.", ";
print $mon_diff." month and ";
print $day_diff." ".$days;

?>


Example Form 18
The Form LanguageSelection.html

<html>
<body>
   <form action="LanguageChoic.php" method="POST">
   Name: <br>
   <input type="text" name="user">
   <br>
  Address: <br>
  <textarea name="address" rows="5" cols="40"></textarea>
  <br>
  Select languages: <br>
  <select name="languages[]" multiple >
  <option>C#</option>
  <option>Java</option>
  <option>PHP </option>
  <option>Erlang</option>
  </select>

  <input type="submit" value="Submit">
  </form>
</body>
</html>

The PHP-file LanguageChoice.php

<?php
if(isset($_POST['user']))
{
   print "Welcome ".$_POST['user']."<br>";
   print "Your address is:".nl2br($_POST['address'])."<br>";
   print "Your language choices are:<br>";

     foreach ($_POST['languages'] as $value)
     {
        print "$value<br>";
     }
     //print $str;
}
?>



Example Form 19

Intelligent Form Handling
Here is a slightly more complex example. We are going to create an HTML form that asks the user to enter a name
and select one or more interests from a selection box. We could do this in two files, where we separate the actual
form from the data handling code, but instead, this example shows how it can be done in a single file:



                                                        54
Begin with PHP 1                                                                                          IOPROG

<HTML><HEAD><TITLE>Form Example</TITLE></HEAD>
<BODY>
<H1>Form Example Core Essentials 2</h2>

<?php
   function show_form($first="", $last="", $interest="")
   {
      $options = array("Sports", "Business","Travel", "Shopping", "Computers");
      if(empty($interest)) $interest=array(-1);
?>

<FORM ACTION="form.php3" METHOD="POST">
First Name:
<INPUT TYPE=text NAME=first
       VALUE="<?echo $first?>">
<BR>
Last Name:
<INPUT TYPE=text NAME=last
       VALUE="<?echo $last?>">
<BR>
Interests:
<SELECT MULTIPLE NAME=interest[]>


<?php
   for($i=0, reset($interest); $i<count($options); $i++)
   {
      echo "<OPTION";
      if(current($interest)==$options[$i])
      {
         echo " SELECTED ";
         next($interest);
      }
      echo "> $options[$i]\n";
   }
?>

</SELECT><BR>
<INPUT TYPE=submit>
</FORM>
<?php }
   if(!isset($first))
   {
      show_form();
   }
   else
   {
      if(empty($first) || empty($last) || count($interest) == 0)
      {
         echo "You did not fill in all the ";
         echo "fields, please try again<P>\n";
         show_form($first,$last,$interests);
      }
      else
      {
         echo "Thank you, $first $last, you ";
         echo "selected ". join(" and ", $interest);
         echo " as your interests.<P>\n";
      }
   }
?>
</BODY>
</HTML>

There are a few things you should study carefully in this example. First, we have isolated the display of the actual
form to a PHP function called show_form(). This function is intelligent in that it can take the default value for each
of the form elements as an optional argument. If the user does not fill in all the form elements, we use this feature
to redisplay the form with whatever values the user has already entered. This means that the user only has to fill
the fields he missed, which is much better than asking the user to hit the Back button or forcing him to reenter all
the fields.


                                                          55
Begin with PHP 1                                                                                            IOPROG


Notice how the file switches back and forth between PHP code and HTML. Right in the middle of defining our
show_form() function, we switch back to HTML to avoid having numerous echo statements that just echo normal
HTML. Then, when we need a PHP variable, we switch back to PHP code temporarily just to print the variable.
We've given the multiple-choice <SELECT> element the name interest[]. The [] on the name tells PHP that the
data coming from this form element should be treated as an auto-indexed array. This means that PHP automatically
gives each element the next sequential index, starting with 0 (assuming the array is empty to begin with).
The final thing to note is the way we determine what to display. We check if $first is set. If it isn't, we know that
the user has not submitted the form yet, so we call show_form() without any arguments. This displays the empty
form. If $first is set, however, we check to make sure that the $first and $last text fields are not empty and
that the user has selected at least one interest.



Filehandling in common
Output from a PHP script is HTML that is sent to the browser. HTML is sent to the browser through standard output.
Input to a PHP script can (usually) be taken form a form input in a browser. Output and input from and to a PHP
script can also be various I/O streams, stdout, stdin, filedescriptor or filepointer, …
PHP is able to create, read and write files on the server system.

Open a file
Prepares file for use and associates a variable with the file for future reference
$file = fopen(filename, mode)

Modes                  Description
r                      Read only. Starts at the beginning of the file
r+                     Read/Write. Starts at the beginning of the file
w                      Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist
w+                     Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist
a                      Append. Opens and writes to the end of the file or creates a new file if it doesn't exist
a+                     Read/Append. Preserves file content by writing to the end of the file
x                      Write only. Creates a new file. Returns FALSE and an error if file already exists
x+                     Read/Write. Creates a new file. Returns FALSE and an error if file already exists


Note: If the fopen() function is unable to open the specified file, it returns 0 (false).


Use file_exists(filename) to determine whether file exists before trying to open it
Because fopen could fail, use it with die

$file = fopen (“test.dat”, “r”) or die (“Error –test.dat can’t be opened”);


Writing to a file
Writing to a file
$bytes= fwrite($file, $out_data);
fwrite returns the number of bytes it wrote


Reading from a file
Read one line from the file:
$line = fgets(file, #bytes)

Read one character at a time:
$ch = fgetc(file)

Control reading lines or characters with eof detection using feof(TRUE for eof; FALSE otherwise)
while(!feof($file))
{
  $ch = fgetc($file);
}




                                                           56
Begin with PHP 1                                                                                           IOPROG


Closing a file.
Use fclose(file) to close a file


Filehandling with formatted textfiles

There is a ”Comma Separated Values”, CSV text file format with separate functionality in PHP. This fileformat is
useful as file format for Microsoft Word and Excel. This is not covered in this document.

Instead the formatted flat textfile characteristics are discussed. This persistent storage is also connected to an array
usage for ”in-memory” storage.

The fprintf() function writes a formatted string to a specified output stream/file (like a file or database).

fprintf(file, format, arg1, arg2, arg++)

A file system pointer file is created created using fopen().


The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-
by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc.

The fprintf() function returns the length of the written string.


Possible format values:


        %% - Returns a percent sign
        %b - Binary number
        %c - The character according to the ASCII value
        %d - Signed decimal number
        %e - Scientific notation (e.g. 1.2e+2)
        %u - Unsigned decimal number
        %f - Floating-point number (local settings aware)
        %F - Floating-point number (not local settings aware)
        %o - Octal number
        %s - String
        %x - Hexadecimal number (lowercase letters)
        %X - Hexadecimal number (uppercase letters)

Additional format values. These are placed between the % and the letter (example %.2f):


        + (Forces both + and - in front of numbers. By default, only negative numbers are marked)
        ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier.
         Example: %'x20s (this uses "x" as padding)
        - (Left-justifies the variable value)
        [0-9] (Specifies the minimum width held of to the variable value)
        .[0-9] (Specifies the number of decimal digits or maximum string length)

Note: If multiple additional format values are used, they must be in the same order as above.

arg1 Required. The argument to be inserted at the first %-sign in the format string arg2 Optional. The argument to
be inserted at the second %-sign in the format string arg++ Optional. The argument to be inserted at the third,
fourth, etc. %-sign in the format string

The fscanf() function parses the input from an open file according to the specified format.

fscanf(file,format, var1, var2, var++)


                                                          57
Begin with PHP 1                                                                                       IOPROG


A file system pointer file is created using fopen().

The specified format is the same as described in documentation above.


File structure
A text file is a container which is divided into records/tupler/rows and fields/columns that holds information . For
example, an Customer file would contain the same basic details on each customer: number, name, title,
department and so on. Each detail, each chunk of information you need to store lives in a field/column1. When you
view a single customer record/row, you can display it in a textual print-out or a graphical form. Whenever you want
to view more that one record at a time, you do so in a table report, where fields appear as columns and each record
is a row.

Example FileHandling 1
In this example we use the common concept for textfiles like row and column. Give the textile the name
“Texfile.txt”.

To get the input data we use a common input form with two field input and a radio button.

This is the file Input_Form.php:

<?php

function printForm()
{
  print '<form action="WriteTextFile.php" method="post">
    Column 1:
    <input type="text" name="colName1" maxlength="25" />
    Column 2:
    <input type="text" name="colName2" maxlength="25" />
    Column 3:
    <input type="radio" name="colName3" value="ja"> Ja
    <input type="radio" name="colName3" value="nej">Nej<br><br>

     <input type="submit" name="formSubmit" value="Write to textfile" />

    </form>';
}

printForm();
?>

This is the file WritTextFile.php:

<?php
include "Input_Form.php";

$colName1 = $_POST['colName1'];
$colName2 = $_POST['colName2'];
$colName3 = $_POST["colName3"] == "" ? "colVal1" : $_POST["colName3"];

$file = fopen("TextFile.txt","a+");

fprintf($file, "%-25s%-25s%-25s\n", $colName1, $colName2, $colName3);

fclose($file);

?>


Running Input_Form.php gives the response on a web browser about “green” cars:




                                                        58
Begin with PHP 1                                                                                          IOPROG


The content in the file TextFile.txt can be like this:




This is the file ReadTextFile.php:

<?php

$file = fopen("TextFile.txt", "r+");

print "<table border=\"1\">";
print "<tr><th>Column 1</th> <th>Column 2</th>            <th>Column 3</th> </tr>";

while( $row=fscanf($file, "%25s%25s%25s\n") )
{
  list($col1, $col2, $col3) = $row;
  print "<tr> <td> $col1 </td> <td> $col2 </td>            <td> $col3 </td> </tr>";
}

print "</table>";

fclose($file);
?>


You can use a mix of numerical and string indices with a single array. That is because internally PHP treats all
arrays as hash tables and the hash, or index, can be whatever you want.
All arrays in PHP can be traversed safely with the following mechanism:

while(list($key,$value)= each($array))
{ }


Running ReadTextFile php gives the following uutput of the file TextFile.txt as a table.




                                                          59
Begin with PHP 1                                                                                      IOPROG


CRUD – Create, Read, Update, Delete Application

WikiPedia: In computer programming, create, read, update and delete (CRUD) are the four basic functions of
persistent storage. Sometimes CRUD is expanded with the words retrieve instead of read or destroy instead of
delete. It is also sometimes used to describe user interface conventions that facilitate viewing, searching, and
changing information; often using computer-based forms and reports.

The acronym CRUD refers to all of the major functions that are implemented in relational database applications
that are considered as complete application. Each letter in the acronym can map to a standard SQL statement:

Although a relational database provides a common persistent layer in software applications, numerous other
persistence layers exist. CRUD functionality can be implemented with an object database, an XML database, flat
text files, custom file formats, tape, or card, for example.


Here follows a PHP and flat text file description how to make a CRUD application. In the part Begin with PHP 4
there is a description of how to make a PHP and relational database (MySQL) CRUD application.



PHP and flat text file CRUD Application
File table

The file table can be compared to database tables structured in rows/tuples and columns/fields

        Column 1          Column 2          Column 3         ...

Row 1 Value               Value             Value            ...
Row 2 Value               Value             Value            ...
...   ...                 ...               ...

Table Person


        Name              Email address     Age

        Kalle Kula        kalle@kula.se     41
        Nisse Hult        nisse@hult.se     55
        ...               ...               ...

Table Order

        Artikel           Antal

        Laptop            9
        IPad              99
        ...               ...

Every row must be unique identified by one of the columns/fields as a (primary) key, normally a generated integer.
This will be more discussed in the PHP and Relational database (MySQL) description.


CRUD menu page

A menu page for the CRUD application can be made by the following XHTM/HTML – CSS code, CRUD_Menu.php.

<html>
<head>
<style type="text/css">

#container {
       position:absolute;
       left:0px;
       top:0px;
       width:1200px;
       height:1000px;
}

                                                        60
Begin with PHP 1                               IOPROG

#navigation {
  position:absolute;
  left:0px;
  top:0px;
  width:1200;
  height:49px;
  background-color:blue;
}

#home {
          position:absolute;
          left:100px;
          top:0px;
          width:150px;
          height:49px;
}

#create_crud {
       position:absolute;
       left:300px;
       top:0px;
       width:150px;
       height:49px;
}

#read_crud {
       position:absolute;
       left:500px;
       top:0px;
       width:150px;
       height:49px;
}

#update_crud {
       position:absolute;
       left:700px;
       top:0px;
       width:150px;
       height:49px;
}

#delete_crud {
        position:absolute;
       left:900px;
       top:0px;
       width:150px;
       height:49px;
}

#navigation a:link,
#navigation a:visited {
  color:yellow;
  text-decoration: none;
  font-size:30px;
  font-weight:bold;
  font-family:Verdana,
  Geneva, sans-serif;
}
#navigation a:hover {color: red ; }
#navigation a:active { color: yellow; }

</style>
</head>




                                          61
Begin with PHP 1                                                                  IOPROG

<body>

  <div id=container>
    <div id=navigation>
      <div id=home>
        <a href="Home.php">Home</a>
      </div>

       <div id=create_crud>
         <a href="./Create_File.php">Crud</a>
       </div>

      <div id=read_crud>
         <a href="./Read_File.php">cRud</a>
       </div>

       <div id=update_crud>
         <a href="./Update_Form.php">crUd</a>
       </div>

       <div id=delete_crud>
         <a href="./Delete_File.php">cruD</a>
       </div>

     </div>
  </div>
</body>
</html>

In a web browser this is displayed like




CRUD – Create

The CRUD Create alternative is noticed as the menu link Crud above.


The Create operation can be as simple as only creating an empty flat text file.

<?php
//Create_File.php
session_start();
if($_GET['formSubmit'] == "Submit")
{
  $filNamn = $_GET['filNamn'];
  $_SESSION['filNamn1'] = $filNamn;

  //print $_SESSION['filNamn1'];

  $file = fopen($_SESSION['filNamn1'], "a+");
  if (!$file)
  {
    print ("Could not create the file!");
    exit;
  }
  //fprintf($file, "%s\n", $filnamn);
  fclose($file);
  exit;
}
?>




                                                         62
Begin with PHP 1                                                                                 IOPROG

<html>
<body>

<form action="Create_File.php" method="get">
  <p> Ange filnamn<br>
  <input type="text" name="filNamn" maxlength="50" value="<?=$filNamn;?>" />
  </p>
  <input type="submit" name="formSubmit" value="Submit" />
</form>

</body>
</html>


To keep the filename during the whole CRUD session, the function session_start() and the $_SESSION[] are
used for the filename.

Click the Crud link in the menu.




The flat text file CRUD_File.txt is created.


CRUD - Update


The CRUD Update alternative is noticed as the menu link crUd above.
The structure of the file table is

Name      Email   Age

To update the file row you can use

fprintf($file, "%s\t%s\t%3d\n", $name, $email, $age);


<?php
//Update_Form.php

session_start();
if($_POST['formSubmit'] == "Submit")
{
       $errorMessage = "";

          if(empty($_POST['fname']))
          {
                  $errorMessage .= "<li>You forgot to enter a first name!</li>";
          }

         if(empty($_POST['lname']))
          {
                 $errorMessage .= "<li>You forgot to enter a last name!</li>";
          }

          if(empty($_POST['email']))
          {
                  $errorMessage .= "<li>You forgot to enter an email address!</li>";
          }

          if(empty($_POST['age']))
          {
                  $errorMessage .= "<li>You forgot to enter age!</li>";
          }

                                                      63
Begin with PHP 1                                                                                     IOPROG




         $fname = $_POST['fname'];
        $lname =$_POST['lname'];
         $email = $_POST['email'];
        $age = $_POST['age'];

        if(empty($errorMessage))
        {
                //$file = fopen("CRUD_File.txt","a+");
               $file = fopen($_SESSION['filNamn1'], "a+");
                fprintf($file, "%s\t%s\t%s\t%3d\n", $fname, $lname, $email, $age);
                fclose($file);
                exit;
        }
}
?>

<html>
<head>
  <title>My Form</title>
</head>

<body>
  <?php
  if(!empty($errorMessage))
  {
    echo("<p>There was an error with your form:</p>\n");
    echo("<ul>" . $errorMessage . "</ul>\n");
  }
  ?>

  <form action="Update_Form.php" method="post">
    <p> First Name:<br>
    <input type="text" name="fname" maxlength="50"          value="<?=$fname;?>" />
    </p>
    <p> Last Name:<br>
    <input type="text" name="lname" maxlength="50"          value="<?=$lname;?>" />
    </p>
    <p> Email:<br>
    <input type="text" name="email" maxlength="50"          value="<?=$email;?>" />
    </p>
    <p> Age:<br>
      <input type="text" name="age" maxlength="50"          value="<?=$age;?>" />
    </p>

    <input type="submit" name="formSubmit" value="Submit" />
  </form>
</body>
</html>

From the form the file Update_Form.php itself is called. The dialogue with the update form can be like this




                                                       64
Begin with PHP 1                                                                                         IOPROG


CRUD - Read


The CRUD Read alternative is noticed as the menu link cRud above.

To read a row from the file, the function/syntax construction list() is used.
list() is used to assign a list of variables in one operation as if they were an array.

To read the file until not end-of-file the condition
while( $row=fscanf($file, "%s\t%s\t%s\t%3d\n") )
can be used.


<?php
//Read_File.php

session_start();
$file = fopen($_SESSION['filNamn1'], "r+");

//printf('%s\t%s\t%s\t%3d','Col1', 'Col2', 'Col3');
//print "<br>";

print "<table border=\"1\">";
print "<tr><th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Age</th></tr>";

while( $row=fscanf($file, "%s\t%s\t%s\t%3d\n") )
{
  list($col1, $col2, $col3, $col4) = $row;
  //printf('%s\t%s\t%s\t%3d',$col1,$col2,$col3,$col4);
  //print "<br>";
  print "<tr> <td> $col1 </td> <td> $col2 </td> <td> $col3 </td> <td> $col4 </td> </tr>";
}

print "</table>";

fclose($file);
?>


The file Read_File.php includes a XHTML/HTML table structure to output the rows in the file.




CRUD - Delete

The CRUD Delete alternative is noticed as the menu link cruD above.
The row to be deleted is inputted in the form interface. The Delete_File .php is reading all rows from the origin file
and write the rows not to be deleted to a temporary file. This temporary file is then read and all rows are written
back to the origin file.

<?php
//Delete_File.php
session_start();

$file = fopen($_SESSION['filNamn1'], "r+");
$tempFile = fopen("tempFile.txt", "w+");

$fname = $_POST['fname'];

while( $row=fscanf($file, "%s\t%s\t%s\t%3d\n") )
{
  list($col1, $col2, $col3, $col4) = $row;

                                                           65
Begin with PHP 1                                                             IOPROG

    if ($col1 != $fname)
    {
      fprintf($tempFile, "%s\t%s\t%s\t%3d\n", $col1, $col2, $col3, $col4);
    }
}

fclose($file);
fclose($tempFile);

$file = fopen($_SESSION['filNamn1'], "w+");
$tempFile = fopen("tempFile.txt", "r+");;

while( $row=fscanf($tempFile, "%s\t%s\t%s\t%3d\n") )
{
  list($col1, $col2, $col3, $col4) = $row;
  fprintf($file, "%s\t%s\t%s\t%3d\n", $col1, $col2, $col3, $col4 );
}

fclose($file);
fclose($tempFile);

?>

<html>
<body>
  <form action="Delete_File.php" method="post">
    <p> Name (first name) for person to be deleted <br>
    <input type="text" name="fname" maxlength="50" value="<?=$fname;?>" />
    </p>

    <input type="submit" name="formSubmit" value="Submit" />
  </form>
</body>
</html>

The dialogue with the delete form can be like this




The origin file is now (use the menu cRud to read the file):




                                                         66
Begin with PHP 1                                                                                       IOPROG


Common Concepts about HTML Forms

HTML <form> Tag

A simple HTML form with two input fields and one submit button:

<form action=". . . . ." method=". . . . .">
  First name: <input type=". . . . ." name=". . . . . " /><br />
  Last name: <input type=". . . . ." name=". . . . . " /><br />
  <input type=". . . . ." value=". . . . ." />
</form>


Definition and Usage

The <form> tag is used to create an HTML form for user input.

A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can
also contain select menus, textarea, fieldset, legend, and label elements. Forms are used to pass data to a server.

Differences Between HTML and XHTML


In XHTML, the name attribute of the <form> tag is deprecated, and will be removed. Use the id attribute instead.

Required Attributes


DTD indicates in which HTML 4.01/XHTML 1.0 DTD the attribute is allowed. S=Strict, T=Transitional, and
F=Frameset.


Attribute           Value                   Description                                                       DTD
action              URL                     Specifies where to send the form-data when a form is submitted    STF


Optional Attributes


Attribute           Value                                          Description                                 DTD
                                                                   Specifies the types of files that can be
accept              MIME_type                                                                                  STF
                                                                   submitted through a file upload
                                                                   Specifies the character-sets the server can
accept-charset      charset                                                                                    STF
                                                                   handle for form-data
                    application/x-www-form-urlencoded
                                                                   Specifies how form-data should be
enctype             multipart/form-data                                                                       STF
                                                                   encoded before sending it to a server
                    text/plain
                    get
method                                                             Specifies how to send form-data            STF
                    post
name                name                                           Specifies the name for a form              TF
                    _blank
                    _self
target              _parent
                    _top
                    framename




                                                        67
Begin with PHP 1                                                                                               IOPROG


HTML <form> action Attribute

Definition and Usage

The required action attribute specifies where to send the form-data when a form is submitted.

Syntax

<form action="value">


Attribute Values


Value              Description
                   Where to send the form data.

                   Possible values:

URL
                            An absolute URL - points to another web site (like
                             action="http://www.example.com/example.htm")
                            A relative URL - points to a file within a web site (like action="example.htm")



HTML <form> method Attribute

Definition and Usage

The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action
attribute).

The form-data can be sent as URL variables (with method="get") or as HTTP post (with method="post").

Notes on the "get" method:


         This method appends the form-data to the URL in name/value pairs
         This method is useful for form submissions where a user want to bookmark the result
         There is a limit to how much data you can place in a URL (varies between browsers), therefore, you cannot
          be sure that all of the form-data will be correctly transferred
         Never use the "get" method to pass sensitive information! (password or other sensitive information will be
          visible in the browser's address bar)

Notes on the "post" method:


         This method sends the form-data as an HTTP post transaction
         Form submissions with the "post" method cannot be bookmarked
         The "post" method is more robust and secure than "get", and "post" does not have size limitations Syntax


Syntax

<form method="value">


Attribute Values


Value                      Description




                                                            68
Begin with PHP 1                                                                                        IOPROG


get                    Appends the form-data to the URL: URL?name=value&name=value

post                   Sends the form-data as an HTTP post transaction



HTML <form> name Attribute

Definition and Usage

The name attribute specifies the name of a form.

The name attribute of the form element provides a way to reference the form in a script.

Tip: In XHTML, the name attribute of the <form> tag is deprecated, and will be removed. Use the id attribute
instead.

Syntax

<form name="value">

Attribute Values


Value                  Description
name                   The name of a form



HTML <input> Tag

Definition and Usage


The <input> tag is used to select user information.

An input field can vary in many ways, depending on the type attribute. An input field can be a text field, a
checkbox, a password field, a radio button, a button, and more.

Differences Between HTML and XHTML

In HTML, the <input> tag has no end tag.
In XHTML, the <input> tag must be properly closed, like this <input />.

Optional Attributes

DTD indicates in which HTML 4.01/XHTML 1.0 DTD the attribute is allowed. S=Strict, T=Transitional, and
F=Frameset.


Attribute              Value                  Description                                                       DTD
                                              Specifies the types of files that can be submitted through a file
accept                 MIME_type                                                                                STF
                                              upload (only for type="file")
                       left
                       right                  Deprecated. Use styles instead.
align                  top                    Specifies the alignment of an image input (only for              TF
                       middle                 type="image")
                       bottom
                                              Specifies an alternate text for an image input (only for
alt                    text                                                                                  STF
                                              type="image")
checked                checked                Specifies that an input element should be preselected when the STF


                                                         69
Begin with PHP 1                                                                                          IOPROG


                                               page loads (for type="checkbox" or type="radio")
                                               Specifies that an input element should be disabled when the
disabled               disabled                                                                                   STF
                                               page loads
                                               Specifies the maximum length (in characters) of an input field
maxlength              number                                                                                     STF
                                               (for type="text" or type="password")
name                   name                    Specifies a name for an input element                              STF
                                               Specifies that an input field should be read-only (for
readonly               readonly                                                                                   STF
                                               type="text" or type="password")
size                   number                  Specifies the width of an input field                              STF
src                    URL                     Specifies the URL to an image to display as a submit button        STF



                       button
                       checkbox
                       file
                       hidden
                       image
type                                           Specifies the type of an input element                             STF
                       password
                       radio
                       reset
                       submit
                       text
value                  value                   Specifies the value of an input element                            STF


HTML <input> type Attribute

Syntax

<input type="value" />


Attribute Values


Value            Description
button           Defines a clickable button (mostly used with a JavaScript to activate a script)
checkbox         Defines a checkbox
file             Defines an input field and a "Browse..." button, for file uploads
hidden           Defines a hidden input field
image            Defines an image as a submit button
password         Defines a password field. The characters in this field are masked
radio            Defines a radio button
reset            Defines a reset button. A reset button resets all form fields to their initial values
submit           Defines a submit button. A submit button sends form data to a server
text             Defines a one-line input field that a user can enter text into. Default width is 20 characters



Text

<input type="text" /> defines a one-line input field that a user can enter text into.

Example

Email: <input type="text" name="email" /><br />
Pin: <input type="text" name="pin" />

<html>
<body>

<form action="form_action.asp" method="get">
  Email: <input type="text" name="email" /><br />


                                                          70
Begin with PHP 1                                                                                      IOPROG

  Pin: <input type="text" name="pin" maxlength="4" /><br />
  <input type="submit" value="Submit" />
</form>

<p>Click on the submit button, and the input will be sent to a page on the server called
"form_action.asp".</p>

</body>
</html>


Button

<input type="button" /> defines a clickable button, that does not do anything. The button type is most often used
to activate a JavaScript when a user clicks on the button.

Example

<input type="button" value="Click me" onclick="msg()" />

<html>
<head>
<script type="text/javascript">
function msg()
{
alert("Hello world!");
}
</script>
</head>
<body>

<form>
<input type="button" value="Click me" onclick="msg()" />
</form>

<p>The button above activates a JavaScript when it is clicked. To learn more about JavaScript,
please read our JavaScript tutorial.</p>

</body>
</html>


Checkbox

<input type="checkbox" /> defines a checkbox. Checkboxes let a user select one or more options of a limited
number of choices.

Example

<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car

<html>
<body>

<form action="form_action.asp" method="get">
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car<br />
<input type="checkbox" name="vehicle" value="Airplane" /> I have an airplane<br />
<input type="submit" value="Submit" />
</form>

<p>Click on the submit button, and the input will be sent to a page on the server called
"form_action.asp".</p>

</body>
</html>



                                                        71
Begin with PHP 1                                                                                           IOPROG


File

<input type="file" /> is used for file uploads.


Example

<input type="file" />

<html>
<body>

<form>
<input type="file" name="pic" accept="image/gif" />
</form>

<p><b>Note:</b> Because of security issues, this example will not allow you to upload files.</p>

</body>
</html>


Hidden

<input type="hidden" /> defines a hidden field. A hidden field is not visible for the user. Hidden fields often store a
default value, or have their value changed by a JavaScript.

Example

<input type="hidden" name="country" value="Norway" />

<html>
<body>

<form action="form_action.asp" method="get">
  Email: <input type="text" name="email" /><br />
  <input type="hidden" name="country" value="Norway" />
  <input type="submit" value="Submit" />
</form>

<p>Click on the submit button, and the input will be sent to a page on the server called
"form_action.asp".</p>

</body>
</html>

Image

<input type="image" /> defines an image as a submit button.


The src and alt attribute are required with <input type="image">.

Example

<input type="image" src="submit.gif" alt="Submit" />
<html>
<body>

<form action="form_action.asp" method="get">
  First name: <input type="text" name="fname" /><br />
  Last name: <input type="text" name="lname" /><br />
  <input type="image" src="submit.gif" alt="Submit" width="48" height="48" />
</form>

<p>Click on the image, and the input will be sent to a page on the server called
"form_action.asp".</p>


                                                          72
Begin with PHP 1                                                                                         IOPROG

<p><b>Note:</b> The image input type sends the X and Y coordinates of the click that activated
the image button as default.</p>

</body>
</html>


Password

<input type="password" /> defines a password field. The characters in a password field are masked (shown as
asterisks or circles).

Example

<input type="password" name="pwd" />

<html>
<body>

<form action="form_action.asp" method="get">
  Email: <input type="text" name="email" /><br />
  Password: <input type="password" name="pwd" maxlength="8" /><br />
  <input type="submit" value="Submit" />
</form>

<p>Click on the submit button, and the input will be sent to a page on the server called
"form_action.asp".</p>

</body>
</html>


Radio

<input type="radio" /> defines a radio button. Radio buttons let a user select only one of a limited number of
choices.

Example

<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female

<html>
<body>

<form action="form_action.asp" method="get">
  <input type="radio" name="sex" value="male" /> Male<br />
  <input type="radio" name="sex" value="female" /> Female<br />
  <input type="submit" value="Submit" />
</form>

<p>Click on the submit button, and the input will be sent to a page on the server called
"form_action.asp".</p>

</body>
</html>



Reset Button

<input type="reset" /> defines a reset button. A reset button resets all form fields to their initial values.


Tip: Use the reset button carefully! It can be annoying for users who accidentally activate the reset button.




                                                         73
Begin with PHP 1                                                                                         IOPROG


Example

<input type="reset" />

<html>
<body>

<form action="form_action.asp" method="get">
  Email: <input type="text" name="email" /><br />
  Pin: <input type="text" name="pin" maxlength="4" /><br />
  <input type="reset" value="Reset" />
  <input type="submit" value="Submit" />
</form>

<p>Click on the reset button to reset the form.</p>
<p>Click on the submit button, and the input will be sent to a page on the server called
"form_action.asp".</p>

</body>
</html>



Submit

<input type="submit" /> defines a submit button. A submit button is used to send form data to a server. The
data is sent to the page specified in the form's action attribute.

Example

<form action="form_action.asp" method="get">
Email: <input type="text" name="email" /><br />
<input type="submit" />
</form>


HTML <input> value Attribute

Definition and Usage

The value attribute specifies a value for an input element.

The value attribute is used differently for different types of input:


         For type="button", "reset", "submit" - defines the text on the button
         For type="text", "password", "hidden" - defines the initial (default) value of the input field
         For type="checkbox", "radio", "image" - defines the value associated with the input. This is the value sent
          to the form's action URL

Note: The value attribute is required with <input type="checkbox"> and <input type="radio">.

Note: The value attribute cannot be used with <input type="file">.

Syntax

<input value="value" />

Attribute Values


Value                   Description
value                   The value of an input element



                                                            74
Begin with PHP 1                                                                                        IOPROG


HTML <input> name Attribute

Definition and Usage

The name attribute specifies a name for an input element.

The name attribute is used to identify form data after it has been submitted to the server, or to reference form data
using JavaScript on the client side.

Note: Only form elements with a name attribute will have their values passed when submitting a form.

Syntax

<input name="value" />

Attribute Values


Value                  Description
name                   The name of an input element




                                                         75

								
To top