PHP TUTOR

Embed Size (px)

Citation preview

  • 8/9/2019 PHP TUTOR

    1/28

    PHPTUTOR

    [A Quick Guide for Beginners]

    by

    S A Shakil

  • 8/9/2019 PHP TUTOR

    2/28

    [1]

    1. Introduction to PHPWelcome! Let's start by answering some of the basic questions on PHP and OPEN SOURCE...

    1.1 What is PHP?

    PHP stands for "PHP: HyperText Preprocessor". PHP is a server side scripting language for making logic driven

    websites. Ever wonder how they made that "contact us" form on their site, which sends out emails? Well, they used

    PHP. Or, how they made that image upload tool? Well, they used PHP. PHP written scripts can use databases to keep

    track of your customer's and visitors activities on your site, send out periodical newsletters to your subscribers,upload files or images and drive the content on your site dynamically. The possibilities are endless. Yep! PHP is that

    powerful. Learning The Basics of PHP will help you tremendously in your Webpage development.

    1.2 How PHP Works?

    PHP sits between your browser and the web server. When you type in the URL of a PHP website in your

    browser, your browser sends out a request to the web server. The web server then calls the PHP script on that page.

    The PHP module executes the script, which then sends out the result in the form of HTML back to your browser,

    which you see on the screen. Here is a basic PHP diagram which illustrates the process.

    1.3 What are PHP benefits?

    PHP is a free open source language. Best of all, it is easy to install. The most striking feature of it is that it is

    easy to learn. PHP is used by millions of people and developers around the world. There are thousands of websites on

    the internet which are written using PHP. One primary example is Yahoo! Bookmarks. I will show you how to build

    your own PHP website in the simplest way I could find. You will also learn the fundamentals of PHP and write your

    own PHP code.

    1.4 What we need in order to build PHP driven sites?You need PHP Hosting. You can register a domain with a php and mysql host on the web anywhere. There

    are tons of web hosting companies providing free domain names or a paid one.

    You can easily install PHP and MySQL on your home computer easily (see PHP installation page). This will allow you to

    write and test code on your computer and later deploy it to your PHP web hosting account.

    1.5 Do you want to know if PHP is easy to learn?

    It is very easy to learn especially when you take it a step at a time. Complicated things you may want to do

    on your website are made easier with the usage of PHP and it will allow you to do almost anything you can imagine.

    Implementing simple forms or logic on your site is very easy. Techniques of learning PHP are best shown with

    examples.

    If you have the will and the determination, then nothing is hard. Just follow the tutorials on my page. I will walk to

    you through step by step; provide you with working examples, code and tutorials to help you learn PHP. My goal is tomake the learning process fun and easy for you. If you have any question or need help, you can email me

    ([email protected]).

    1.6 What can PHP personally do for you?

    It can greatly increase the functionality of your websites. It will allow you to write scripts which will allow

    your visitors to interact with you through your website. If you are the owner of a small business website, you can use

    PHP to let your users send feed back to you in relation to your ad services, products, or even create forms which will

    allow your website visitors to send you emails. Learn PHP, you will find out what you have been missing in your web

    design and development.

    1.7 Installing PHP on Windows

    Installing PHP is easy. Abyss Web Server is a good Local Webhost. To download Abyss Web Server, browsehttp://www.aprelium.com/downloads. Follow the provided instructions and choose the correct version of the

    software suitable to your computer and to the operating system you are using.

    Visit http://www.aprelium.com/abyssws/scripting.html for configuring your PHP host. Once configured, you are now

    ready to test your php experiences by using your local host.

  • 8/9/2019 PHP TUTOR

    3/28

    [2]

    2. PHP SyntaxWelcome! In this section we're going to learn how PHP and HTML works together. We are also going to build

    our first PHP web page. Exciting! Are you ready?

    2.1 PHP Tags

    PHP is a web scripting language which means it was designed to work with HTML. You can easily embed PHP

    code into your HTMl code. Hmmm! Nice but how do we do that? Simple! When writing php code, you enclose your

    PHP code in special php tags. This tells the browser that we're working with PHP. See below.

    2.2 PHP and HTML

    Now let see how we blend PHP and HTML together.

    my php page

    Echo is a special statement in php for outputting data to the browser. This statement is more often used

    when we need to print something to the browser. You will learn how to use echo in as we go along.

    [Note: Note that, at the end of each PHP statement we need to put a semicolon, i.e. " ;" as you see in the

    above code. Otherwise PHP will report syntax error.]

    Pretty neat, eh? I remember when I first wrote my php code, I was just so amazed.

    So, let do that. Lets write our first PHP page.

    2.3 My First PHP Page

    1. Open up notepad.

    2. Copy-paste the above PHP and HTML code in notepad.3. Now, lets save the file in your root folder, i.e. C:/ Abyss Web Server / htdocs/

    [Remember, we need PHP to run PHP pages on our computer. To install PHP, please go to the PHP installation page.]

    4. Name the file my_php_page.php and save it in your htdocs folder.

    [All PHP files must be saved with extension *.php. This is important because we need to tell the browser that we are

    working with PHP.]

    5. Now, go to http://localhost/my_php_page.php in your web browser.

    You should see "hello there!" printed out on the browser. Pretty simple, eh?

    There you have your first web page in PHP. Now, lets play around with the code. Lets do some more cool stuff.

    2.4 Doing Cool Stuff with PHP and HTML

    Echo statement is powerful in a sense that you can put HTML code in it and it will render the text as if it was

    HTML in your browser. Try it!Example - Make Text Bold

    Replace the PHP line in your code to the following code. Save the file and now refresh your page.>

    You should see hello there! in bold letters in your browser.

    Example - Make Text Green

    Replace the PHP line in your code to the following code. Save the file and now refresh your page.

  • 8/9/2019 PHP TUTOR

    4/28

    [3]

    Example - What's today's date?

    Lets print out today's date using the php date function. Don't worry we will see more examples of the date

    function in later tutorials. We will learn some useful techniques for printing date in different formats. For now, let's

    try the following code.

    Try it! Replace previous echo line with this line. You should see today's date, "today is 2010-02-27", printedout on your browser.

    So, in this section we saw how we can add PHP into our HTML code. This should give you a brief glimpse into

    how PHP works and what we can do with it. You're now ready to move on to some advance PHP stuff! What are we

    waiting for, lets go!

    3. PHP VariablesWelcome! A variable is a mean to store values such as strings or integers so we can easily reuse those values

    in our code. For example, we can store a string value such as "I Love PHP" or an integer value such as 100 into a

    variable. When ever we need to use these values, we simply call that variable instead writing out those values over

    and over again in our code. Here is an example.

    The following code should print "I Love PHP100I Love PHP100". Try it. Copy the code in an empty file, save

    the file as php and run it on your browser.

    Every language has its own semantics of defining variables. In PHP, we define a variable starting with a $ sign,

    then write the variable name and finally assign a value to it. Here is an example below.$variable_name = value;

    3.1 Few Naming Rules

    There are few things we need to note when working with PHP variables.

    A variable name should only start with underscore "_" or a letter.

    A variable can only contain letters, numbers or underscore. In another words, you can't use other funky

    characters like

  • 8/9/2019 PHP TUTOR

    5/28

  • 8/9/2019 PHP TUTOR

    6/28

    [5]

    4.5 How to define a global variable in PHP?

    If you want variables defined out side the function to be accessed inside the function scope then you have to

    make them global inside the function. You can use the global term.

    4.6 How to cast variables in PHP?

    Casting in PHP works the same as in Java or C++. You write the cast type in brackets before the variable.

    Allow cast types:

    (5oolean)

    (int)

    (string)

    (array)

    (object)

    4.7 How to concatenate variables using .=?

    You can use the . operator in PHP to concatenate two variables.

    The example above outputs apples and oranges.

    4.8 PHP Variable type juggling in PHP

    PHP doesnt require variables be declared using primitive types. Therefore, juggling between two types

    doesnt require use of any special function. We can simply do things like

    The above code outputs 4.5 is the total.

    5. PHP Strings OperatorsWelcome! In programming, a string is a sequence of letters, symbols, characters and arithmetic values or

    combination of all tied together in single or double quotes.

    5.1 Strings in PHPExample - PHP String

  • 8/9/2019 PHP TUTOR

    7/28

    [6]

    ?>

    In the above example, we store the string value "I Love PHP" in a variable name $str and use echo to output

    its value.

    5.2 Concatenating Strings in PHP

    Sometimes while working with strings in our code, we need to join two strings. In PHP, you can use ' .' to

    concatenate two or more strings together to form a single string.

    Example 1 - Concatenating PHP Strings

    In the above example we join $str1, empty string and $str2 to form a single string. The above code will

    output "I Love PHP. PHP is fun to learn."

    Example 2 - Concatenating PHP Strings

    Another way you to concatenate strings in PHP.

    In the above example we join $str1 with " PHP is fun to learn." and set it $str2 to form a single string and

    echo str2. The above code will output the same value, "I Love PHP. PHP is fun to learn." as above.

    5.3 PHP Strings in Single and Double Quotes

    5.3a Strings in Double Quotes

    As we saw in our examples, strings are wrapped in double quotes. Using double quotes is the primary

    method. Double quotes allow us to escape specials characters in our string. For example, you can use a single quotes

    with in double quotes.

    [Special characters are escaped using backslash. Sometimes we need escape special characters in our strings.

    We will learn about in the following section.]Example - String in Double Quotes

    5.4 Single Quotes vs. Double Quotes

    Then, looking at single quote strings and double strings you may think there is any difference. However,

    there are reasons for using single quotes and doubles in a string.

    Single quotes should be used when outputting HTML code. Since HTML tag attributes use double quotes

    with in themselves and since using double quotes in HTML tags is the convention, therefore it is advisable to use

    single quotes when wrapping an HTML code in PHP. Here's an example.

    Example - Single Quotes used for wrapping HTML Code

    Double quotes are used when we want to use special characters in our strings such as new line characters\n and \r. Single quotes will treat them as regular characters. Also when printing a variable in a string, it is advisable

    to use double quotes. For example

    Example - Variable Wrapped in Double Quote String

  • 8/9/2019 PHP TUTOR

    8/28

    [7]

    5.5 Escaping Special Characters

    As mentioned above we can escape characters in a string using backslash. An example would be using quotes

    inside quotes in a string. Let's have a look.Example - Escaping quotes with in quotes

    Notice the \". We escaped the double quote using a backslash. The above code will output "This is a PHP

    string examples in double quotes" in double quotes.

    And same goes with single quotes. When you need to use single quotes within single quote, we need to escape it.In the above example we escaped the apostrophe using a backslash like this \'.

    5.6 Useful PHP String Functions

    Here we will list some of the commonly used PHP string functions.

    Example - strlen() Function

    This function returns the number of characters in a string. It takes a string as an argument.

    The above will output 6.

    Example - str_replace() FunctionThis function replaces all occurrences of the search string in the main string with the replace string. Let's look

    at the example below.

    In the above example, I'm saying replace the "Hello" with "Hi" in string $str. The above code will output "Hi!

    How are you today?"

    Example - strtoupper() Function

    This function converts all lower case letters to upper.

    The above example will output "HELLO!"

    Example - ucfirst() Function

    This function changes the first letter in the string to upper case.

    The above example will output "Hello!"

    Example - trim() FunctionThis function removes whitespace from the beginning and from the end of the string.

  • 8/9/2019 PHP TUTOR

    9/28

    [8]

    ?>

    The above example will output "hello!"

    6. PHP OperatorsWelcome! In this section were going to cover different kinds of operators we use in programming. These

    operators are common to ever language. So, in PHP they are no longer different. We will go through each type of

    operators with examples on how they are done in PHP.

    6.1 Arithmetic Operators

    In programming, we often perform arithmetic operations to calculate values. Below is the list of these

    operators with examples.

    Operator Name Example Output

    + Addition

    10

    - Subtraction

    0

    * Multiplication

    25

    / Division

    1

    6.2 Comparison Operators

    Comparison Operators prove very useful when checking the status of two variables or values. For example, if

    you want to check if one is equal to the other, we would use = operator. Comparison operators are used in logic

    conditional statements (check PHP If...else section) to evaluate if the condition is true orfalse.Operator Name Example Output

    > is greater than 6 > 5

    5 > 6

    First example returns true.

    Second example returns false.

    < is less than 6 < 5

    5 < 6

    First example returns false.

    Second example returns true.

    >= is greater than equal to 5 >= 4 returns true

  • 8/9/2019 PHP TUTOR

    10/28

    [9]

    7. PHP If Else StatementWelcome! In this section we are going to learn how to write conditional statements in PHP using "if, else if

    and else" clause.

    Often in programming while writing code to solve problems, we require to perform certain actions based on

    certain conditions. For example, in our application, we might want to display different messages to the users on our

    page based on what day of the week it is. In order to handle this, we write what we call conditional statements where

    each action is performed based on a condition and when that condition is true. Here's what I mean...

    if (condition)perform action 1

    else

    perform action 2

    The above pseudo-code translates... if the first condition is true, then perform action 1, otherwise perform

    action 2.

    7.1 The If...Else Statement in PHP

    Let's examine some code to get an idea how conditional statements are done in PHP. In the following

    example, we evaluate what day of the week it is today. Based on that we display an appropriate message to the user.

    Example - If..Else Statement in PHP (without curly brackets)

  • 8/9/2019 PHP TUTOR

    11/28

    [10]

    In the above example, we use the curly brackets to enclose the action part of the conditional statements

    when we have more than one line in there.

    7.3 The Elseif Statement in PHP

    In the above section, you saw how to write two conditional statements using "If and Else". What if we want to have

    more than two conditional statements? We can have as many conditional statements as we want in your code. To do

    that, we have to use "elseif" between our "if" and "else" statements. Let's say in our above example we also want to

    print a message for Fridays to our users saying "Have a nice weekend!". We would use the elseifclause to do that.

    Let's see how that is done.

    Example - The Elseif Statement

  • 8/9/2019 PHP TUTOR

    12/28

    [11]

    8.2 PHP Switch Statement

    Switch statement should be used in the code when you want to evaluate different cases of a given scenario.

    The switch statement takes a single variable as input and then checks it against all cases we have in our switch

    statement.

    Let's imagine you own a computer retail store. Depending on the product name we want to display the price

    of that product.

    Now, instead writing separate if else statements for each product name, we simple use the PHP switch

    statement on the product name variable to evaluate which product we want to the display the price for. Let's have

    look at the example.

    Example - PHP Switch Statement

  • 8/9/2019 PHP TUTOR

    13/28

    [12]

    ?>

    The code will execute the default code block since we don't carry Briefcase and it is not part of our switch

    statement cases. The code will output "Sorry, we don't carry Briefcase in our catalog".

    [Tip: It is always good to include the default case in your switch statements. It will help you debug your code

    better during testing. In case, none of your switch cases match in your switch statement during code execution, the

    default case will be executed.]

    8.4 PHP Switch Statement: The Break Statement

    The break statement in PHP switch code prevents the code from executing other cases in the switch

    statement when a case is matched to a switch statement, the break statement basically stops the code execution. If

    the break statement is not there, then each case is executed. Consider the following example with two same product

    cases.

    Example- The Break Statement in PHP Switch Statement

    As we can see in the above example, we don't have the break statement after each switch case and we have

    two cases for the product "Processors". So, the above code will evaluate both cases for "Processors".The code evaluates the first case and prints "Intel processors range from $100 to $1000" and then it goes to

    the next case and prints "AMD processors range from $100 to $1000".

    [Tip: If you're a new to switch statements, it is good to use the break statement in your switch cases to

    prevent any confusion.]

    9. PHP ArraysWelcome! In this section we cover what arrays are, what they are used for and how to work with arrays in

    PHP. What is PHP Array?

    An array is a mean to store collection of values in a single variable. Imagine, if you own a shop and you want

    to store the names of your employees. Now, instead of creating a separate variable to store each employee's name,

    you can use an array to store the names of all your employees in a single variable. This is how you would do it.

    Example - PHP Array$employee_names[0] = "Dana";

    $employee_names[1] = "Matt";

    $employee_names[2] = "Susan";

    Each value in the array above is stored as an element and each element is associated to an id or a key which

    you see in the square brackets.

    9.1 Working with PHP Arrays

    There are two types of arrays we deal with in PHP.

    Numeric Arrays

    Associative Arrays

    9.2 Numeric Arrays

    In a numeric array we store each element with a numeric ID key.

  • 8/9/2019 PHP TUTOR

    14/28

    [13]

    9.3 Creating an Numeric Array

    There are two ways to create a numeric array. Lets look at each example to see how we do that.

    Example 1 - Creating a Numeric Array in PHP

  • 8/9/2019 PHP TUTOR

    15/28

    [14]

    Hmmm, that's nice but how the heck would I store employees table in an array? Simple! PHP allows us to do

    that using multidimensional arrays. Let's look at the examples below to see how we would do that.

    9.7 Creating Multidimensional Array in PHP

    Again, there are two ways to create a multidimensional array. Lets look at each example to see how we do

    that.

    Example 1 - Creating Multidimensional Array in PHP

    The above code creates an multidimensional array name employees and outputs "Matt is the Manager and

    he earns $40,000 a year.".

    Example 2 - Creating Multidimensional Array in PHP

    The above code creates a multidimensional array name employees and outputs "Dana is the Owner and they

    earn $60,000 a year."

    9.8 Printing PHP Arrays?

    To print the results of an array you can use the PHP function print_r() to print an array. See example below.

  • 8/9/2019 PHP TUTOR

    16/28

    [15]

    $employee_title["Dana"] = "Owner";

    $employee_title["Matt"] = "Manager";

    $employee_title["Susan"] = "Cashier";

    echo "";

    print_r($employee_title);

    echo "";

    ?>The array result will print out as follow...Array(

    [Dana] => Owner[Matt] => Manager[Susan] => Cashier

    )

    [Note: Always remember to use tags while printing an array as shown above otherwise the

    result is not very reader friendly.]

    Summary

    So, in this section we covered an important lesson on arrays. You will find yourself using arrays a lot when

    programming in PHP because its the most easy and useful way of storing values. The usefulness of arrays will become

    more apparent in the next lesson, PHP Loops.

    10. Loops in PHP:foreach() LoopWelcome! In programming, we often want to repeat a block of code to solve a problem. Instead of writing

    that block of code over and over again, we can use loops to iterate through the code for however number of times we

    want.

    10.1 Types of Loops in PHP

    There are three types of loops often used while programming in PHP.

    foreach loop

    for loop while loop

    Let's go through each type with examples to a have better understanding on how to used them in PHP.

    10.2 Foreach Loop

    Foreach loop is most often used to print elements in a array.

    10.3 Foreach Loop Syntaxforeach (array as $value)

    {

    //code block to be run inside loop

    }

    On every iteration of aforeach loop, the value of the current array is assigned to $value.

    10.4 Using Foreach Loop with Array

    Let's imagine we want a drop down box list of our favorite browsers. We can use an array to store the names

    of the browsers and use PHP foreach loop in conjunction with HTML to make the drop down box. Let have a look at

    the code example to see how that is done.

    Example 1 - Using foreach to print values in an array

  • 8/9/2019 PHP TUTOR

    17/28

    [16]

    The above code will output our drop down box. Firefox 10.5 Using Foreach Loop with Key - Value Pair Array

    In last section, PHP Arrays, we learned multidimensional arrays. We can use foreach loop to print the keys and the

    values from a multidimensional array. What am I talking about?

    Let say we have an multidimensional array of articles. In our array the article title is the key and the article body is the

    value. We will useforeach loop to print the articles onto our web page. Let see how that is done.

    Example 1 - Using foreach to print key - values pairs in an array

  • 8/9/2019 PHP TUTOR

    18/28

    [17]

    11.2 For Loop Syntaxfor(initialize counter; condition until counter is reached; increment counter)

    {

    //execute block of code

    }

    Forloop has three statements.

    In the first statement, we initialize a counter variable to a number value.

    In the second statement, we set a condition (a max/min number value) until the counter is reached.

    In the third statement, we set a value by how much we want the counter variable to incremented by.

    Lets look at an example to see how to create a for loop in PHP.

    11.3 PHP For Loop

    Example - Print number through 0 to 5 with PHP For Loop

    In the above example, we set a counter variable $i to 0. In the second statement of our forloop, we set thecondition value to our counter variable $i to 5, i.e. the loop will execute until $i reaches 5. In the third statement, we

    set $i to increment by 1.

    The above code will output numbers through 0 to 5 as 0 1 2 3 4 5.

    [Note: The third increment statement can be set to increment by any number. In our above example, we can

    set $i to increment by 2, i.e., $i=$i+2. In this case the code will produce 0 2 4.]

    Example - Print number through 5 to 0 with PHP For Loop

    What if we want to go backwards, i.e. print number though 0 to 5 in reverse order? We simple initialize the

    counter variable $i to 5, set its condition to 0 and decrement $i by 1.

    The above code will output number from 5 to 0 as 5 4 3 2 1 0 looping backwards.

    Example - Print table with alternate colors using PHP For Loop

    Let's have a look an interesting example of php forloop. You often seen tables cell with alternate colors on

    different websites. So, let say we want to print the numbers in a table with alternate colors. This is how we would do

    it.

    0

    1

    2

    3

    4

    5

  • 8/9/2019 PHP TUTOR

    19/28

    [18]

    echo "";echo "";echo $i;echo "";echo "";

    }}echo "";

    ?>The above code sets different background color to the table cells depending on the value of $i. If $i is

    divisible by 2, which means if it is even then display color green, otherwise display color red.

    Now that we are familiar with PHP forloop. Now, let's take a look at the last type of loop, the while loop in PHP.

    12. Loops in PHP: while() LoopWelcome! In this section we going to cover the use of while loops in PHP.

    12.1 While Loops

    Just like the for loop, while loop is used to execute a block of code for certain number of times until the

    condition in the while evaluate to true.

    12.2 While Loop Syntaxwhile(condition)

    {

    //execute block of code

    }

    [Note: The condition statement must evaluate to true for the loop to exit otherwise the loop will run

    forever.]

    12.3 PHP While Loop

    Example - Print number through 1 to 5 with PHP While Loop

    Example below prints integers through 1 to 5

    In the above example, you see that the loop is run until the value of $i is less than or equal to 5 according to

    the condition in the loop. The $i = $i + 1; statement increments the value of $i by 1 on each iteration of our while

    loop.

    Example - Print decimal number through 1.0 to 5.0 with PHP While Loop

    Here is another example with decimal numbers.

    Example below prints decimal numbers through 1.0 to 5.0

    12.4 Breaking out of a PHP LoopWe can use the break; statement to stop the loop from executing.

    Sometimes when we are working with loops, we want to break the loop when a certain condition is true.

    For example, we might want to break our loop when $i reaches 4. Lets look at the example below.

  • 8/9/2019 PHP TUTOR

    20/28

    [19]

    $i = 1;

    while ($i

    In the above example, we break the loop when $i reaches 4. The loop outputs...

    1

    2

    3

    13. PHP FunctionsWelcome! In this section we are going to cover PHP functions.

    13.1 What are Functions?

    In technical terms, a function is a group of instructions to perform a task. In laymans term, a function is a

    block of code with a name which can be used in our code whenever we need it.The concept might be new to you but when you look at what a function is, you will be amazed how useful

    and simple it is to create a function. So, let's have a look at what a function looks like...

    Function Syntaxfunction my_function_name(parameters)

    {

    //block of code

    }

    A typical function has three components to it

    Starts with the word function

    Has a function name followed by parentheses (). A function name can only start with a letter or a

    underscore.

    The code block in the function always goes inside curly brackets.

    Now, let's look a how we create functions in PHP.

    13.2 A Simple PHP Function

    Example - Creating and Calling a PHP Function

    In the above code, we create our own function name my_function() and we call that function by just typing

    the its name. The above code outputs "Hello! How are you?".

    13.3 PHP Function with Parameters

    A function can be used to pass arguments (values or information) into it through parameters. This is useful

    when we want to add more functionality to our functions. For example, we can modify the above function to pass a

    person's name and a message into it and display that information.[Note: Parameters appear within the parentheses "()". They are like normal PHP variable.]

    Example - PHP Functions with Parameters

  • 8/9/2019 PHP TUTOR

    21/28

    [20]

  • 8/9/2019 PHP TUTOR

    22/28

    [21]

    //we call our function like this when we want to use it

    echo "The total price after tax: \$" . my_function(50, 5);

    ?>

    In the above function we calculate the total price and return it. The code outputs The total price after tax:

    $55.

    Summary

    Hopefully now you can see how we use functions in our code. We can use functions to organize our code

    into little meaningful chunks and use them as we need them in our code.

    14. PHP CommentsWelcome! Comments are used to describe your code. When you write a block of code to accomplish

    something, it is good practice to write what you have done in that code. More precisely explain what the code does

    using comments.

    Now let's see how we write comments in our code.

    14.1 Types of Comments in PHPThere are two ways to write comments in your PHP code.

    Single Line Comments

    Multiple Line Comments

    14.2 Single Line comments in PHP

    Single line comments are written using two forward slashes, "//". Any line in your PHP code with // in front

    will be ignored and treated as comments. Lets take a look at an example.

    Example - Single Line Comments

    my php page

    In the above example we described the echo line code using a single line comment "// print hello there on

    the screen".

    Also notice that we put // in front of the echo on the last line. Even thou that line is a valid PHP code but it is

    treated as a comment and is ignored by the PHP interpreter.

    14.3 Multiple Line Comments in PHP

    Multiple line PHP comment begins with "/*" and ends with "*/". So, anything inside /* */ will be treated ascomments by the PHP interpreter.

    Multiple line comments are normally used when you have to explain a rather long block of code instead of

    one line code as we saw above with the echo statement. For example, commenting what a function does would be

    done using /* */. Let's have a look at an example to see what i mean.

    Example - Multiple Line Comments

    my php page

  • 8/9/2019 PHP TUTOR

    23/28

    [22]

    function print_name($name)

    {

    // print hello there on the screen

    echo "hello $name!";

    }

    ?>

    14.4 Why write comments in your code?

    Comments are an integral part of your code. Most of the times you will be writing lots of code and things will

    get complicated. Without comments in your code, you could get lost as to what your code does when you come back

    to it later. Comments will help you remember what you did and what your code does.

    It also helps to write comments when you are working in a team. Other programmers can easily tell what

    your code does by reading your comments. They don't have to bother to read your code line by line to figure out

    what it does. This can be really painful for the other developers.

    14.5 Tips on writing comments

    When writing comments describe what the code does instead describing how the code works. Newbies and

    students usually make this mistake. Use single line comments when describing a single line of code and use multipleline comments when describing a block of code.

    15. PHP EmailWelcome! In this section were going to cover how to use the mail function in PHP to send emails.

    PHP has a built in function mail for sending emails. Using this function we can send plain text emails or HTML emails.

    15.1 PHP Mail Function

    mail($to, $subject, $message, $headers);

    As you can see above, the mail function has four parameters.

    to - the recipients email address

    subject - the subject of the email.

    message - the email message to be sent.headers - the header contains information such as the format of the email (plain text or HTML), senders name and

    email, reply to address, CC and BCC.

    15.2 Sending Plain Text Email in PHP

    The following code will send out a plain text email using the PHP built in mail function.

    PHP: Send plain text email

  • 8/9/2019 PHP TUTOR

    24/28

    [23]

    $message);

    ?>

    In our send_email function we set the appropriate headers. Reply-To and Return-Path points to the email

    you want the recipient to reply to. Some server requires the use of Return-Path, so it's good to leave it in there.

    Next we call the send_email function which sends out the email.

    15.3 Sending HTML Email in PHP

    The following function will send out an HTML formatted email using the PHP built in mail function.

    PHP: Send HTML email

  • 8/9/2019 PHP TUTOR

    25/28

    [24]

    Saturday February 27, 2010, 10:16:35

    Saturday February 27, 2010, 10:16 PM

    16.2 PHP Date Function Syntax

    date(format, timestamp)

    As seen above, the php date function take two arguments.

    1. format - Always required. Specify the format to display the in.

    2. timestamp - Optional. Specify UNIX time stamp. If not passed, the current timestamp is used.

    16.3 PHP Date Function Parameters

    format - The first parameter, format, in the date function specifies how to display the date/time. It uses different

    letters to represent the date and time. Some of the letters used above are described here.

    d - The day of the month, i.e. 01-31

    m - Month representation in numbers, i.e. 01-12

    Y - Year in four digits

    For complete list of date/time format reference, visit http://www.php.net/manual/en/function.date.php

    timestamp - The second parameter, timestamp, is an optional parameter. Timestamp is the number of seconds since

    January 1, 1970 at 00:00:00 GMT. This is also known as the Unix Timestamp.

    16.4 PHP Date: Finding Date / TimeUsing the 2nd timestamp parameter we can do things like say find exactly what date or day it was yesterday

    or a week ago or what date it will be 1 month from today.

    There are two ways we can do that.

    Using the PHP strtotime function.

    Using the PHP mktime function.

    1. strtotime - Convert any English textual datetime description into a Unix timestamp.

    2. mktime - Get Unix timestamp for a date.16.5 PHP Date: Using strtotime to find date/time

    Let's see some of the examples to find out dates using date and strtotime function.

    Find Yesterdays date

    Outputyesterday was 2010-02-26

    Find Date one week ago

    Output1 week form today was 2010-02-20

    16.6 PHP Date: Using mktime to find date/timemktime could be used to find more specific things like find the next leap year in the calendar.

    Find Leap Year

  • 8/9/2019 PHP TUTOR

    26/28

    [25]

    * If day is 29 then it must be the leap year. if day is 01, then it not

    a leap year.

    */

    if($day == 29)

    {

    $year = date("Y")+$i;

    break;

    }}

    echo "next leap year is in year $year";

    ?>

    Output

    next leap year is in year 2012

    The mktime takes 6 arguments. The parameters are explained as below.

    1. hour - The number of the hour.

    2. minute - The number of the minute.

    3. second - The number of seconds past the minute.

    4. month - The number of the month.

    5. day - The number of the day.

    6. year - The number of year.

    17. Cooking Cookies with PHP

    17.1 What is a cookie?

    A cookie is often used to store data which can be used to identify a user, for example, person's username.

    Cookie is a small flat file which sits on users computer. Each time that user requests a page or goes to a webpage, all

    cookie information is sent too. This is used to identify who you are.

    17.2 Example of cookie usage:

    When you log into a website and check remember me, it will store your username (and other information

    about you) in a cookie. Next time when you come back to the same website, it knows who you are and will log you in

    automatically.

    In this tutorial, we will learn how to write, read and delete cookies in PHP.

    17.3 Creating a cookie

    A cookie can be created using the setcookie function in PHP. Lets explore this function.

    setcookie($name, $value, $expire, $path, $domain, $secure)

    $name - name of the cookie. Example: "username"

    $value - value of the cookie. Example: "john"

    $expire - time (in UNIX timestamp) when the cookie will expire. Example: time()+"3600". Cookie is set to

    expire after one hour.

    $path - path on the server where cookie will be available.

    For example, if the path is set to "/", the cookie will be available through out the whole site. If the cookie is set tosay "/news/", the cookie will only be available under /news/ and all its sub-directories.

    If no path is given, cookie in created under the current directory.

    $domain - domain where cookie will be available. Instead of path you can use domain settings.

    For example, if the domain is set to ".yourdomian.com", the cookie will be available within the domain and all its

    sub-domains, example news.yourdomain.com.

    If the cookie is set say "www.yourdomian.com" the cookie will be available under all www sub-domains, example

    " www.yourdomian.com/news"

    $secure - true if cookie is being set over a secure "https" server, false otherwise, Default value is false.

    17.4 Creating a cookie with setcookie

  • 8/9/2019 PHP TUTOR

    27/28

  • 8/9/2019 PHP TUTOR

    28/28

    [27]

    When you start a session a unique session id (PHPSESSID) for each visitor/user is created. You can access the

    session id using the PHP predefined constant PHPSESSID.The code above starts a session for the user on the server, and assign a session id for that user's session.

    [Note: The session_start() function must appear BEFORE the tag]

    18.2 Storing information in a session

    To store information is a session variable, you must use the predefined session variable $_SESSION.

    Now, as an example, lets store user's name and their favorite color in a session. To do so you would do the

    following.

    18.3 Retrieving stored session information

    Retrieving stored session information is really easy. You can access the stored session information on any

    page without doing anything extra.

    OutputJohny

    Blue

    18.4 Destroying/deleting session information

    Remember sessions are destroyed automatically after user leaves your website or closes the browser, but if

    you wish to clear a session variable yourself, you can simple use the unset() function to clean the session variable.

    To completely destroy all session variables in one go, you can use the session_destroy() function.

    Thank You