Sunday, December 30, 2012

PHP Tutorial (Faq's) part-6

PHP Mail

You can use PHP to dynamically send emails to one or more recipients. This can be handy for a lot of reasons, for example:
  • Sending newsletters to a mailing list
  • Sending a "welcome" email to new members of your website
  • A user has just made a purchase and you need to send them a receipt by email
  • Sending an email alert to your technical administrator whenever an error occurs
  • Many more reasons...

The PHP mail() Function

To send email using PHP, you use the mail() function. This accepts 5 parameters as follows (the last 2 are optional).
Code

Below is an explanation of the parameters.
Parameter Description
to Required. The recipient's email address.
subject Required. The email's subject line.
message Required. The actual email body.
headers Optional. Additional header fields such as "From", "Cc", "Bcc" etc.
parameters Optional. Any additional parameters.

Sending an Email

You could send email by simply doing this:
Code

Although, in reality, you would probably set your parameters up as variables. Also, if the email was triggered by a user, you would probably provide them with feedback to say that the email had been sent.
Code

HTML Emails

To send an HTML email, the process is the same, however, you need to provide additional headers (as well as an HTML formatted message).
Note that you need to separate each header with a carriage return.

Windows

For Windows systems, use this code:
Code

UNIX

For UNIX systems, use this code:
Code

Difference Between UNIX and Windows Code?

You probably noticed in the above example that there's a Windows version and a UNIX version.
The only difference is in the way the carriage returns are specified. On Windows it's "\r\n", on UNIX it's "\n".
The PHP specification stipulates that you should use "\r\n" for creating the carriage returns. This should work fine on Windows systems. UNIX systems however, have a tendency to add "\r" to the "\n", therefore resulting in "r\r\n", which of course, wouldn't work. Therefore, we simply leave out the "\r" on the UNIX version.

Configuring Mail on PHP

The above steps assume that your PHP installation is configured to send mail. Your hosting provider should already have configured PHP to send mail, so you shouldn't need to do anything further if your website is hosted with a third party hosting provider.
If you need to send mail from your local computer, you may need to configure PHP to send mail. The next lesson explains this.

 PHP Mail Configuration

In the previous lesson, we used mail() to send mail in PHP. That lesson assumes that your PHP installation is configured for sending mail. If your system isn't configured for sending mail, all is not lost - you can change the configuration. This lesson explains how to configure PHP for sending mail.

The php.ini File

The php.ini file is where you configure your PHP installation. This is the file you need to edit in order to configure PHP to send mail.
You need to ensure that the php.ini file contains details of the mail server that should be used whenever your application sends mail.
To check/change your PHP mail configuration:
  1. Open your php.ini file (if you don't know where this is, see below)
  2. Search for the line that reads [mail function]
  3. Add/change the details of your mail server. This could be a local mail server or the mail server of your ISP.
  4. Save/close the php.ini file
  5. Restart your web server
Here's an example of what the mail settings could look like when you first open the php.ini file:
Code

If you're using a UNIX based system, you will need to change the line that reads ;sendmail_path =. You will also need to remove the semicolon from the start of this line (semicolons indicate that the line is a comment). For example, sendmail_path = /usr/sbin/sendmail.
If you're using a Windows system, you should change the line that reads SMTP = localhost to include your mail server (or your ISP's mail server). You could leave it at localhost if you're using your own local SMTP server. If you aren't using your own local SMTP server, you will need to enter a mail server that you have access to (such as your ISP's mail server). For example, SMTP = mail.earthlink.net.
You should also set a default "From" email address by changing the line that reads ;sendmail_from = me@example.com. For example, sendmail_from = you@earthlink.net.

Don't Know Your php.ini Location or sendmail_path Path?

If you don't know where your php.ini is, or what your sendmail_path setting should be, read on...
Your php.ini may be located here: /private/etc/php.ini. And there's a chance that your sendmail path will be at /usr/sbin/sendmail). Having said this, each PHP installation is different, so you should check using phpinfo().
Fortunately, this is easy to do.
phpinfo() is used to view your PHP configuration details. You can do this by creating a .php file with the following line on it: <?php phpinfo(); ?>. When you run this in your browser, you will see a full list of PHP configuration variables. Simply search for the lines that contain php.ini and sendmail_path to see the values you need to use.

 PHP Database Driven Website

You can use PHP, (in conjunction with SQL and HTML), to create database driven websites.
To create a database driven website in PHP, you need a database management system (DBMS). Common database systems include MySQL, Microsoft SQL Server, and Oracle.
Your DBMS can be located either on the same computer that the website is on, or on another server. It's good practice to separate your database server from your web server, but if you've only got one machine to develop on, sharing the same machine shouldn't cause any problems (as long as it's powerful enough to run a web server and database server etc).
Anyway, once you have a database with some tables and some data, you can connect to it and query it.
MySQL is a database system commonly used with PHP websites. The following examples demonstrate how to connect and query a MySQL database.

Connecting to the Database

Before you can query your database, you need to connect to the database server, then locate the database. Once you've done this, you can send in your SQL code to do your queries.
To connect to the database server:
Code

The above code uses the mysql_connect function to connect to the database server. We provide the following parameters: Server, Username, Password. PHP needs this info so that it knows which server to connect to. In this example we are just connecting to the local machine so we use "localhost" as the server.
We have also used the PHP die and mysql_error functions to be used in the event there's an error and PHP can't connect to the server. This will display the error message which can assist us in determining the cause of the problem.
To select the database:
Code

The above code uses the mysql_select_db function to select the database from the database server. You need to do this because, your database server could contain many databases. You need to tell PHP which database to use.
Again we use the die and mysql_error functions to be used in the event of an error.

Querying the Database

You can use the mysql_query function to send a SQL query to the database:
Code

What we do here is, assign the results of a query to the $result variable. The query is acheived by passing a SQL statement to the mysql_query as a parameter. In this SQL statement, we are selecting all records from the "Individual" table.
Once again we use the die and mysql_error in case there's an error.

Displaying the Results

To display the results, you need to loop through the results of the query and display each record with each iteration of the loop:
Code

Here we use a while loop to loop through the results of the query. The while loop keeps iterating until it finishes the last result. This means we can display each result as it iterates past that result. We display the result using $echo and the PHP $row variable, indicating which columns we want to display.

The Whole Code

Combining the above code, (and adding comments), results in something like this:
Code

PHP Tutorial (Faq's) part-5

PHP Include

A PHP "Include" is a file that is included into another file. This concept allows you to re-use content throughout your website.
For example, you could have a standard header and footer on every page of your website. Instead of copying/pasting this code on to every page, you could simply place your header code into one include file and your footer code into another include file. Then, on every page, all you need to do is refer to the header and footer include files. You can do this either using the include() function or the require() function.
There's only a small difference between the include function and the require function. More on that below.

The include() Function

To include a file using the include() function, you simply call the function (as you would any other function) and insert the file path as a parameter.

Usage Example

Code

The require() Function

Usage of the require() function is exactly the same as the include() function - simply call the function and pass the path of the include file.
The difference between the include() and require() functions is in the way they handle errors. If the included file can't be located, the include() function will still display the rest of the page (as well as an error). The require() function, on the other hand, will simply display an error - it won't display the rest of the page.

Usage Example

Code

 PHP Upload File

You can use PHP to allow your users to upload a file to the server.
To allow users to upload a file to the server, you first need to provide a form for them to specify which file they want to upload. Once they click the submit button of the form, the action page is called. This is the page that needs to contain the PHP code to process the uploaded file.

The Input Form

Before a user can upload a file, you need to provide them with an interface that allows them to select a file and initiate the upload.
The following code is an example of an input form. There are a couple of important things to note about this code:
  • The action attribute points to a .php file. This is the file that will process the uploaded file.
  • There is an attribute called enctype, and its value is multipart/form-data.
  • One of the input fields has type="file".
Code

The Action Page

Once the user uploads a file, the file is uploaded into a temporary directory on the server. If you don't move the file it will disappear. Therefore, your action page needs to move the file to another location where it can stay as long as you want it to.
Whenever a file is uploaded, you can find out certain information about the file including its name, type, size, as well as the name of the temporary file on the server. These details are made available to you via a PHP array called $_FILES.

Displaying Details of the Uploaded File

This code simply displays the details of the uploaded file. It doesn't move the file to another location - we'll get to that next. For now, you can use this code in conjunction with the above input form to demonstrate what happens when you upload a file to the server.
Notice the PHP $_FILES array which contains info about the file. Note that we also divide the file size by 1024 in order to convert it into kb.
(Ignore any carriage returns in this example - each table row should be on one line).
Code

The above code results in something like this:
Client Filename: Water lilies.jpg
File Type: image/jpeg
File Size: 81.830078125 Kb
Name of Temp File: C:\WINDOWS\TEMP\php48B2.tmp

Moving the Temp File

As mentioned, if we want to keep the file on the server, we need to move it to another location (of our choice). The following code demonstrates how to move the file from the temporary location.
Code

Checking for Errors

The $_FILES array includes an item for any errors that may result from the upload. This contains an error code. If there are no errors, the value is zero ( 0 ).
You check this value within an "If" statement. If the value is greater than zero, you know an error has occurred and you can present a user friendly message to the user. Otherwise you can processing the file.
Code

Restricting File Type/Size

Letting your users upload files to your server can be very risky. If you're not careful, you could get users uploading all sorts of files - perhaps including harmful executables etc. You could also find one day that you've run out of disk space because some users have been uploading enormous files.
You can restrict the file types and file sizes by using an "if" statement. If the file type and size are acceptable, processing can continue, otherwise, display a message to the user.
Important Note: This doesn't prevent the temp file from being created. The file needs uploaded to the server before PHP can find out the file size and type. This simply prevents the file from being moved to your "permanent" location - hence the file should disappear and (hopefully) not become a problem. In any case, I recommend that you install good anti-virus software before allowing users to upload files to your server.
Code

 PHP File

In the previous lesson we learned how to enable our users to upload files to the server. In this lesson, we'll learn how to work with files on the server.

Reading a File

The following code can be used to read a file.
Code

Here's an explanation of what's happening:
  1. Before you read a file you need to open it. We're using PHP's fopen() function and providing it with two parameters: the file name and the mode in which it should be opened.
  2. We then loop through the file using PHP's feof() function. This checks for the end of the file. Our loop specifies that, while the end of file has not been reached, process the code inside the loop.
  3. The code inside the loop uses PHP's fgets() function. This function reads the file line by line. We need to put our own break otherwise each line would end up on the same line.
  4. Finally, we close the file using PHP's fclose() function, passing the opened file as a parameter.

Writing to a File

The following code can be used to write to a file.
Code

Here's an explanation of what's happening:
  1. Again, we use PHP's fopen() function and supply it with two parameters: the file name and the mode in which it should be opened.
  2. We then use PHP's fwrite() function to write to the file. We supply two parameters: the opened file, and the text to go inside the file.
  3. Finally, we close the file using PHP's fclose() function, passing the opened file as a parameter.

Appending Data to a File

The previous code overwrites any content that might have been in the file. If you only want to add to the end of the existing data, you can simply change the mode from "w" (for "write") to "a" (for "append").
Code

Deleting a File

To delete a file, you use PHP's unlink() function and provide it with the name/path of the file to delete.
Code

 

PHP Tutorial (Faq's) part-4

PHP For Loops

PHP for loops allow you to execute the same piece of code for a specified number of times. Once the specified number has been reached, the program will break out of the loop and continue processing the rest of the page.

Syntax

A PHP for loop requires 3 parameters. The 1st parameter sets a counter, the 2nd parameter defines how high the counter should get before breaking from the loop, the 3rd parameter is used to increment the counter.
Code

Example

We can use the same topic we used in the previous lesson on "while" loops. In fact, for loops are more suited to this type of usage than while loops.
Code

The above code results in:
The share price is $1. Don't sell yet.
The share price is $2. Don't sell yet.
The share price is $3. Don't sell yet.
The share price is $4. Don't sell yet.
The share price is $5. Don't sell yet.
The share price is $6. Don't sell yet.
The share price is $7. Don't sell yet.
The share price is $8. Don't sell yet.
The share price is $9. Don't sell yet.
The share price is $10. Don't sell yet.
The share price is $11. SELL NOW!

For/Each Loops

A for/each loop allows you to loop through arrays. It will execute code continuously until it has looped through every item in the array. Once it has done that, it will continue on processing the rest of the page.
Code

The above code results in:
Apples
Strawberries
Blackberries

 PHP Operators

PHP operators are characters (or sets of characters) that perform a special operation within the PHP code. For example, when you use the equals sign ( = ) to assign a value to a variable, you are using an assignment operator. When you add two numbers together using a plus sign ( + ), you are using an arithmetic operator.
Here's a list of the various PHP operators:

Artithmetic Operators

OperatorDescription
+Addition
-Subtraction
*Multiplication
/Division
%Modulus (remainder of a division)
++Increment
--Decrement

Assignment Operator

OperatorDescription
=Assign
+=Increments, then assigns
+=Decrements, then assigns
*=Multiplies, then assigns
+=Increments, then assigns
/=Divides, then assigns
%=Modulus, then assigns

Comparison Operators

OperatorDescription
==Is equal to
!=Is not equal to
>Greater than
>=Greater than or equal to
<Less than
<=Less than or equal to

Logical Operators

OperatorDescription
&&And operator. Performs a logical conjunction on two expressions (if both expressions evaluate to True, result is True. If either expression evaluates to False, result is False)
||Or operator. Performs a logical disjunction on two expressions (if either or both expressions evaluate to True, result is True).
!Not operator. Performs logical negation on an expression.

Concatenation Operators

OperatorDescription
.Concatenate (join two strings together)

 PHP Functions

Sometimes you might find yourself writing the same piece of code over and over again. You might even find yourself "copy/pasting" code so that you can re-use it in another part of your application. The problem with doing this is, you now have more code to maintain. For example, if you want to change the code, you need to change it in many different places. A better idea would be to put that code into a function.
PHP functions are self contained blocks of code that perform a specified "function". A function often accepts one or more "parameters" (also referred to as "arguments") which you can "pass" to it. By providing a different parameter to the function, you get a different result (depending on what the function actually does).

Creating PHP Functions

To create a PHP function, follow these steps:
  1. Think of a name for the function. Make it short but descriptive. It should describe what the function actually does.
  2. Type function
  3. On the same line, type the name of the function followed by opening/closing brackets ( eg, myFunction() ).
  4. Add an opening curly brace ( { )
  5. Type the code that makes up the function
  6. Finish with a closing curly brace ( } )

Example

Code

Calling PHP Functions

The function doesn't actually do anything until you call it. To call a function, do the following:
  1. Write the function name followed by opening and closing brackets (i.e. functionName() )
  2. Between the opening/closing brackets, provide any parameters the function requires. If it doesn't require any parameters you can leave it blank.

Example

In this example, we create the same function we created in the previous example. We then call that function:
Code

The above code results in the following:
My favorite fruit is pomegranate.

Passing Parameters

The previous example is a very simplistic version of a function. We could improve this function by allowing it to accept a parameter. For example, imagine if, at the time we called the function, we could pass it the name of a fruit. The function could then display the name of that fruit (instead of displaying "pomegranate" every time).

Example 1

Code

The above code results in the following:
My favorite fruit is: Watermelon
This is one of the things that make functions so cool. For example, by accepting a parameter (such as the fruit name), we could let our website users provide us with the name of their favorite fruit. Behind the scenes, we could put that fruit into a variable, then pass that variable to our function. The function could then display the name of their favorite fruit (instead of "pomegranate"!).

Example 2

In this example, the fruit name is supplied as a variable. For the purposes of this tutorial, we set the variable to a hard-coded string, but there's no reason this couldn't be a value provided by the user (for example, a value from a form).
Code

The above code results in the following:
My favorite fruit is: Watermelon

Return Values

In the previous examples, our functions simply displayed a string to the user. Sometimes, you might not want your function to automatically display the result. Sometimes you might just want the function to return the result to you so that you can use it for your own programmatical purposes. That way, it's your choice whether you display it to the user, or do something else with the result.
To create a return value, you type return followed by the value you want to return.

Example

Code

The above code results in the following:
104

PHP Tutorial (Faq's) part-3



PHP Switch Statements
In the previous lesson we used a PHP if... elseif statement in order to execute different block of code for each different condition. As mentioned, we could use as many "elseif"s as we like.
If you have many conditions, PHP switch statements are a more efficient way of doing this. The server will execute a PHP switch statement quicker than multiple "elseif"s. Also, there's actually less code for the programmer to write.
To write a PHP switch statement, you start with the switch keyword followed by the expression to evaluate (for example, a variable name). You then follow that with a case for each condition (based on the expression).

Syntax

Code

Example

In the following example, we declare a variable called $favoriteVege and assign a value to it. We then execute a switch statement in order to display a different string depending on the value of the variable.
Don't forget to end each case with a break;. This is required, otherwise all cases would be displayed.
Code

The above code results in the following:
Sorry, don't know how much energy that vegetable contains.

PHP Arrays

PHP arrays allow you to store groups of related data in one variable (as opposed to storing them in separate variables). Storing data like this in an array has many benefits. For example, if you have a lot of data, you could populate the array programmatically. You could also output the contents programatically - all you need to know if the name of the array.
There are 3 different types of PHP arrays:
  • Numeric arrays
  • Associative arrays
  • Multidimensional arrays

Numeric Arrays

Numeric arrays use a number as the "key". The key is the unique identifier, or ID, of each item within the array. We can use this ID later when working with the contents within the array - we don't need to know the item's value, just the ID.
Note that numbering starts at zero.

Creating Numeric Arrays

You can choose between the following options when creating an array. Both of these options have the same result.
·         Option 1 - Manual key assignment
When creating an array this way, you assign each "key" as a number within open and closing square brackets ([ and ]).
Code

·         Option 2 - Automatic key assignment
When using this method to create an array, you don't need to assign the key - PHP will do that for you.
Code

Displaying the Array Contents

You can work with each value in an array by referring to its key. For example, to select the 2nd value in an array, we would do this: $arrayName[1]. Just a reminder that numbering starts at zero, so the 2nd item actually uses the number one as it's key.
Example:
Code

The above code results in:
Strawberries

Associative Arrays

Associative arrays are similar to numeric arrays but, instead of using a number for the key, we use a value. We then assign another value to the key - you could think of it as two values for the price of one!

Creating Associative Arrays

As with creating numeric arrays, there are two options for creating associative arrays in PHP (although in both cases, we have to create the key manually).
·         Option 1
Code

·         Option 2
Code

Displaying the Array Contents

You can display the contents of associative arrays just as you would with numeric arrays - by referring to it's key.
Code

The above code results in the following:
Artichoke: 105 kilojoules

Multidimensional Arrays

Multidimensional arrays allow you to put an array inside another array. In other words, the contents of the array is another array. You can do this as many times as you wish - you could have an array inside another array, which is inside another array, etc
The following diagram demonstrates this. We have an array called "Food", which contains 3 arrays (called "Fruit", "Vegetables", "Grains"). Each of these arrays contain their own arrays (one for each food within that group).
Food
Fruit
Apples

Bananas

Oranges

Vegetables
Carrots

Potatoes

Grains
Oatbran

Creating a Multidimensional Array

We can create the above array using the following code:
Code

PHP While Loops

PHP while loops allow you to execute the same piece of code continuously while a certain condition is true. Once the condition becomes false, the program will break out of the loop and continue processing the rest of the page.

Syntax

Code

Example

This example executes the same piece of code while the "sharePrice" variable is less than or equal to 10. With each iteration through the loop, we increment the value of $sharePrice by 1. This means the value of $sharePrice will eventually become greater than 10, which will result in the end of the loop, and the rest of the page will be processed.
Code

The above code results in:
The share price is $1. Don't sell yet.
The share price is $2. Don't sell yet.
The share price is $3. Don't sell yet.
The share price is $4. Don't sell yet.
The share price is $5. Don't sell yet.
The share price is $6. Don't sell yet.
The share price is $7. Don't sell yet.
The share price is $8. Don't sell yet.
The share price is $9. Don't sell yet.
The share price is $10. Don't sell yet.
The share price is $11. SELL NOW!

Do/While Loops

A do/while loop is similar to a while loop. The difference is that a do/while loop executes the code at least once before checking the condition. Therefore, if the condition is false, a do/while loop will execute once. A while loop, on the other hand, won't execute the code at all if the condition is false.

Example

This example demonstrates the difference between a while loop and a do/while loop.
·         While Loop
Code

·         The above code results in:
  • The share price is 15. SELL NOW!
·         Do/While Loop
Code

·         The above code results in:
  • The share price is 15. Don't sell yet.
    The share price is 16. SELL NOW!

PHP Tutorial (Faq's) part-2

PHP Variables

Variables are named "containers" that allow you to store a value. This value can then be used by other parts of the application, simply by referring to the variable's name. For example, the application could display the contents of the variable to the user.
In PHP, variable names must start with a dollar sign ($). For example:
Code

Another Example

PHP variables can contain strings (like the previous example), numbers, and arrays. When a variable contains a number, you can perform calculations against that value. Here's a simple calculation using variables:
Code

The above code results in the following:
11

Concatenation

When outputting multiple variables and other text to the screen, you can concatenate them (join them together) either with multiple echo statements, or by using one echo statement with a dot (.) between each part.
Here's an example of both methods:

Option 1

Code

Option 2 (less code)

Code

Both of the above code examples result in:
2 + 9 = 11

Variable Names

When creating names for your variables, you need to ensure they comply with the following naming rules:
  • All PHP variable names must start with a letter or underscore ( _ )"
  • Variable names can only contain alpha-numeric characters and underscores ( i.e. a-z, A-Z, 0-9, or _ )
  • Variable names must not contain spaces. For multi-word variable names, either separate the words with an underscore ( _ ) or use capitalization.

 PHP Form Variables

Many website applications rely on HTML forms so that users can perform their tasks. For example, most Content Management Systems allow users to provide content for a website by entering the content into a textarea form field, then clicking a "Save" button. When the user clicks the Save button, the form is submitted to the action page. The action page is normally specified with the action attribute of the form tag.
If you're not familar with HTML forms, see the HTML forms section of the HTML tutorial, then return to this page.
Once a form has been submitted, the form fields are made available to the action page as a special type of variable. You, as the programmer, can read these form variables by using the appropriate syntax for form variables. Form variables are stored as an array. We will be covering arrays later, but for now all you need to know is how to read each form variable.
Forms can be submitted using one of two methods: get or post. By default, a form will be submitted using the "get" method. This results in each form variable being passed via the URL. If you decide to use the "post" method, you specify this using the method attribute ( method="post" ) of the form tag.

The Get Method

If you use the get method, your action page can access each form field using $_GET["variableName"] (where "variableName" is the name of the form field).

Example

Form page
CodeResult



Action page (php_action_page1.php):
Here, the action page outputs the contents of the form variables that were passed from the form.
Code

The Post Method

If your form uses the post method, you use $_POST["variableName"].

Example

Form page
CodeResult



Action page (php_action_page2.php):
Here, the action page outputs the contents of the form variables that were passed from the form.
Code

 PHP If Statements

You use PHP if statements when you want your program to execute a block of code only if a particular condition is true. In other words, you can tell your program "if something is true, then execute this piece of code".

Syntax

Code

Example

In the following example, we create a variable called "favoriteFruit" and assign a value to it. We then compare the value with a string: "Pomegranate". If the two values are the same, we output some text.
The two equals signs (==) is a comparison operator (it compares the two values). If this condition is true, it displays the code within the curly braces ({ and }). The curly braces are only necessary if you're outputting multiple lines of code . If you're only outputting one line of code (like we are) they're optional.
Code

The above example results in the following:
Your favorite fruit contains around 7% fibre.

If Else Statement

We can add an else to our if statement to make our application do something else if the condition is not true.
Example:
Code

The above example results in the following:
Sorry, I don't know how much fibre that fruit contains.

If... Elseif Statement

Let's say we learn the fibre content of another fruit. We could then add an elseif to our if statement. That way, we could include a custom message for the new fruit. In fact, we could use elseif as many times as we like.
Example:
Code

The above example results in the following:
Your favorite fruit contains around 1.5% fibre.