Overview of PHP Structure and Syntax
a The extension of php file is .php
a This extension signifies to the server that it needs to parse the php code before sending the resulting html code to the viewer's web browser.
a PHP is denoted in the page with opening and closing tags, as follows,
..... ..... ....
..... ..... ....
?>
The lines end with a semicolon.
echo "What is you name?";
echo $name;
?>
a You can add comments frequently in you code.
// This is a comment statement that is not compiled by web server;
/* You can use this kind of comment also when;
you need to write multi-lined text as comment */;
?>
a Some few PHP coding are given below;
echo " Hi $_POST['fname']
echo "Your name's not Jeo, so you can't enter the web site.
";
?>
Or
echo " ";
echo "Hi";
echo "$_POST['fname']";
echo "
?>
Considerations with HTML Inside PHP
a You have to check for double quotes. Ex: echo "";
a Remember that you still have to follow PHP rules, even though you're coding in HTML.
a Don't try cram too much HTML into your PHP sections.
Using Constants and Variables
Constant:
Syntax:
define("CONSTANT NAME","VALUES")
define ("FAVMOVIE","The Life of Brian");
?>
Overview of variables
a Variables are denoted with a dollar sign ($).
a They are case-sensitive.
a The first letter of the variable name must be an underscore or letter and cannot be a number.
Example,
$variable_of_php=10;
$variable_of_php="Susanta";
$variable_of_php=13.23;
$variable_of_php=99999;
?>
Mathematical statement in PHP
$variable1=10;
$variable2=23;
$variable3=4;
$variable4=9;
$variable5=(($variable1 + $variable1 + $variable1 + $variable1) / 4 );
echo "The average movie rating for this movie is : ";
echo $variable5;
?>
Function | Description |
rand([min],[max]) | Generates a random integer. |
ceil(number) | Rounds a decimal up to the next highest integer. |
floor(number) | Rounds a decimal down to the next lowest integer. |
max(argument1,argument2, ...) | Returns the maximum value of the supplied arguments. |
min(argument1,argument2, ...) | Returns the minimum value of the supplied arguments. |
Passing Variables Between Pages
There are basically four ways to accomplish this task;
1) Pass the variables in the URL.
2) Through a session.
3) Via a cookie
4) With an HTML form.
A Word about register_global
a This is a configuration setting in your php.ini
a Coding with the assumption that register_globals has been turned off is the safest way to code because your program will work regardless of the server's setting.
a We can pass the value of variables from one page to another by using the following functions without based on whether register_globals is turned on or off.
Syntax | When to use it |
$_GET['varname'] | When the method of passing the variable is the "GET" method in HTML forms. |
$_POST['varname'] | When the method of passing the variable is the "POST" method in HTML forms. |
$_SESSION['varname'] | When the variable has been assigned the value from a particular session. |
$_COOKIE['varname'] | When the variable has been assigned a value from a cookie. |
$_REQUEST['varname'] | When it doesn't matter ($_REQUEST includes variables passed from any of the above methods) |
$_SERVER['varname'] | When the variable has been assigned a value from the server. |
$_FILES['varname'] | When the variable has been assigned a value from a file upload. |
$_ENV['varname'] | When the variable has been assigned a value from the operating environment. |
Passing Variables Through a URL (Uniform Resource Allocate)
Example:
First File name is index.php which will send value of variables to second file.
echo "href='page1.php? favoritemovie=Matrix'>";
echo "Click Here to see information about my favorite movie!";
echo "";
?>
Second file name is page1.php will display the value of favoritemovie.
echo "My Favorite Movie is :";
echo $_REQUEST['favoritemovie'];
?>
Other examples: To send value of variables through URL
Click Here
echo "";
echo "Click Here";
echo "";
?>
Other examples: To take value of variables from URL
echo $_REQUEST['favoritemovie'];
echo $_GET['favoritemovie'];
echo $_POST['favoritemovie'];
?>
Passing Variables with Sessions
a A session is basically a temporary set of variables that exists only until the browser has shut down.
a Unless you can set up differently in your php.ini file.
a Every session is assigned a unique session ID, which keeps all the current information together.
a Your session ID either can be passed through the URL or through the use of cookies.
a Although it is preferable for security reasons to pass the session ID through a cookie so that it is hidden from the human eye.
a If cookies are not enabled, the backup method is through the URL.
a If you would like to force the user to pass variables through cookies, you would set the following line in your php.ini. Such as, session.use_only_cookies=1
a To begin a session, use the function session_start().
a Because we assume you have register_globals set to "off", you should not use the session_register() function you may have seen in other PHP scripts.
a Make sure before using sessions that your php.ini file has been modified to show a valid path in the session.save_path variable.
a All the session information is at the top of the page, before any HTML code. This is very important. If there is even a leading space before the php code at the top of the page, you will get the error.
Exampel:
The first file: index.php
session_start();
$_SESSION['username'] = "Joe1234";
$_SESSION['authuser'] = 1;
?>
$myfavorite = urlencode("Matrix");
echo "";
echo "Click Here to see information about my favorite movie!";
echo "";
?>
The Second file: page1.php
session_start();
// check to see if user has logged in with a valid password
if ($_SESSION['authuser'] != 1) {
echo "Sorry, but you don't have permission to view this page.";
exit();
}
?>
echo "Welcome to our site,";
echo $_SESSION['username'];
echo "!
";
echo "My Favorite Movie is ";
echo $_REQUEST['favoritemovie'];
?>
Passing variable with Cookies
a Cookies are tiny bits of information stored on your Web site visitor's computer.
a Your visitors may either have cookies turned off or may physically delete cookies from their computers.
a The advantage to storing information in a cookie versus a session is longevity. Session can't store information for more than the length of time the browser window is opened.
a Cookies can live on a person's computer until the developer has decided it's been long enough and they automatically die.
a If your sessions are passing variables using cookies, you can set the life of these cookies to longer than the life of the browser using the session.cookie_lifetime configuration in your php.ini file.
a Like session, cookie must be placed at the very top of he page, before your first line.
Syntax:
setcookie('cookiename','value','expiration time','path','domain','secure connection');
Feature | Description (Mandatory / Optional) |
cookiename | Cookie name is mandatory. |
value | Value of the cookie |
expiration time | Time in seconds when the cookie will expire. This time is based on a Unix timestamp, but you can set it using the syntax time()+60*60*28*365, which keeps the cookie alive for a year. This is optional, but if it is not set, the cookie will expire when the browser is closed. |
path | The directory where the cookie will be saved - optional. |
domain | Domains that may access this cookie - optional. |
secure connection | Whether a cookie must have a secure connection to be set (defaults to 0, to enable this feature set this to 1) |
Example:
First File : index.php
setcookie('username','Jeo', time()+60 );
session_start();
$_SESSION['authuser']=1;
?>
$myfavorite = urlencode("Matrix");
echo "";
echo "Click Here to see information about my favorite movie!";
echo "";
?>
Second file: page1.php
session_start();
// check to see if user has logged in with a valid password
if ($_SESSION['authuser'] != 1) {
echo "Sorry, but you don't have permission to view this page.";
exit();
}
?>
echo "Welcome to our site,";
echo $_COOKIE['username'];
echo "!
";
echo "My Favorite Movie is ";
echo $_REQUEST['favoritemovie'];
?>
Passing information with Forms
A form is made up of four parts -
1. Opening tag line, indicated by the : This tag must include an action and a method. A method may be either GET or POST (however POST is preferred method because it is more secure).
2. Content of the form, including input fields: Input areas where user types in the information (or selects it in the case of a checkbox or radio button). An input field must include a type and a name. The type of input field can be one of many different selections, the most common beings:
a) Text: Used for collecting from 2 characters up to 2,000 characters.
b) Checkbox: Used to allow user to make a selection from a list of choices; also permits user to make more than one choice.
c) Radio: Used for allowing users to choose from a list, but permits only one choice.
d) Select: Used for allowing users to choose from a list.
e) Password: Hides what user is typing behind asterisks, but does not compromise the value of the variable.
3. Action button(s) or images, typically submit/clear or a user-defined button, typically considered input types as well: These are indicated with the input types submit, reset and image for user-created buttons.
4. Closing tag line, indicated with a tag.
Example:
Enter your name:
First file: index.php -
session_unset();
?>
Enter your password:
Second file: page1.php -
session_start();
$_SESSION['username'] = $_POST['user'];
$_SESSION['userpass'] = $_POST['pass'];
$_SESSION['authuser'] = 0;
// Check username and password information
if (($_SESSION['username'] == 'sumon') and ($_SESSION['userpass'] == 'sumon' )) {
$_SESSION['authuser'] = 1;
}
else {
echo "Sorry, you have no permission to view this page!";
exit();
}
?>
$myfavorite = urlencode("Matrix");
echo "";
echo "Click Here to see information about my favorite movie!";
echo "";
?>
Third page: display.php -
session_start();
if ($_SESSION['authuser'] != 1) {
echo "Sorry, you have no permission to view this page!";
exit();
}
?>
echo "Welcome to our site,";
echo $_SESSION['username'];
echo "!
";
echo "My Favorite Movie is ";
echo $_REQUEST['favoritemovie'];
?>
Using if Statement
Syntax:
if (condition1 operator condition2) action to be taken if true;
Example:
if ($stockmarket >= 10000) echo "Hooray! Time to Party!";
Example: If the action to take is longer than a simple statement that will easily fit on one line.
if ($stockmarket >=10000) {
echo "Hooray! Time to Party!";
$mood = "happy";
$retirement = "Potentially obtainable";
}
Example: Here, date("n") returns a value equal to the numerical equivalent of the month as set in your server, such as 1 for January, 2 for February and so no.
echo "The number of day of the month is ";
$month = date("n");
if ($month ==1) echo "31";
if ($month ==2) echo "28 (unless it's a leap year)";
if ($month ==3) echo "31";
if ($month ==4) echo "30";
if ($month ==5) echo "31";
if ($month ==6) echo "30";
if ($month ==7) echo "31";
if ($month ==8) echo "31";
if ($month ==9) echo "30";
if ($month ==10) echo "31";
if ($month ==11) echo "30";
if ($month ==12) echo "31";
?>
Using if-else statement
Example: Suppose, the year is 2007. That is not a leap year, so the value of $leapyear would be 0. If this is a leap year then date("L") sends the value as 1 else it sends value as 0.
$leapyear = date("L");
if ($leapyear == 1) echo "It is a leap year!";
else echo "Sorry, mate. No leap year this year.";
?>
Operator
Operator | Appropriate Syntax |
equal to | == |
not equal to | != or <> |
greater than | > |
less than | < |
greater than or equal to | >= |
less than or equal to | <= |
equal to, AND data types match (both are integers, or both are strings) | === |
not equal to, OR the data types are not the same | !== |
Using Includes for effective code
Example:
First File: included_file.php - which will be added to the main page.
Welcome to my movie review site
echo "Today is ";
echo date("F d");
echo ", ";
echo date("Y");
?>
Second file: main.php -
included_file.php"; ?>
My Favorite Movie is : Matrix Part I, II and III
Using Functions for Efficient Code
a Functions are mini-programs within themselves.
a They don't know about any other variables around them unless you let the other variables outside the function in through a door called "global".
a Your functions can be located anywhere within your script and can be called from anywhere within your script.
a You can list all your commonly used functions at the top of your program and they can all be kept together for easier debugging. Better yet, you can put all your functions in a file and include them in your programs.
Example:
Enter your name:
First file: index.php -
session_unset();
?>
Enter your password:
Second File: page1.php -
session_start();
$_SESSION['username'] = $_POST['user'];
$_SESSION['userpass'] = $_POST['pass'];
$_SESSION['authuser'] = 0;
// Check username and password information
if (($_SESSION['username'] == 'sumon') and ($_SESSION['userpass'] == 'sumon' )) {
$_SESSION['authuser'] = 1;
}
else {
echo "Sorry, you have no permission to view this page!";
exit();
}
?>
$myfavorite = urlencode("Matrix");
echo "";
echo "Click Here to see information about my favorite movie!";
echo "";
echo "
";
echo "";
echo "Click Here to see my top 5 movies.";
echo "";
echo "
";
echo "";
echo "Click Here to see my top 10 movies.";
echo "";
?>
Second file: display.php -
session_start();
if ($_SESSION['authuser'] != 1) {
echo "Sorry, you have no permission to view this page!";
exit();
}
?>
echo "Welcome to our site,";
echo $_SESSION['username'];
echo "!
";
function listmovies_1()
{
echo "1. Matrix.
";
echo "2. Life of Brain.
";
echo "3. Stripes.
";
echo "4. Office Space.
";
echo "5. The Hole Grail.
";
}
function listmovies_2()
{
echo "6. Terminator 2.
";
echo "7. Star Ears.
";
echo "8. Close Encounters of the Third Kind.
";
echo "9. Sixteen Candles.
";
echo "10. Caddyshack.
";
}
if (isset($_REQUEST['myfavorite'])) {
echo "My Favorite Movie is ";
echo $_REQUEST['favoritemovie'];
}
else {
echo "My Top ";
echo $_REQUEST['movienum'];
echo " movies are :
";
listmovies_1();
if ($_REQUEST['movienum'] ==10) listmovies_2();
}
?>
Array
a Arrays are nothing more than lists of information mapped with keys and stored under one variable name. Example, you can store a person's name and address or a list of states in one variable.
Example: We can write the following table into a array.
First Name | Last Name | Age | |
Husband | Albert | Einstein | 34 |
Wife | Mileva | Einstein | 32 |
$husband = array("firstname"=>"Albert",
"lastname"=>"Einstein",
"age"=>34);
$wife["firstname"] = "Mileva";
$wife["lastname"] = "Einstein";
$wife["age"] = 32;
?>
Example: You can also have arrays within arrays (also known as multi-dimensional arrays).
$table1 = array("husband" => array("firstname"=>"Albert",
"lastname"=>"Einstein",
"age"=>34),
"wife" => array("firstname"=>"Mileva",
"lastname"=>"Einstein",
"age"=>32)) ;
echo $table1["husband"]["firstname"];
echo "
";
echo $table1["wife"]["firstname"];
?>
Example:
$flavor[] = "blue raspberry";
$flavor[] = "root beer";
$flavor[] = "pineapple";
echo $flavor[0]; //outputs blue raspberry
echo $flavor[1]; //outputs root beer
echo $flavor[2]; //outputs pineapple
?>
Sorting Arrays
a PHP provides many easy ways to sort array values.
Function | Description |
arsort(array) | Sorts the array in descending value order and maintains the key/value relationship |
asort(array) | Sorts the array in ascending value order and maintains the key/value relationship |
rsort(array) | Sorts the array in descending value order |
sort(array) | Sorts the array in ascending value order |
Example: Here print_r() is simple prints out information about a variable so that people can read it. It is frequently used to check array values, specifically.
$flavor[] = "blue raspberry";
$flavor[] = "root beer";
$flavor[] = "pineapple";
sort($flavor);
print_r($flavor);
?>
foreach Constructs
a PHP also provides a foreach command that applies a set of statements for each value in an array.
Example:
$flavor[] = "blue raspberry";
$flavor[] = "root beer";
$flavor[] = "pineapple";
echo "My favorite flavors are:
";
foreach ($flavor as $currentvalue) {
// These lines will execute as long as there is a value in $flavor
echo $currentvalue . "
\n";
}
?>
While Statement
Example: At the top of the loop, the while checks to see that the value of $num is less than or equal to 5. After five times through the loop, the value of $num is 6, so the loop ends.
$num = 1;
while ($num <= 5) {
echo $num;
echo "
";
$num = $num + 1;
}
Example: The following code works exactly the the same way, except that the condition is checked at the end of the loop. This guarantees that the conditions inside the loop will always be executed at least once.
$num = 1;
do {
echo $num;
echo "
";
$num = $num + 1;
} while ($num <=5);
echo
Example:
echo "My top ". $_POST['num'] ." movies are :
";
Alternates to the Tags
a : This must be turned on in your php.ini file with the short open tags configuration.
a <% and %>: This must be turned on in your php.ini file with the ASP tags configuration.
a : These are available without changing your php.ini file.
Alternates to the echo command
a print() command to display text or variable values in your page.
a The difference between echo() and print() is that when you use print(), a value of 1 or 0 will also be returned upon the success or failure of the print command.
Altering to Logical Operators
a && can be used in place of and, only difference being the order in which the operators is evaluated during a mathematical function.
a || can be used in place of or, only difference being the order in which the operators is evaluated during a mathematical function.
Alternates to incrementing / Decrementing Values
Syntax Shortcut | What it does to the value |
++$value | Increases by one, and returns the incremented value. |
$value++ | Returns the value, then increases by one. |
--$value | Decreases by one and returns the decremented value. |
$value-- | Returns the value, then decreases by one. |
$value=$value+1 | Increases the value by one. |
$value+=1 | Increases the value by one. |