PHP TUTORIAL WITH EXAMPLES PDF

adminComment(0)

Download Free Php tutorial pdf, HTML tutorial pdf, CSS tutorial pdf, Javascript pdf, php ebook free download and php tutorial for beginners with examples. PHP i. About the Tutorial. The PHP Hypertext Preprocessor (PHP) is a programming language in this tutorial, please notify us at [email protected] computerescue.info PHP Tutorial in PDF - A simple and short PHP tutorial and complete reference manual for all built-in PHP functions. This tutorial is designed for beginners to.


Php Tutorial With Examples Pdf

Author:LAZARO ENGELSMAN
Language:English, Portuguese, French
Country:Thailand
Genre:Biography
Pages:679
Published (Last):08.12.2015
ISBN:731-4-61898-292-7
ePub File Size:26.80 MB
PDF File Size:18.35 MB
Distribution:Free* [*Sign up for free]
Downloads:37023
Uploaded by: LEVI

HTTP and HTML: Berners-Lee's Basics. 2. The Request/Response Procedure. 2. The Benefits of PHP, MySQL, JavaScript, and CSS. 5. Using PHP. 5. MySQL. Presented by developerWorks, your source for great tutorials . Following tradition, we will begin coding with a "hello world" example. .. and PDF files. In our PHP tutorial you will learn about PHP, and how to execute scripts Below, we have an example of a simple PHP script which sends the text "Hello World".

Page 47 of The problem with the code above is that unauthorized users can insert data into the mail headers via the input form. What happens if the user adds the following text to the email input field in the form?

The mail function puts the text above into the mail headers as usual, and now the header has an extra Cc: When the user clicks the submit button, the e-mail will be sent to all of the addresses above! The code below is the same as in the previous chapter, but now we have added an input validator that checks the email field in the form: In the code above we use PHP filters to validate input: An error message with filename, line number and a message describing the error is sent to the browser.

Page 50 of If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. This tutorial contains some of the most common error checking methods in PHP.

We will show different error handling methods: Simple "die " statements Custom errors and error triggers Error reporting. Basic Error Handling: Using the die function The first example shows a simple script that opens a text file: If the file does not exist you might get an error like this: To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it: The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.

However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors. Creating a Custom Error Handler Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP.

This function must be able to handle a minimum of two parameters error level and error message but can accept up to five parameters optionally: Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels. Specifies the filename in which the error occurred Optional. Specifies the line number in which the error occurred. Specifies an array containing every variable, and their values, in use when the error occurred.

Error Report levels These error report levels are the different types of error the user-defined error handler can be used for: Page 52 of Description Non-fatal run-time errors.

The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script. Now that we have created an error handling function we need to decide when it should be triggered. Page 53 of We are going to make the function above the default error handler for the duration of the script. It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways.

However, in this example we are going to use our custom error handler for all errors: Example Testing the error handler by trying to output variable that does not exist: The output of the code above should be something like this: Trigger an Error In a script where users can input data it is useful to trigger errors when an illegal input occurs.

In this example an error occurs if the "test" variable is bigger than "1": Value must be 1 or below in C: An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered. Possible error types: Errors that can not be recovered from. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally.

Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging.

PHP Advanced Tutorials

Sending errors messages to yourself by e-mail can be a good way of getting notified of specific errors. Send an Error Message by E-Mail In the example below we will send an e-mail with an error message and end the script, if a specific error occurs: And the mail received from the code above looks like this: This should not be used with all errors.

Regular errors should be logged on the server using the default PHP logging system. PHP Exception Handling Exceptions are used to change the normal flow of a script if a specified error occurs. Exception handling is used to change the normal flow of the code execution if a specified error exceptional condition occurs.

This condition is called an exception.

This is what normally happens when an exception is triggered: The current code state is saved The code execution will switch to a predefined custom exception handler function Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code We will show different error handling methods: Basic use of Exceptions Creating a custom exception handler Multiple exceptions Page 57 of Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point.

Basic Use of Exceptions When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message. Lets try to throw an exception without catching it: The code above will get an error like this: Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in C: Try, throw and catch To avoid the error from the example above, we need to create the proper code to handle an exception.

Page 58 of Proper exception code should include: Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal.

However if the exception triggers, an exception is "thrown" 2. Throw - This is how you trigger an exception.

Each "throw" must have at least one "catch" 3. Catch - A "catch" block retrieves an exception and creates an object containing the exception information Lets try to trigger an exception with valid code: Example explained: The code above throws an exception and catches it: The checkNum function is created. It checks if a number is greater than 1.

If it is, an exception is thrown Page 59 of The checkNum function is called in a "try" block 3. The exception within the checkNum function is thrown 4. Creating a Custom Exception Class Creating a custom exception handler is quite simple.

We simply create a special class with functions that can be called when an exception occurs in PHP. The class must be an extension of the exception class.

The custom exception class inherits the properties from PHP's exception class and you can add custom functions to it. Lets create an exception class: The new class is a copy of the old exception class with an addition of the errorMessage function.

Since it is a copy of the old class, and it inherits the properties and methods from the old class, we can use the exception class methods like getLine and getFile and getMessage. The code above throws an exception and catches it with a custom exception class: The customException class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class 2. The errorMessage function is created.

This function returns an error message if an e-mail address is invalid 3. The "try" block is executed and an exception is thrown since the email address is invalid 5. The "catch" block catches the exception and displays the error message. Multiple Exceptions It is possible for a script to use multiple exceptions to check for multiple conditions.

It is possible to use several if.. These exceptions can use different exception classes and return different error messages: The code above tests two conditions and throws an exception if any of the conditions are not met: The "try" block is executed and an exception is not thrown on the first condition 5. The second condition triggers an exception since the e-mail contains the string "example" Page 62 of The "catch" block catches the exception and displays the correct error message If there was no customException catch, only the base exception catch, the exception would be handled there.

Re-throwing Exceptions Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way. It is possible to throw an exception a second time within a "catch" block. A script should hide system errors from users. System errors may be important for the coder, but is of no interest to the user. To make things easier for the user you can re-throw the exception with a user friendly message: The code above tests if the email-address contains the string "example" in it, if it does, the exception is re-thrown: The "try" block contains another "try" block to make it possible to rethrow the exception 5.

The exception is triggered since the e-mail contains the string "example" 6. The "catch" block catches the exception and re-throws a "customException" 7.

The "customException" is caught and displays an error message If the exception is not caught in its current "try" block, it will search for a catch block on "higher levels".

Uncaught Exception occurred. In the code above there was no "catch" block. Instead, the top level exception handler triggered. This function should be used to catch uncaught exceptions. Code may be surrounded in a try block, to help catch potential exceptions Each try block or "throw" must have at least one corresponding catch block Multiple catch blocks can be used to catch different classes of exceptions Exceptions can be thrown or re-thrown in a catch block within a try block.

What is a PHP Filter? A PHP filter is used to validate and filter data coming from insecure sources. To test, validate and filter user input or custom data is an important part of any web application. The PHP filter extension is designed to make data filtering easier and quicker. Why use a Filter? Almost all web applications depend on external input. Usually this comes from a user or another application like a web service.

By using filters you can be sure your application gets the correct input type. Page 65 of You should always filter all external data! Input filtering is one of the most important application security issues. What is external data? Input data from a form Cookies Web services data Server variables Database query results. Functions and Filters To filter a variable, use one of the following filter functions: Since the integer is valid, the output of the code above will be: If we try with a variable that is not an integer like "abc" , the output will be: Page 66 of Validating and Sanitizing There are two kinds of filters: Validating filters: Are used to allow or disallow specified characters in a string No data format rules Always return the string.

Options and Flags Options and flags are used to add additional filtering options to the specified filters. Different filters have different options and flags.

Like the code above, options must be put in an associative array with the name "options". If a flag is used it does not need to be in an array. Since the integer is "" it is not in the specified range, and the output of the code above will be: Check each filter to see what options and flags are available.

Validate Input Let's try validating input from a form. The first thing we need to do is to confirm that the input data we are looking for exists. In the example below, the input variable "email" is sent to the PHP page: Check if an "email" input variable of the "GET" type exist 2. If the input variable exists, check if it is a valid e-mail address.

Let's try cleaning up an URL sent from a form. First we confirm that the input data we are looking for exists. In the example below, the input variable "url" is sent to the PHP page: Check if the "url" input of the "POST" type exists 2. Filter Multiple Inputs A form almost always consist of more than one input field.

The received GET variables is a name, an age and an e-mail address: Example Explained The example above has three inputs name, age and email sent to it using the "GET" method: Set an array containing the name of input variables and the filters used on the specified input variables 2.

Page 70 of If the parameter is a single filter ID all values in the input array are filtered by the specified filter. If the parameter is an array it must follow these rules: Must be an associative array containing an input variable as an array key like the "age" input variable The array value must be a filter ID or an array specifying the filter, flags and options.

This way, we have full control of the data filtering. You can create your own user defined function or use an existing PHP function The function you wish to use to filter is specified the same way as an option is specified. What is MySQL? MySQL is a database. The data in MySQL is stored in database objects called tables.

A table is a collections of related data entries and it consists of columns and rows. Databases are useful when storing information categorically. A company may have a database with the following tables: Database Tables A database most often contains one or more tables.

Each table is identified by a name e. Tables contain records rows with data. Below is an example of a table called "Persons": With MySQL, we can query a database for specific information and have a recordset returned.

Look at the following query: The query above selects all the data in the "LastName" column from the "Persons" table, and will return a recordset like this: LastName Hansen Svendson Pettersen. Perhaps it is because of this reputation that many people believe that MySQL can only handle small to medium-sized systems. The truth is that MySQL is the de-facto standard database for web sites that support huge volumes of both data and end users like Friendster, Yahoo, Google.

Look at http: Page 73 of Parameter Description servername Optional. Specifies the server to connect to. Default value is "localhost: Specifies the username to log in with. Default value is the name of the user that owns the server process Optional. Specifies the password to log in with. Default is "". There are more available parameters, but the ones listed above are the most important. The "die" part will be executed if the connection fails: Closing a Connection The connection will be closed automatically when the script ends.

This function is used to send a query or command to a MySQL connection. Page 75 of The following example creates a table named "Persons", with three columns. Page 76 of A database must be selected before a table can be created.

When you create a database field of type varchar, you must specify the maximum length of the field, e. The data type specifies what type of data the column can hold. A primary key is used to uniquely identify the rows in a table. Each primary key value must be unique within the table.

Furthermore, the primary key. The following example sets the personID field as the primary key field. The first form doesn't specify the column names where the data will be inserted, only their values: The second form specifies both the column names and the values to be inserted: In the previous chapter we created a table named "Persons", with three columns; "Firstname", "Lastname" and "Age". We will use the same table in this example. The following example adds two new records to the "Persons" table: Here is the HTML form: When a user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.

The "insert. Here is the "insert.

Forcing a Download Using PHP

The while loop loops through all the records in the recordset. Page 81 of If you want to sort the records in a descending order, you can use the DESC keyword.

The following example selects all the data stored in the "Persons" table, and sorts the result by the "Age" column: Order by Two Columns It is also possible to order by more than one column. When ordering by more than one column, the second column is only used if the values in the first column are equal: Earlier in the tutorial we created a table named "Persons".

Here is how it looks: The following example updates some data in the "Persons" table: After the update, the "Persons" table will look like this: Look at the following "Persons" table: After the deletion, the table will look like this: Open the Administrative Tools icon in your Control Panel.

Choose the System DSN tab. Select the Microsoft Access Driver. Click Finish. In the next screen, click Select to locate the database. Click OK. Note that this configuration has to be done on the computer where your web site is located. If you are running Internet Information Server IIS on your own computer, the instructions above will work, but if your web site is located on a remote server, you have to have physical access to that server, or ask your web host to to set up a DSN for you to use.

The function takes four parameters: The following example creates a connection to a DSN called northwind, with no username and no password.

It then creates an SQL and executes it: This function returns true if it is able to return rows, otherwise false. The function takes two parameters: This function takes two parameters: The code line below returns the value of the first field from the record: The code line below returns the value of a field called "CompanyName": What is XML? XML is used to describe data and to focus on what data is.

An XML file describes the structure of the data. In XML, no tags are predefined. You must define your own tags. What is Expat? There are two basic types of XML parsers:. Tree-based parser: This parser transforms an XML document into a tree structure. It analyzes the whole document, and provides access to the tree elements. Views an XML document as a series of events.

When a specific event occurs, it calls a function to handle it Page 91 of The Expat parser is an event-based parser. Event-based parsers focus on the content of the XML documents, not their structure.

Because of this, event-based parsers can access data faster than tree-based parsers. Look at the following XML fraction: However, this makes no difference when using the Expat parser. Expat is a non-validating parser, and ignores any DTDs. XML documents must be well-formed or Expat will generate an error. There is no installation needed to use these functions. Tove From: Jani Heading: Reminder Message: Don't forget me this weekend! How it works: Create functions to use with the different event handlers 3.

Parse the file "test. What is DOM? It analyzes the whole document, and provides access to the tree elements Event-based parser: When a specific event occurs, it calls a function to handle it.

The DOM parser is an tree-based parser. Look at the following XML document fraction: Level 1: XML Document Level 2: Root element: Text element: Tove Jani Reminder Don't forget me this weekend!

In the example above you see that there are empty text nodes between each element. When XML generates, it often contains white-spaces between the nodes. The XML DOM parser treats these as ordinary elements, and if you are not aware of them, they sometimes cause problems. Page 97 of What is SimpleXML? It is an easy way of getting an element's attributes and text, if you know the XML document's layout.

When there's more than one element on one level, they're placed inside an array Attributes - Are accessed using associative arrays, where an index corresponds to the attribute name Element Data - Text data from elements are converted to strings.

If an element has more than one text node, they will be arranged in the order they are found SimpleXML is fast and easy to use when performing basic tasks like: Installation As of PHP 5. We want to output the element names and data from the XML file above. Here's what to do: Load the XML file 2. Get the name of the first element 3. Create a loop that will trigger on each child node, using the children function 4.

Reminder body: AJAX is not a new programming language, but simply a new technique for creating better, faster, and more interactive web applications. The AJAX technique makes web pages more responsive by exchanging data with the web server behind the scenes, instead of reloading an entire web page each time a user makes a change. AJAX applications are browser and platform independent. Cross-Platform, Cross-Browser technology. Web applications have many benefits over desktop applications: AJAX is based on open standards.

These standards have been used by most developers for several years.

Online PHP Tutorial pdf, what is php, PHP MYSQL Online Courses, Classes, Training

After the web server has processed the data, it will return a completely new web page to the user. Because the server returns a new web page each time the user submits input, traditional web applications often run slowly and tend to be less user friendly.

With AJAX, web applications can send and retrieve data without reloading the whole web page. This is done by sending HTTP requests to the server behind the scenes , and by modifying only parts of the web page using JavaScript when the server returns data. XML is commonly used as the format for receiving server data, although any format, including plain text, can be used.

You will learn more about how this is done in the next chapters of this tutorial. There is no such thing as an AJAX server. AJAX is a technology that runs in your browser. It uses asynchronous data transfer HTTP requests between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. AJAX is a web browser technology independent of web server software. It has been available ever since Internet Explorer 5.

Internet Explorer uses an ActiveXObject. Here is the simplest code you can use to overcome this problem: Example above explained: Set the value to null. Then test if the object window. XMLHttpRequest is available. This object is available in newer versions of Firefox, Mozilla, Opera, and Safari.

If it's available, use it to create a new object: If it's not available, test if an object window. ActiveXObject is available. This object is available in Internet Explorer version 5. If it is available, use it to create a new object: A Better Example? The example below tries to load Microsoft's latest version "Msxml2. Try to create the object according to web standards Mozilla, Opera and Safari: Try to create the object the Microsoft way, available in Internet Explorer 6 and later: If this catches an error, try the older Internet Explorer 5.

This example consists of three pages: The form works like this: An event is triggered when the user presses, and releases a key in the input field 2. When the event is triggered, a function called showHint is executed. This is used as a placeholder for the return data of the showHint function. This function executes every time a character is entered in the input field. If there is some input in the text field str.

Defines the url filename to send to the server 2. Adds a parameter q to the url with the content of the input field 3. Adds a random number to prevent the server from using a cached file 4. Sends an HTTP request to the server If the input field is empty, the function simply clears the content of the txtHint placeholder. When the state changes to 4 or to "complete" , the content of the txtHint placeholder is filled with the response text. The code above called a function called GetXmlHttpObject.

This is explained in the previous chapter. Page of The code in the "gethint. Find a name matching the characters sent from the JavaScript 2. If more than one name is found, include all names in the response string 3. If no matching names were found, set response to "no suggestion" 4.

If one or more matching names were found, set response to these names 5. The response is sent to the "txtHint" placeholder. Select a CD: The paragraph below the form contains a div called "txtHint". The div is used as a placeholder for info retrieved from the web server.

When the user selects data, a function called "showCD" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user changes the value in the drop down box, the function showCD is called. This document contains a CD collection. Example Explained The stateChanged and GetXmlHttpObject functions are the same as in the last chapter, you can go to the previous page for an explanation of those The showCD Function If an item in the drop down box is selected the function executes the following: Defines the url filename to send to the server 3.

Adds a parameter q to the url with the content of the input field 4. Adds a random number to prevent the server from using a cached file 5. Call stateChanged when a change is triggered 6. Sends an HTTP request to the server. The CD containing the correct artist is found 4. The album information is output and sent to the "txtHint" placeholder. The Database The database we will be using in this example looks like this: When the user selects data, a function called "showUser " is executed.

Each time the user changes the value in the drop down box, the function showUser is called. The showUser Function If an item in the drop down box is selected the function executes the following: Adds a parameter q to the url with the content of the dropdown box 4. The "user" with the specified name is found 3.

A table is created and the data is inserted and sent to the "txtHint" placeholder. Receiving the response as an XML document allows us to update this page several places, instead of just receiving a PHP output and displaying it.

This example consists of four elements: The HTML form is a drop down box called "users" with names and the "id" from the database as option values. The stateChanged Function If an item in the drop down box is selected the function executes the following: Defines the "xmlDoc" variable as an xml document using the responseXML function 2.

Mon, 26 Jul The PHP document is set to "no-cache" to prevent caching 3. The "user" with the specified id is found 6. The data is outputted as an xml document. Live search has many benefits compared to traditional searching: Matching results are shown as you type Results narrow as you continue typing If results become too narrow, remove characters to see a broader result. This example consists of four pages: In this example the results are found in an XML document links.

To make this example small and simple, only eight results are available. When the event is triggered, a function called showResult is executed. This is used as a placeholder for the return data of the showResult function. The JavaScript code is stored in "livesearch. The showResult Function This function executes every time a character is entered in the input field.

If there is no input in the text field str. However, if there is any input in the text field the function executes the following: When the state changes to 4 or to "complete" , the content of the txtHint placeholder is filled with the response text, and a border is set around the return field. The code in the "livesearch. If more than one match is found, all matches are added to the variable 4.

Top msnbc. Uneasy alliance behind Gaza strikes The Israeli campaign on Gaza is being led by an unlikely group of three Israeli leaders who have all but staked their political futures on the highly risky military operation. Blagojevich makes Senate pick Defying U. Senate leaders and his own state's lawmakers, Gov. Israel mulls halt in Gaza strikes Israel is considering halting its Gaza offensive temporarily to give Hamas militants an opening to halt rocket fire on Israel, an Israeli defense official said Tuesday.

An event is triggered when the user selects an option in the drop down box 2. When the event is triggered, a function called showRSS is executed. This is used as a placeholder for the return data of the showRSS function. The showRSS Function Every time an option is selected in the input field this function executes the following: Adds a parameter q to the url with the selected option from the drop down box 3.

The elements from the RSS channel are found and outputted 4. The three first elements from the RSS items are looped through and outputted. An event is triggered when the user selects the "yes" or "no" option 2. When the event is triggered, a function called getVote is executed. When the data is returned from the getVote function, the return data will replace the form.

It is stored like this: The first number represents the "Yes" votes, the second number represents the "No" votes.

Remember to allow your web server to edit the text file. The getVote Function Page of This function executes when "yes" or "no" is selected in the HTML form. Defines the url filename to send to the server Adds a parameter vote to the url with the content of the input field Adds a random number to prevent the server from using a cached file Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object to execute a function called stateChanged when a change is triggered 5.

Sends an HTTP request to the server 1. Open up your web browser and in the address bar, type localhost. If it's the first time you run it, it will ask what language would you prefer, just simply pick and it will lead you to the menu. Now let's try running the website you just placed. It should be the same as the picture below. If you will notice that the URL is MyFirstWebsite, it is derived from the htdocs folder and it automatically reads files that are named "index" Be it index.

You can also create your custom name for the URL by simply renaming the folder but let's just stick to MyFirstWebsite. Note: If you don't have a file named index and you entered the URL, you will receive an error for not having the file on the server.

If you do have different files that are not named index. Creating the public HTML Pages Next, let's re-modify our website and add a registration link where our users can register as well as a Log-in page right after getting registered. Let's modify our home page with the following code: index. Let's create the registration page first: register.

Now for the login page: Hint: Just copy-paste the same code to make things faster. Click here for the complete login. Creating the database and it's tables Now that we have our basic page for the public.

Let's proceed to the database. Just leave the Collation as is. You have just successfully created your first database. Now from there, let's create a table wherein we can register our users and display information. Adding users to the database Now that we have our tables. Let's move on to the fun part, getting your registration page into action. From your registration.

Click here for the form method reference. This just simply gets the input based on the name from the form. In our case it's username and password. This ensures that your strings don't escape from unnecessary characters.

Click here to learn more about SQL Injections. Now try to go to your register.

PHP-Tutorial(w3schools).pdf

In my case I placed in the username xtian and password as It should display the inputs below. Here's my sample: On this part, you should have understood on how to get input from the form. Now to add it to the database. On your register.

The default username is root and no password for default. Click here for some SQL query samples. The again, i'm not here to discuss about mySQL. It is placed in a while loop so that it would query all rows.

Take note that only 1 row is queried per loop that's why a while loop is necessary. It is represented as an array. Try the inputs that you have made earlier and see what happens. It should prompt that you have successfully registered. Try going to phpmyadmin and see your users table: Congratulations! Now you know how to add data into the database with data validations.

User log-in: Authentication Now for the login page. Let's create a new file called checklogin. The reason is going back to our login. If you will notice on the register.Pao Hinojosa.

Why PHP? The most classic way and often taken as reference for i18n and l10n is a Unix tool called gettext.

If you do not supply a timestamp, the current time will be used. In this example an error occurs if the "test" variable is bigger than "1": This way, we have full control of the data filtering. Abhilash Sahoo. AJAX is a web browser technology independent of web server software. Now from there, let's create a table wherein we can register our users and display information.

GAYLE from Athens
I fancy sharing PDF docs unbearably. Look over my other articles. I am highly influenced by limited overs cricket.
>