Learn PHP by Examples

In this tutorial, I will walk through the most popular examples to learn PhP. The topics includes simple php example, php get and post methods,  php arrays,  and php object.

PhP hello word

Here the echo keyword is used to print out the html string on your browser. 

Get system information from PHP

<?php phpinfo(); ?>
Get Client’s browser information
$_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal.
A possible output might be:
Mozilla/4.0 (compatible; MSIE 6.0; Linux Ubuntu..)

PHP html form example

htmlspecialchars() can be sued to convert special characters to HTML entities. It  makes sure any characters that are special in html are properly encoded so people can’t inject HTML tags or Javascript into your page.
The $_POST[‘name’] and $_POST[‘age’] variables are automatically set for you by PHP.
If we used the method GET then our form information would live in the $_GET superglobal instead. You may also use the $_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data.
For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters.

PhP Get vs Post

We should use the GET method when your form is getting something off the server and not actually changing anything.
We should use the POST method when you’re using the form to change the state of something on the server end.
Don’t ever use GET method in a form that capture passwords and other things that are meant to be hidden.

PHP $_POST Variable

An associative array of variables passed to the current script via the HTTP POST method when usingapplication/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

This is a ‘superglobal’, or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

PHP $_GET Variable

An associative array of variables passed to the current script via the URL parameters.

PhP multiple selected forms:

Determining variable types

PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string().

PHP arrays

PHP arrays is the most important data structures. I have written another post about php array examples. Please refer to that post.

PHP object