PHP Tutorial

PHP stands for "PHP: Hypertext Preprocessor". It is a widely-used Open Source general-purpose scripting language especially suited for web development. It can be embedded into HTML. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP.

What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was.

Complete PHP Guide

PHP is a server-side programming language used for creating dynamic web sites and interactive web applications. The acronym PHP originally stood for Personal Home Page, but as its functionality grew, this was changed to PHP: Hypertext Preprocessor.

The function uses Document Object Model to get array of HTML elements of any particular tag element from the HTML. You can also get values from specific tags that have particular attribute and value.

PHP provides an error-handling class called Exception. PHP 5 introduced new object oriented way of dealing with errors. 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.

PHP tries to be helpful when problems arise. It provides different types of error messages and warnings with as much information as possible. An understanding of errors will help you quickly recognize where problems exist in your code, which will lend to faster debugging and understanding where to look for problems.

You cannot have two classes with the same name, since PHP would not know which one is being referred to when creating a new object. To solve this issue, PHP allows the use of namespaces, which act as paths in a file system. In this way, you can have as many classes with the same name as you need, as long as they are all defined in different namespaces.

Cookies and sessions are mechanisms to store and use information from any page on your site. A cookie is a small file kept on the client's computer that can be used to store data relating to that user.

Superglobals were introduced in PHP 4.1.0. They are built-in variables that are always available in all scopes. You can access them from any function, class or file without having to do anything special.

You can upload files on server using a HTML form and PHP. You can upload any kind of file like images, videos, ZIP files, Microsoft Office documents, PDFs, and other files. The uploaded file can be saved in any folder on permanent basis. You can also implement some basic security check like file type and file size to ensure that users upload the correct file type and within the allowed limit.

The PHP superglobals $_GET and $_POST are used to collect form data submitted by the user. Several predefined variables in PHP are called superglobals. You can access them from any function, class or file without having to do anything special.

PHP provides a method you can use to copy an object. The method is __clone, with two underscores. You can write your own __clone method in a class if you want to specify statements to run when the object is copied. If you don’t write your own, PHP uses its default __clone method that copies all the properties as is.

It is common in PHP to process user-supplied data. Such data needs to be tested before it is used to confirm that it exists and has a valid value. PHP provides a number of built-in constructs that can be used for this purpose.

The constructor is a special method, added with PHP 5, that is executed when an object is created. A constructor isn’t required, and you don’t need to use a constructor if you don’t want to set any property values or perform any actions when the object is created. Only one constructor is allowed.

In order to use a class, you need to include the file that defines it. Autoloading is a PHP feature that allows your program to search and load files automatically given some set of predefined rules. Each time you reference a class that PHP does not know about, it will ask the autoloader.

In order to write PHP code, you have to start the file with <?php. You can also finish the file or PHP code with ?>. You can mix PHP code with other content, like HTML, CSS, or JavaScript, in your PHP file as soon as you enclose the PHP bits with the <?php and ?> tags.

An abstract class provides a partial implementation that other classes can build upon. When a class is declared as abstract, it means that the class can contain incomplete methods that must be implemented in child classes, in addition to normal class members.

PHP constants are similar to variables. Constants are given a name, and a value is stored in them. However, they can’t be changed by the script. After you set the value for a constant, it stays the same. For example, if you used a constant for age and set it to 21, the value is always and forever 21.

In a normal class, all the properties and methods are linked to a specific instance. So, two different instances could have two different values for the same property. PHP allows you to have properties and methods linked to the class itself rather than to the object. These properties and methods are defined with the keyword static.

Inheritance allows a class to acquire the members of another class. For example, the Square class inherits from Rectangle, specified by the extends keyword. Rectangle then becomes the parent class of Square, which in turn becomes a child class of Rectangle.

At their simplest, objects are data types. You can compare objects with the equal operator, which is two equal signs (==), or with the identical operator, which is three equal signs (===).

Using the equal operator, two objects are equal if they are created from the same class and have the same properties and values. However, using the identical operator, two objects are identical only if they refer to the same instance of the same class.

The class is the template or pattern for the object. You write the class statement to define the properties and methods for the class. A class is defined by the keyword class followed by a valid class name and a block of code.

A function is a reusable block of code that, given an input, performs some actions and, optionally, returns some result. Applications often perform the same task at different points in the script or in different scripts.

Loops are control structures that allow you to execute certain statements several times, as many times as you need. Loops are used frequently in scripts to set up a block of statements that repeat. The loop can repeat a specified number of times. The most common use is when interacting with arrays. For example, imagine you have an array with elements, but you do not know what is in it. You want to print all its elements, so you loop through all of them.

Almost all the programs require evaluating conditions using if/else and switch/case statements. If-Else statements are easy to code and global to all languages. However, they can be too long. The ternary operator (?:) can replace a single if/else clause.

Conditional statements are used to execute different code blocks based on different conditions.A conditional evaluates a Boolean expression, that is, something that returns a value. If the expression is true, it will execute everything inside its block of code. A block of code is a group of statements enclosed by {}.

An array is used to store a collection of values in a single variable. Arrays in PHP consist of key-value pairs. The key can either be an integer (numeric array) or as a string (associative array). The value can be any data type.

Strings are concatenations or series of characters that you cannot see at once when searching for something. Instead, you have to look one by one and keep track of what the content is. PHP has many predefined functions that help you in interacting with strings. Characters are letters, numbers, and punctuation. When a number is used as a character, it is just a stored character, the same as a letter. It can't be used in arithmetic.

Operators are symbols that take some expressions, operands, and perform mathematical or logical actions on them to get a result. An expression is almost anything that has a value. Variables, numbers, or text are examples of expressions. Operators expect expressions of a specific type, for example, arithmetic operators expect either integers or floats.

Values stored in a variable or in a constant are stored as a specific type of data. PHP provides eight data types.

Variables are used for storing data, such as numbers or strings, so that they can be used multiple times in a script. A variable has a name, and information is stored in the variable.

For example, you might name a variable $age and store the number 12 in it. Information stored in a variable can be used later in the script. This value can change if you want it to; that is why they are called variables.

Comments are used to insert notes into the code. They have no effect on the parsing of the script. Adding comments in your scripts that describe their purpose and what they do is essential. You might need to revise the script next year when the details are long buried in your mind under thoughts of more recent projects.

PHP is a server-side language, which means it runs on the server before anything is sent to the user’s computer. This is in contrast to client-side languages, where the code is sent to the user's computer to be processed locally with languages like JavaScript.

Web applications can become more complex. The more functionality you add, the more difficult the code is to maintain and understand. It is for this reason that structuring your code in an organized way is crucial.

Websites try to format their URLs to make them easier to remember instead of depending on the file that should handle that request. Also, all the requests go through the same file, index.php, regardless of their path. Because of this, we need to keep a map of the URL paths, and who should handle them.

Clean Form Data

The first thing is to pass all variables through PHP's htmlspecialchars() function. The htmlspecialchars() function converts special characters to HTML entities. If a user tries to enter some code in the form, it will not be executed and is now safe to be displayed on a page or inside an e-mail.

PHP DOM (Document Object Model) Parser is very good at dealing with XML and HTML. It travels based on tree-structure and loads the data into DOM object. The first thing you need to do is to construct a dom document object and then load the html content in it.

You can connect to an email inbox using PHP’s IMAP functions. First, you need to open an IMAP stream to a mailbox.

An associative array is composed of a collection of key and value pairs. Indexed array is an array with a numeric key.

You can display a 2 dimensional array in PHP as a HTML table using nested foreach loop. For example, this is useful when you get rows of information from MySQL, and then you need to display its output as a table.

If you want all the visitor on the webpage to redirect to, this can be done using several methods using PHP, JavaScript and HTML.

Calculating the difference between two dates is not as easy as it sounds. There are a lot of things that can go wrong if you are not careful. For example, you have to take both leap years and daylight saving time into consideration. Simply converting two dates to a timestamp and subtracting the values is not reliable in all cases. The PHP DateTime class takes care of all this.

Many times, you have to programmatically resize images. Maybe you have to create multiple sizes of the same image to serve on different devices. Maybe you need to resize images that your users are uploading. You can make use of the PHP’s GD library to resize images in PHP. GD has all the necessary functions to manipulate images so you won’t have to use any other 3rd party library.

All these functions are used to manipulate strings. They are part of the PHP core, so you don't have to install anything to use these functions.

Many times, the strings have extra spaces that need to be removed. For example, you might want to replace multiple spaces with a single space or you might want to get rid of all the whitespace in a string. Similarly, you might be planning on stripping all the whitespace from either the left or the right end of a string.

Random values are very important in many situations. Random values can be used to generate strings for passwords, quotes, and CAPTCHAs. They can also be used for grabbing random numbers for games and other purposes.

The substr() function returns a part of a string.

cURL means client URL. It allows you to connect with other URLs and use their responses in your code.

The explode() function in PHP is used to split a string into multiple strings based on the specified delimiter. It is similar to the split function in Perl.

The strlen() function returns the length of a given string. It returns 0 if the string is empty.

If you need to display some HTML code on the browser, first you need to convert it into HTML entities. Otherwise, the code will be processed by the PHP. For example, instead of <bold> output, the text itself will become bold.

You can use the array_shift() function to remove the first element or value from an array. The array_shift() function returns the removed first value of array. If the array is empty (or the variable is not an array), the returned value is NULL.