Post Reply  Post Thread 


PHP tutorial
Author Message
geneticthylon
Started Website


Posts: 23
Group: Newbie
Joined: Jul 2008
Status: Offline
Reputation: 0
Post: #1
PHP tutorial

What is PHP? PHP is a web programming language used to write dynamic webpages. In this tutorial you will learn basics of PHP. I will assume you already know a bit about programming language so I won't cover the whole thing.

======================================================

Lesson 1 : Opening & Ending PHP Tags

To open a block of PHP code in a page you can use one of these four sets of opening and closing tags



The first pair (<? and ?>) is called short tags. You should avoid using short tags in your application especially if it's meant to be distributed on other servers. This is because short tags are not always supported ( though I never seen any web host that don't support it ). Short tags are only available only explicitly enabled setting the short_open_tag value to On in the PHP configuration file php.ini.

So, for all PHP code in this website I will use the second pair, <?php and ?>.

Now, for the first example create a file named hello.php ( you can use NotePad or your favorite text editor ) and put it in your web servers root directory. If you use Apache the root directory is APACHE_INSTALL_DIR\htdocs, with APACHE_INSTALL_DIR is the directory where you install Apache. So if you install Apache on C:\Program Files\Apache Group\Apache2\htdocs then you put hello.php in C:\Program Files\Apache Group\Apache2\htdocs



The example above shows how to insert PHP code into an HTML file. It also shows the echo statement used to output a string. See that the echo statement ends with a semicolon. Every command in PHP must end with a semicolon. If you forget to use semicolon or use colon instead after a command you will get an error message like this

Parse error: parse error, unexpected ':', expecting ',' or ';' in c:\Apache\htdocs\examples\get.php on line 7

However in the hello.php example above omitting the semicolon won't cause an error. That's because the echo statement was immediately followed by a closing tag.

Lesson 2 : Using Comments


Comment is a part of your PHP code that will not be translated by the PHP engine. You can use it to write documentation of your PHP script describing what the code should do. A comment can span only for one line or span multiple line.

PHP support three kinds of comment tags

1. //
This is a one line comment
2. #
This is a Unix shell-style comment. It's also a one line comment
3. /* ..... */

Use this multi line comment if you need to.

07-29-2008 01:27 PM
Find all posts by this user Digg this Post! Add Post to del.icio.us Bookmark Post in Technorati Furl this Post! Add blinklist Add Mongolia Add Netscape Reddit! Stumble Quote this message in a reply
geneticthylon
Started Website


Posts: 23
Group: Newbie
Joined: Jul 2008
Status: Offline
Reputation: 0
Post: #2
RE: PHP tutorial

Lesson 3 : PHP Variables

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive, so $myvar is different from $myVar.

A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

Example :


Variable Scope

The scope of a variable is the context within which it is defined. Basically you can not access a variable which is defined in different scope.

The script below will not produce any output because the function Test() declares no $a variable. The echo statement looks for a local version of the $a variable, and it has not been assigned a value within this scope. Depending on error_reporting value in php.ini the script below will print nothing or issue an error message.



If you want your global variable (variable defined outside functions) to be available in function scope you need to use the$global keyword. The code example below shows how to use the $global keyword.



PHP Superglobals

Superglobals are variables that available anywhere in the program code. They are :

* $_SERVER
Variables set by the web server or otherwise directly related to the execution environment of the current script. One useful variable is $_SERVER['REMOTE_ADDR'] which you can use to know you website visitor's IP address



$_GET
Variables provided to the script via HTTP GET. You can supply GET variables into a PHP script by appending the script's URL like this : http://www.php-mysql-tutorial.com/../exa...iend=mysql
or set the a form method as method="get"



* Note that I put $_GET['name'] and $_GET['friend'] in curly brackets. It's necessary to use these curly brackets when you're trying to place the value of an array into a string.

You can also split the string like this :
echo "My name is " . {$_GET['name']} . "<br>"; but it is easier to put the curly brackets.
* $_POST
Variables provided to the script via HTTP POST. These comes from a form which set method="post"
* $_COOKIE
Variables provided to the script via HTTP cookies.
* $_FILES
Variables provided to the script via HTTP post file uploads. You can see the example in
Uploading files to MySql Database
* $_ENV
Variables provided to the script via the environment.
* $_REQUEST
Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and which therefore cannot be trusted. It's use the appropriate $_POST or $_GET from your script instead of using $_REQUEST so you will always know that a variable comes from POST or GET.
* $GLOBALS
Contains a reference to every variable which is currently available within the global scope of the script.

You usually won't need the last three superglobals in your script.

07-29-2008 01:47 PM
Find all posts by this user Digg this Post! Add Post to del.icio.us Bookmark Post in Technorati Furl this Post! Add blinklist Add Mongolia Add Netscape Reddit! Stumble Quote this message in a reply
geneticthylon
Started Website


Posts: 23
Group: Newbie
Joined: Jul 2008
Status: Offline
Reputation: 0
Post: #3
RE: PHP tutorial

Lesson 4 : Variable Types

PHP supports eight primitive types.

Four scalar types:

* boolean : expresses truth value, TRUE or FALSE. Any non zero values and non empty string are also counted as TRUE.
* integer : round numbers (-5, 0, 123, 555, ...)
* float : floating-point number or 'double' (0.9283838, 23.0, ...)
* string : "Hello World", 'PHP and MySQL, etc

Two compound types:

* array
* object

And finally two special types:

* resource ( one example is the return value of mysql_connect() function)
* NULL

In PHP an array can have numeric key, associative key or both. The value of an array can be of any type. To create an array use the array() language construct like this.



When working with arrays there is one function I often used. The print_r() function. Given an array this function will print the values in a format that shows keys and elements



Don't forget to print the preformatting tag <pre> and </pre> before and after calling print_r(). If you don't use them then you'll have to view the page source to see a result in correct format.

Type Juggling

In PHP you don't need to explicitly specify a type for variables. A variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.

Example :


Type Casting

To cast a variable write the name of the desired type in parentheses before the variable which is to be cast.



The casts allowed are:

* (int), (integer) - cast to integer
* (bool), (boolean) - cast to boolean
* (float), (double), (real) - cast to float
* (string) - cast to string
* (array) - cast to array
* (object) - cast to object

07-29-2008 02:08 PM
Find all posts by this user Digg this Post! Add Post to del.icio.us Bookmark Post in Technorati Furl this Post! Add blinklist Add Mongolia Add Netscape Reddit! Stumble Quote this message in a reply
geneticthylon
Started Website


Posts: 23
Group: Newbie
Joined: Jul 2008
Status: Offline
Reputation: 0
Post: #4
RE: PHP tutorial

Lesson 5 : Playing With Strings

Strings are probably what you will use most in your PHP script. From concatenating, looking for patterns, trim, chop etc. So I guess it's a good idea to take a better look at this creature. We will also take a peek at some string functions that you might find useful for everyday coding.

Creating a string

To declare a string in PHP you can use double quotes ( " ) or single quotes ( ' ). There are some differences you need to know about using these two.

If you're using double-quoted strings variables will be expanded ( processed ). Special characters such as line feed ( \n ) and carriage return ( \r ) are expanded too. However, with single-quoted strings none of those thing happen. Take a look at the example below to see what I mean.

Note that browsers don't print newline characters ( \r and \n ) so when you open string.php take a look at the source and you will see the effect of these newline characters.



String Concatenation

To concat two strings you need the dot ( . ) operator so in case you have a long string and for the sake of readability you have to cut it into two you can do it just like the example below.

Actually if you need to write a loong string and you want to write it to multiple lines you don't need concat the strings. You can do it just like the second example below where $quote2 is split into three lines.



String Functions
substr($string, $start, $end) : get a chunk of $string



str_repeat($string, $n) : repeat $string $n times

For example if you want to print a series of ten asteriks ( * ) you can do it with a for loop like this :



Or you can go the easy way and do it like this :



strrchr($string, $char) : find the last occurence of the character $char in $string

For example: you want to get the file extension from a file name. You can use this function in conjunction with substr()



What the above code do is get a chunk of $filename starting from the last dot in $filename then get the substring of it starting from the second character ( index 1 ).

To make things clearer suppose $filename is 'tutorial.php'. Using strrchr('tutorial.php', '.') yield '.php' and after substr('.php', 1) we get the file extension; 'php'

trim($string) : remove extra spaces at the beginning and end of $string



addslashes($string) : adding backslashes before characters that need to be quoted in $string

This function is usually used on form values before being used for database queries. You will see this function used a lot in this tutorial so there's no need to present an example here.

explode($separator, $string) : Split $string by $separator

This function is commonly used to extract values in a string which are separated by a a certain separator string. For example, suppose we have some information stored as comma separated values. To extract each values we ca do it like shown below



Now, $info is an array with three values :

Array
(
[0] => Uzumaki Naruto
[1] => 15
[2] => Konoha Village
)

We can further process this array like displaying them in a table, etc.

implode($string, $array) : Join the values of $array using $string

This one do the opposite than the previous function. For example to reverse back the $info array into a string we can do it like this :



Another example : Pretend we have an array containing some values and we want to print them in an ordered list. We can use the implode() like this :



The result of that code is like an ordered list just like shown below

1. Uchiha Sasuke
2. Haruno Sakura
3. Uzumaki Naruto
4. Kakashi

By the way, i did write the above php code to print that list instead of writing the list directly

number_format($number): display a number with grouped thousands

When displaying numbers it's usuallly more readable if the numbers is properly formatted like 1,234,567 instead of 1234567.

07-29-2008 03:27 PM
Find all posts by this user Digg this Post! Add Post to del.icio.us Bookmark Post in Technorati Furl this Post! Add blinklist Add Mongolia Add Netscape Reddit! Stumble Quote this message in a reply
geneticthylon
Started Website


Posts: 23
Group: Newbie
Joined: Jul 2008
Status: Offline
Reputation: 0
Post: #5
RE: PHP tutorial

Lesson 6 : Control Structures

The next examples will show you how to use control structures in PHP. I won't go through all just the ones that i will use in the code examples in this site. The control structures are

* if
* else
* while
* for

If Else

The if statement evaluates the truth value of it's argument. If the argument evaluate as TRUE the code following the if statement will be executed. And if the argument evaluate as FALSE and there is an else statement then the code following the else statement will be executed.



The strpos() function returns the numeric position of the first occurrence of it's second argument ('Opera') in the first argument ($agent). If the string 'Opera' is found inside $agent, the function returns the position of the string. Otherwise, it returns FALSE.

When you're using Internet Explorer 6.0 on Windows XP the value of $_SERVER['HTTP_USER_AGENT'] would be something like:

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

and if you're using Opera the value the value may look like this :

Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT 5.1) Opera 7.0 [en]

So if i you use Opera the strpos() function will return value would be 61. Since 61 !== false then the first if statement will be evaluated as true and the value of $agent will be set to the string 'Opera'.

Note that I use the !== to specify inequality instead of != The reason for this is because if the string is found in position 0 then the zero will be treated as FALSE, which is not the behaviour that I want.

While Loop

The while() statement is used to execute a piece of code repeatedly as long as the while expresssion evaluates as true. For example the code below will print the number one to nine.



You see that I make the code $number += 1; as bold. I did it simply to remind that even an experienced programmer can sometime forget that a loop will happily continue to run forever as long as the loop expression ( in this case $number < 10 ) evaluates as true. So when you're creating a loop please make sure you already put the code to make sure the loop will end in timely manner.

Break

The break statement is used to stop the execution of a loop. As an example the while loop below will stop when $number equals to 6.



You can stop the loop using the break statement. The break statement however will only stop the loop where it is declared. So if you have a cascading while loop and you put a break statement in the inner loop then only the inner loop execution that will be stopped.



If you run the example you will see that the outer loop, while ($floor <= 5), is executed five times and the inner loop only executed two times for each execution of the outer loop. This proof that the break statement only stop the execution of the inner loop where it's declared.

For

The for loop syntax in PHP is similar to C. For example to print 1 to 10 the for loop is like this



A more interesting function is to print this number in a table with alternating colors. Here is the code



This code display different row colors depending on the value of $i. If $i is not divisible by two it prints yellow otherwise it prints gray colored rows.

07-29-2008 03:43 PM
Find all posts by this user Digg this Post! Add Post to del.icio.us Bookmark Post in Technorati Furl this Post! Add blinklist Add Mongolia Add Netscape Reddit! Stumble Quote this message in a reply
geneticthylon
Started Website


Posts: 23
Group: Newbie
Joined: Jul 2008
Status: Offline
Reputation: 0
Post: #6
RE: PHP tutorial

Lesson 7 : Using Functions

Real world applications are usually much larger than the examples above. In has been proven that the best way to develop and maintain a large program is to construct it from smaller pieces (functions) each of which is more manageable than the original program.

A function may be defined using syntax such as the following:



Using Default Parameters

When calling a function you usually provide the same number of argument as in the declaration. Like in the function above you usually call it like this :

$result = addition(5, 10);

But you can actually call a function without providing all the arguments by using default parameters.



Function repeat() have two arguments $text and $num. The $num argument has a default value of 10. The first call to repeat() will print the text 15 times because the value of $num will be 15. But in the second call to repeat() the second parameter is omitted so repeat() will use the default $num value of 10 and so the text is printed ten times.

Returning Values

Applications are usually a sequence of functions. The result from one function is then passed to another function for processing and so on. Returning a value from a function is done by using the return statement.



You can return any type from a function. An integer, double, array, object, resource, etc.

Notice that in buildRows() I use the built in function implode(). It joins all elements of $array with the string '</td></tr><tr><td>' between each element. I also use the '.' (dot) operator to concat the strings.

You can also write buildRows() function like this.

07-29-2008 03:58 PM
Find all posts by this user Digg this Post! Add Post to del.icio.us Bookmark Post in Technorati Furl this Post! Add blinklist Add Mongolia Add Netscape Reddit! Stumble Quote this message in a reply
geneticthylon
Started Website


Posts: 23
Group: Newbie
Joined: Jul 2008
Status: Offline
Reputation: 0
Post: #7
RE: PHP tutorial

Lesson 8 : Using Form

Using forms in a web based application is very common. Most forms are used to gather information like in a signup form, survey / polling, guestbook, etc.

A form can have the method set as post or get. When using a form with method="post" you can use $_POST to access the form values. And when the form is using method="get" you can use $_GET to access the values. The $_REQUEST superglobal can be used to to access form values with method="post" and method="get" but it is recommended to use $_POST or $_GET instead so you will know from what method did the values come from.

Here is an example of HTML form :



The form above use $_SERVER['PHP_SELF'] as the action value. It is not required for the form to perform correctly but it's considered good programming practice to use it.

Below is the PHP code used to access form values :



The if statement is used to check if the send variable is set. If it is set then the form must have been submitted. The script then print the value of username using $_POST and $_REQUEST

Using Array As Form Values

Take a look at the code example below. The form have five input with the same name, language[]. Using the same input name is common for checkboxes or radio buttons.



The PHP code below print the value of language after the form is submitted. Go ahead and try the example. Try checking and unchecking the options to see the effect.



From the above code you will notice that $language is an array. This is because in the form code language is repeated several times. When you specify the same input name in a form, PHP will treat it as an array.

There is one important issue you should know when using forms, that is form validation. The code above does not check whether the input is correct such as checking if the user is entering any value into the textbox or is the user selecting any checkboxes. This is actually a bad practice because you should never put a web form without any validation.

============================================

That's it. You just completed the basics of PHP programming!

Grin

07-29-2008 04:08 PM
Find all posts by this user Digg this Post! Add Post to del.icio.us Bookmark Post in Technorati Furl this Post! Add blinklist Add Mongolia Add Netscape Reddit! Stumble Quote this message in a reply
Post Reply  Post Thread 

View a Printable Version
Send this Thread to a Friend
Subscribe to this Thread | Add Thread to Favorites

Forum Jump: