• Home

Logo

Navigation
  • Home
  • Articles
    • Content Writing
    • Design
    • General
    • Internet Marketing
    • Social Media
    • Tools and Tips
    • Usability
    • Web Hosting Articles
  • Tutorials
    • AJAX Tutorials
    • ASP Tutorials
    • C# Tutorials
    • CGI and Perl Tutorials
    • CSS Tutorials
    • Flash Tutorials
    • HTML Tutorials
    • Illustrator Tutorials
    • Java Tutorials
    • JavaScript Tutorials
    • Linux Tutorials
    • Miscellaneous Tutorials
    • MySQL Tutorials
    • Photoshop Tutorials
    • PHP Tutorials
    • Python Tutorials
    • Wireless Tutorials
    • WordPress Tutorials
    • XML Tutorials
  • Scripts
    • AJAX Scripts
    • ASP Scripts
    • ASP.NET Scripts
    • CGI & Perl Scripts
    • Flash Scripts
    • Java Scripts
    • JavaScript Scripts
    • PHP Scripts
    • Python Scripts
    • Remotely Hosted
    • Tools and Utilities
    • XML Scripts
  • Answers
  • Online Services
  • Tools

Introduction to PHP Programming

By PHP Catalyst | on Nov 19, 2007 | 0 Comment
PHP Tutorials
  • Tweet
  • Share
  • Tweet
  • Share

What can I do with PHP?

PHP, as we told earlier, is a server-side scripting
language. The client will always see and interact with HTML in his
browser. PHP is capable of generating dynamic HTML pages and hence it
can output HTML which servers as a presentation layer and in the
backend, on the server
it can continue to process all requests made by the client. These
requests could be processing of form, handling cookies, uploading
files,
generating dynamic HTML by querying a database etc.

PHP can also be used from command line to execute php scripts. This
is similar to running a UNIX shell or a perl script from command to
accomplish tasks like taking backup of files, analyzing log files,
generating a list of files and folders etc.

PHP is capable of doing much more than what read above. You can use
it on command line interface to do most of the tasks stated above,
without a browser, of course. PHP can also be used to create rich GUI
applications using PHP-GTK kit. This requires knowledge of advanced
PHP features.

Let’s look at some of the popular features of PHP.

Popoular Features of PHP

Some of the most popular features of PHP are as mentioned below:-

  1. PHP works on multiple Operating Systems. Some are Linux, manu Unix flavors, BSD, Mac OS X and many more..
  2. Plenty of Web Servers are supported. Some are Apache, IIS, Netscape iPlanet and many others..
  3. Use it as a procedural programming or object oriented programming. Choice is yours!
  4. Dynamic generation of HTML, PDF, Flash, Text, CSV, XML and others..
  5. Support for numerous databases like MySQL, Oracle, MS-SQL, Sybase, PostgreSQL and many others..
  6. Interaction with services like LDAP, POP3, SMTP etc..

PHP comes along with PEAR
(PHP Extension and Application Repository) which is like a library of
code, procedures for handling error, components which can be reused.

Not only these, but there are many more features and abilities of PHP which you will discover as you go along.

I am sure you are excited by now. Let’s begin with PHP Installation. If
you already have the required environment for PHP then let’s look at Basics of PHP.

Basics of PHP

Are we ready?

Assuming that your installation went smooth and you are now ready to
begin, let’s start with some basic understanding of PHP files.

You must understand and remember few things about creating PHP files. And these are:-

  1. Every PHP file will have an extension of .php or optionally
    .php3 You have an option to change these default file extensions using
    the
    web server’s configuration file(s).
  2. A .php file should have all the PHP code inside <? (opening tag) and ?> (closing tag). The
    opening tag can be <?php as well. It will then be treated as php language code and parsed
    accordingly. This is useful when you want to mix PHP code with HTML.
  3. PHP can be embedded inside HTML, but in a slightly different fashion. In between the HTML tags where ever you want to make
    use of PHP code, you will have to use <? php code ?> and this will be parsed by PHP.
  4. All statements must end with a ;(semicolon). This is very important and this semicolon tells the PHP parser to
    treat this line as a single statement. Without this you will see error messages when parsing the code.

Your first PHP code

Why not display some output onto the screen? It is in fact much
easier to accomplish with PHP. All you have to do is use PHP language
construct
called echo and we are done. Here’s how..

Open a blank new file in your editor or notepad and write the below
mentioned lines in the file. Then save the file with a .php extension.
If you are using notepad as editor then be careful about the file
extension. In Windows OS the file extensions are often hidden, so you
must ensure that file saved has a .php extension. Ok, take a look at
the code below..


<? echo "This is my first line!"; ?>
 Or, you can write it using other declaration tag as well, which is
<?php echo "This is my first line!"; php?>


Now save the file and upload it to the correct location in the web server and call it.
The url could be http://localhost/filename.php (just an example, replace ‘localhost’ and filename.php with actual.)

Great! What do you see? We expect to see an output which will look like..

This is my first line!

If that is the exact output on your browser, then it is a success!!!
We are on a good start. If you did not see this output, then perhaps
PHP
was not installed/configured properly. Note that if the PHP file is
prompted to be downloaded in your browser, then PHP is not
installed/configured properly as the file with .php extension is not
being parsed. Please refer to your installation procedure.

Case Sensitivity

All the keywords and built-in constructs are case in-sensitive. Which means, there is no difference between echo and ECHO

Handling Statements

All statements are separated using a semicolon. It’s only a compound
statement such as if loop or a conditional loop which does not need a
semicolon before and after
the closing bracket. For example:


<?php
if (a=b) {
echo 
"a and b are equal"  // Semicolon is not needed here
}                     // Semicolon is not needed here
?>


Commenting the code

Code require commenting for a many reasons. The commented code is
not parsed by PHP and is a good way of adding comments about
statements, code and functions. All lines starting with // will be treated as a comment by PHP. One can also using # to comment the code. Example:


<?php
// Function to echo string passed as an argument
function echo_string($a) {
echo 
$a   // The value of variable a will be printed on screen
}
?>


Now you know that the text in first line and third line after // are treated as comments.

Variables in PHP

Variables

A variable is something that is subject to variation or likely to
vary. In PHP variables are represented with a dollar sign before
the variable name. For example $a, $b are variables. The variable name
is case-sensitive and must always start with a character. So, $a and $A
are different variable names. Some examples are:


<?php
$first_name 
= 'firstname'; //Valid
$last_name = 'lastname'; //Valid
$Middle_Name = 'middlename'; //Valid
echo "$firstname, $Middle_Name, $last_name";
$
9Name = 'name';  //not valid. Variable name can not start with a number
?>


Predefined variables

PHP provides
significant number of predefined variables, some of which are platform
dependent, version specific, server specific.

Some of the widely used predefined variables are:

Server variables:

$_SERVER
when used, offers information such as hostname, script name, location
etc. When used, the information is obtained onto this array from the
web server running PHP. However, as we read before, you may not be able
to get all the information when this variable is used.

Widely used elements of $_SERVER are as mentioned below:

‘PHP_SELF’
refers to file name of the currently executed script. For instance if
the URL is http://www.phpcatayst.com/examples/self.php then $_SERVER['PHP_SELF'] will refer to /examples/self.php

‘argv’ array of arguments passed to the script.

contains the number of command line parameters passed to the script

‘SERVER_ADDR’ the IP address of the server on which the current script is executing.

‘SERVER_NAME’ the hostname of the server on which the current script is executing.

‘REQUEST_METHOD’ request method which was used to access the page; i.e. ‘GET’, ‘HEAD’, ‘POST’, ‘PUT’.

‘QUERY_STRING’ the query string, via which the page was accessed.

‘DOCUMENT_ROOT’ the document root directory under which the current script is executing. This information is
obtained from server’s configuration file.

‘HTTP_ACCEPT’ contents of the Accept: header from the current request, if there is one.

‘HTTP_REFERER’ the address of the page which referred to the current page.

‘HTTPS’ set to a non-empty value if the script was queried through the HTTPS protocol.

‘REMOTE_ADDR’ the IP address from which the user is viewing the current page.

‘REQUEST_URI’ the URI used to access the current page.

Data Types in PHP

In PHP a variable can hold data of any type. These data types are as following:

  • Integer – An integer is a non-fractional, whole number such as 1, 2, 3, 4, 88, 1000, 1374747. The range of integer
    is operating system specific.
  • Real Number – It is also known as a floating
    number or floating point number. It is not a whole number and has
    fractions such as 1.22, 2.45, 100.765 etc.
  • String – Also called character string, it consists of a series of characters such as "php".
  • Boolean – A boolean is a true or a false value.

Assigning data types

Unlike other programming languages, PHP does not require formal
declaration of the data type of a variable. When you assign certain
value to a variable, PHP will automatically try to guess the type of
data being stored and assign the data type to the variable. When needed
PHP will automatically convert the data type.


<?
$a 
= 5; //Storing an integer
$b = 5.5 //Storing a floating number
$c = $a + $b; // $a is integer and $b is floating number
?>


Here data type of $a is automatically converted to a real number and
then added with the value of $b which is a real number too.

Type Casting

Sometimes, there might be a need to change the data type of a
certain variable from string to an integer and then back to a string.
Such manual over riding of data types is called Type Casting. Since PHP
will automatically change the data type, chances are rare that you will
need to use type casting at all. To specify a different of a particular
data type, use the following:


<?
$a 
= (int) $b;  //changing to a variable
$a = (string) $b;  //changing to a string
$a = (float) $b;  //changing to a real number
?>


Determining Data Type

To find out the data type of a variable, use a statement like the following:


<?
$a 
= 100; // storing an integer
var_dump($a);
//This prints the value stored in the variable $a ?>


This will output the data type and value of the variable. In this case, the output will be int(100)

Expressions and Operators

Expressions

PHP can also be called an expression-oriented language that is
because everything you write in PHP is an expression. An earlier
example
where we’ve assigned 100 to $a, an integer value of 100 or either a
string 100 is being stored in the variable $a. You may also assign a
string "hello" to $a by writing $a = hello; Now, if you were to write $b = $a, then $b is containing the string "hello".

Using PHP it is also possible to assign a function to a variable by writing $a = function_a();
and this is all possible because PHP is an expression-oriented language
as well. Another good example of expression orientation is pre- and
post-increment and decrement. This is achieved using variable++ and
variable–. These are known as increment and decrement operators. For
example: if you
want to increment $a by 1, you can simply write ‘$a++’ or ‘++$a’. But
if you want to add more than 1 to $a, say 4, then you will have to
write ‘$a++’ or ‘++$a’ multiple times. A better practice is to write
‘$a = $a + 4′. ‘$a + 4′ evaluates to the value of $a plus 4, and is
assigned back into $a, which results in
incrementing $a by 4. This can also be written as ‘$a += 3′ which
executes faster than previous ways of incrementing values. Extending
this, any two-place operator can be used in this operator-assignment
mode, for example ‘$a -= 10′ (subtract 10 from
the value of $a), ‘$b *= 5′ (multiply the value of $b by 5), etc.

A very common type of expressions are comparison expressions. These expressions evaluate to either FALSE or TRUE.
PHP supports > (bigger than), >= (bigger than or equal to), ==
(equal), != (not equal), < (smaller than) and <= (smaller than or
equal to). The language also supports a set of strict equivalence
operators: === (equal to and same type) and !== (not equal to or not
same type). These expressions are most commonly used inside conditional
execution, such as if statements.

Operators

An operator is something that you feed with one or more values which yields another value.
There are three types of operators.

  • Unary operator – which operates on only one value
  • Binary operators
  • Ternary operator: ?: – used to select between two expressions depending on a third one

Arithmetic Operators

It’s like basic arithmetic. You add, multiply, subtract, divide.


<?
//Example Code for Arithmetic Operators
-$a; // Negation
$a + $b; //Addition - This adds values of $a and $b
$a - $b; // Subtraction - Difference of $a and $b
$a * $b; // Multiplication - Product of $a and $b
$a / $b; // Division - Quotient of $a and $b - returns a float value anytime
$a % $b; // Modulus - Remainder of $a divided by $b
?>


Assignment Operators

The basic assignment operator is "=" which means that the left operand gets set to the value of the expression on the right.


<?
//Example Code
$a = 10; //sets value of $a to 10 
$b = $a; //sets value of $b to the value of $a 
echo $b; //you will see output as 10 
$a = ($b = 20) + 10; // $a is equal to 30 now, and $b has been set to 20 
?> 

Comparison Operators

One of the most important operators are Comparison Operators. They help you compare two values. Take a look at this table:

Example Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

Remember, when comparing an integer with a string, the string is
converted to a number. If you compare two numerical strings, they are
compared as integers.

Control Structures in PHP

Flow-Control Statements (Control Structures)

As you get deeper into programming, you will see a need of executing
a series of statements based on conditions. Based on your requirement,
statements can be grouped into a statement-group by encapsulating a
group of statements with curly braces like { and }.

if construct

if (expr)
    statement

If the expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE – it’ll ignore it.

Let us look at a simple logical flow before we attempt to write PHP
code for the same. In fact, when I started to learn programming, I
first started to write simple english statements and then wrote coding
for them. So, here it is:

Step1 – I want to check if value of $a is bigger than 5
Step2 – If value of $a is bigger than 5, I want to print "Bigger than
5" on screen. Else if value is not bigger than 5, I want to do nothing.
Step3 – End of my logic

Now, writing the same code, programmatically:


<?php
$a 
= 6;
if (
$a > 5) {
   echo 
"Bigger than 5";
   }
?>


In the above code, the expression is evaluated to either TRUE or
FALSE and in this case, if value of $a is found to be bigger than 5, it
evaluates to TRUE and then the statements within the
statement-group are then executed. In this example, we have already
assigned a value of 6 to $a, but you should try to assign values less
than 5 and test the results. As we said earlier, you can group more
statememts in the statement-group and execute them. Try the example and
check the result:


<?php
$a 
= 6;
if (
$a > 5) {
   echo 
"I evaluated the value of a";
   echo 
"and found it to be";
   echo 
"bigger than 5";
   }
?>


You could also do the following:


<?php
$a 
= 6;
if (
$a > 5) {
   echo 
"Bigger than 5";
   
$b = $a;
   }   
?>


Now, if you were to execute the above code, it will print the string
"Bigger than 5" and then assign the value of $a to $b. Have some fun
with this code, try this:


<?php
$a 
= 6;
$b = 10;
if (
$a > 5) {
   echo 
"Bigger than 5";
   
$b = $a;
   }
echo 
$b;
?>


Here, if $a is bigger than 5, value of $a is assigned to $b and the
same is printed on screen. Change the value of $a in first line to 4
and see what happens?

I hope, you had a good learning session with if construct. If you
need more examples in this section, please contact us and let us know.

You now know how to execute statement(s) if certain condition is
met. In this section we will execute a statement in case the expression
in the if statement evaluates to FALSE. Let’s start with looking with the example that we had used earlier:


<?php
$a 
= 6;
$b = 10;
if (
$a > $b) {
   echo 
"a IS bigger than b";
   } else {
   echo 
"a is NOT bigger than b"
   
}
?>


In the above example, swap the values of $a and $b and then check
the results. I hope, you are understanding the use of else construct.
Often, we want to execute statement, when the expression in if
statement is evaluated to TRUE. But, in case, we want to execute a
different set of statement when the expression is evaluated to FALSE
and that’s when else plays a role.
Remember that else statements are executed ONLY when the expression in
if statement is evaluated to FALSE. There is another construct called
‘elseif’ which is a combination of if and else. Unlike else, it will
execute that alternative expression only if the elseif conditional
expression evaluates to TRUE. See this example elseif statement for
better understanding:


<?php
$a 
= 1;
$b = 2;
if (
$a > $b) {
   echo 
"a is bigger than b";
} elseif (
$a == $b) {
   echo 
"a is equal to b";
} else {
   echo 
"a is smaller than b";
}
?>


In this example, the if construct evaluates if $a is bigger than $b.
If TRUE, it will execute the statement within the curly brackets which
is "a is bigger than b". If found to be FALSE, it will move onto elseif
construct which will then evaluate the condition to check if values of
$a and $b are equal (note the use of ==, Comparison Operators) and if
found TRUE will execute the statement "a is equal to b". If FALSE, it
will move onto the else construct which does not evaluate any condition
but will execute the statement "a is smaller than b" because the
condition of if previous expression was evaluated to be false. Try
changing the values of $a and $b to understand this better.

while statement

Using while statement is very simple. Let’s first look at the basic syntax/form of while statement:

while (expr)
   statement

In while statement, group of statement(s) are executed as long as
the expression in while statement evaluates to TRUE. The condition and
its evaluation is checked at the beginning of each iteration. A simpler
example of while statement would be:

Step1 – Assign value of 1 to $i
Step2 – Print the value of $i and increment it by 1 till the value of $i becomes 10

Writing it using while statement would look something like:


<?php
$i 
= 1;
while (
$i <= 10) { //Execute the statements below if this is TRUE
   
echo $i; //Print the value of $i
   
echo " "; //print a space
   
$i++;  //Increment value of $i by 1
   
}
?>


do-while loop

Let us start with the syntax of do-while loops:

do {
   statement
} while (expr);

The only difference between a while and do-while statement is that
expression is evaluated at the end of each iteration instead of doing
it at the beginning. In a do-while loop, the statement will run the
first time and when it reaches end of statements the expression is
evaluated. Based on the exression being TRUE or FASLE, this iteration
is either repeated or ends.

See this example of do-while loop:


<?php
$i 
= 1;
do {
   echo 
$i;
   echo 
" "; //print a space
   
$i++;
} while (
$i >= 10);
?>


In the example, it first prints the value of $i, then increments it
by 1 and then evaluates the expression in while statement. Try changing
the value of $i from 1 to 10 and see what happens?

for loops

for loops are more complex in strcuture than other loop strutures in PHP. The general syntax for a for loop is:

for (expr1; expr2; expr3)
   statement

Here, the first expression (expr1) is executed without any
conditions at the very beginning of the loop. Then at the beginning of
each iteration, the second expression (expr2) is evaluated and if found
to be TRUE, the nested statements are executed. This is one iteration
cycle. If the expression (expr2) is evaluated to be false, the
execution of the loop ends there. And, at the end of each iteration,
the third expression (expr3) is executed.

Share this story:
  • tweet

Author Description

 

No Responses to “Introduction to PHP Programming”

You must be logged in to post a comment.

Connect With Us

RSSSubscribe 0Followers 494Likes
  • Popular
  • Recent
  • Comments
  • Creating Energy Spheres in Photoshop

    Apr 15, 2008 - 96 Comments
  • Easy Screen Scraping in PHP with the Simple HTML DOM Library

    Aug 6, 2008 - 20 Comments
  • Calculating date difference more precisely in PHP

    Mar 7, 2008 - 13 Comments
  • When Does Hosting Your Website in the Cloud Make Sense?

    Oct 8, 2010 - 2 Comments
  • Fun with the Microsoft Managed Extensibility Framework Part 2

    Oct 6, 2010 - 0 Comment
  • Fun with the Microsoft Managed Extensibility Framework Part 1

    Sep 22, 2010 - 0 Comment
  • Website Management on the go with the iPad

    I appreciated your post, but I was looking for something I didn't...
    November 24, 2012 - drmoderator
  • Creating Energy Spheres in Photoshop

    I'm a little stuck down here especially at the step of creating the...
    November 23, 2012 - sarah
  • Running background processes in PHP

    Can you give an example? As see it, you can use this only when you...
    November 16, 2012 - Shaked Klein Orbach
Developer Resources
  • Tutorial Directory
  • Learn HTML
  • Learn PHP
  • Learn CSS
  • Learn AJAX
  • Learn JavaScript
  • Learn Pear
  • White Papers
  • Resources
    • NetVisits Web Directory
    • Realtor Pixels
    • Answers On The Run
    • Ask A Geek
  • Recent Posts

    • When Does Hosting Your Website in the Cloud Make Sense?
    • Fun with the Microsoft Managed Extensibility Framework Part 2
    • Fun with the Microsoft Managed Extensibility Framework Part 1
    • Website Management on the go with the iPad
    • Code Contracts in C# 4.0 – Part 1

    Calendar

    May 2013
    M T W T F S S
    « Oct    
     12345
    6789101112
    13141516171819
    20212223242526
    2728293031  

    Recent Comments

    • drmoderator on Website Management on the go with the iPad
    • sarah on Creating Energy Spheres in Photoshop
    • Shaked Klein Orbach on Running background processes in PHP
    • Thomas Cuvillier on How To Upload Files Using PHP
    • rizal aditya on Extracting text from Word Documents via PHP and COM
    • Home
    © 2003 - 2013 DeveloperTutorials.com. All Rights Reserved. Privacy Policy.