- Introduction to PHP
- Introduction to HTML
- HTML5 New Tags
- Style Sheet (CSS)
- Bootstrap (Responsive Design)
- PHP Language Building Blocks
- Conditional Statements
- Introducing ARRAY
- Manipulation User Input
- Reusing Code and Functions
- Object-Oriented PHP
- File System and the Server
- File Uploading & Downloading
- String Manipulation and Regular Expression
- State Management
- MySQL Database
- jQuery with Ajax
- Advance PHP Techniques
PHP: Hypertext Preprocessor (or simply PHP) is a server-side scripting language designed for Web development, but also used as a general-purpose programming language. It was originally created by Rasmus Lerdorf in 1994, the PHP reference implementation is now produced by The PHP Group.PHP originally stood for Personal Home Page, but it now stands for the recursive acronym PHP: Hypertext Preprocessor.
PHP code may be embedded into HTML code, or it can be used in combination with various web template systems, web content management systems, and web frameworks. PHP code is usually processed by a PHP interpreter implemented as a module in the web server or as a Common Gateway Interface (CGI) executable. The web server combines the results of the interpreted and executed PHP code, which may be any type of data, including images, with the generated web page. PHP code may also be executed with a command-line interface (CLI) and can be used to implement standalone graphical applications.
The standard PHP interpreter, powered by the Zend Engine, is free software released under the PHP License. PHP has been widely ported and can be deployed on most web servers on almost every operating system and platform, free of charge.
The PHP language evolved without a written formal specification or standard until 2014, with the original implementation acting as the de facto standard which other implementations aimed to follow. Since 2014 work has gone on to create a formal PHP specification.
Comparing PHP with other Web Scripting Languages or Technology
As different as they are, there are some top-level similarities worth considering, especially if you are comparing a PHP back-end to Node.js.
- Simplicity. PHP is conceptually much simpler to use than Node.js. When setting up a server, all you need is a .php file with some code wrapped between the tags, enter the URL into your browser, and you’re done. The statement you wrap between those tags can be as simple as and it will work. Behind the scenes, a web server like MySQL with PHP installed will be able to interpret the file and display your web page in your browser. Setting up a Node.js server, while not difficult, usually requires more lines of code, and a basic understanding of how closures and callback functions work.
PHP vs Python: Similarities
At first glance, it may seem flawed to compare the two languages originally created for different purposes. However, seemingly different, PHP and Python have a number of common properties that make them popular:
- Both languages are easy to learn (compared to C++, Perl, and others);
- Both languages are accompanied by the extensive and detailed documentation;
- Both languages are open source and can be updated and advanced by users with the purpose of improvement;
- Wide and friendly developer communities facilitate the process of learning and working with PHP and Python;
- Portability and versatility: both languages have IDEs for all the major operating systems.
PHP vs Python: Differences
Naturally, when choosing a language for development, its distinguishing features are the first thing that should be considered.
The first and most important difference between PHP and Python is their orientation. Python is aspect-oriented (separates the program functionality and splits the program into separate modules), while PHP is object-oriented (encapsulates code modules that contain certain functions and data into objects).
Thus, working with Python, the developer creates separate functional modules and then registers the connections between them on the if-then basis. It results in an algorithm that executes this or that program block based on the user’s actions.
Working with PHP means creating an integral code object that has certain properties and executes certain actions depending on the user input.
The syntax of a language is constituted by its fundamental grammatical rules. The main difference between various languages, be they spoken or programming, lays in syntax, and the process of learning a language is by most the study of its grammar.
The PHP’s syntax is almost the same as the syntax of C (due to its origins). When writing the code using this language, curly brackets, additional characters and operators, and other C elements are used. A nice moment in working with PHP is neglect of white spaces during the compilation, which brings additional usability and gives the ability to structure the code into simple logical components. An unpleasant feature of PHP is the incompatibility of the namespace conventions, which is why many developers do not perceive it as a full-fledged programming language. However, this feature is primarily due to the fact that the language initially was designed for the website management.
The syntax of Python, on the contrary, is based on the separation of the code with spaces and tabs, which significantly speeds up the process of coding, but increases the possibility of careless errors. Considering Python, it’s also worth noting the simplicity of commands. In fact, most of the commands in this language are similar to the corresponding words in natural English, which makes it much easier to learn.
The list of secondary PHP and Python differences is as follows:
- Python is considered a more flexible programming language, while PHP is tightly regulated;
- Python uses special packages to load additional libraries, while PHP requires loading them manually;
- Unlike PHP, where assuring the software security requires additional tools, applications written in Python are considered among the safest;
- Although Python supports a graphical user interface and can be used in web development, PHP, originally created to support web applications, is more applicable in this area.
PHP vs Perl: Similarities
- Compiled scripting languages − Both Perl and PHP are scripting languages.This means that they are not used to produce native standalone executables in advance of execution.
- Syntax − PHP’s basic syntax is very close to Perl’s, and both share a lot of syntactic features with C. Code is insensitive to whitespace, statements are terminated by semicolons, and curly braces organize multiple statements into a single block. Function calls start with the name of the function, followed by the actual arguments enclosed in parentheses and separated by commas.
- Dollar-sign variables − All variables in PHP look like scalar variables in Perl: a name with a dollar sign ($) in front of it.
- No declaration of variables − As in Perl, you don.t need to declare the type of a PHP variable before using it.
- Loose typing of variables − As in Perl, variables in PHP have no intrinsic type other than the value they currently hold. You can store either number or string in same type of variable.
- Strings and variable interpolation − Both PHP and Perl do more interpretation of double-quoted strings (“string”) than of singlequoted strings (‘string’).
PHP vs Perl: Differences
- PHP is HTML-embedded − Although it is possible to use PHP for arbitrary tasks by running it from the command line, it is more typically connected to a Web server and used for producing Web pages. If you are used to writing CGI scripts in Perl, the main difference in PHP is that you no longer need to explicitly print large blocks of static HTML using print or heredoc statements and instead can simply write the HTML itself outside of the PHP code block.
- No @ or % variables − PHP has one only kind of variable, which starts with a dollar sign ($). Any of the datatypes in the language can be stored in such variables, whether scalar or compound.
- Arrays versus hashes − PHP has a single datatype called an array that plays the role of both hashes and arrays/lists in Perl.
- Specifying arguments to functions − Function calls in PHP look pretty much like subroutine calls in Perl. Function definitions in PHP, on the other hand, typically require some kind of list of formal arguments as in C or Java which is not the csse in PERL.
- Variable scoping in functions − In Perl, the default scope for variables is global. This means that top-level variables are visible inside subroutines. Often, this leads to promiscuous use of globals across functions. In PHP, the scope of variables within function definitions is local by default.
- No module system as such − In PHP there is no real distinction between normal code files and code files used as imported libraries.
- Break and continue rather than next and last − PHP is more like C langauge and uses break and continue instead of next and last statement.
- No elsif − A minor spelling difference: Perl’s elsif is PHP’s elseif.
- More kinds of comments − In addition to Perl-style (#) single-line comments, PHP offers C-style multiline comments (/* comment */ ) and Java-style single-line comments (// comment).
- Regular expressions − PHP does not have a built-in syntax specific to regular expressions, but has most of the same functionality in its Perl-compatible regular expression functions.
Installation of PHP
To start using PHP, you can:
- Find a web host with PHP and MySQL support
- Install a web server on your own PC, and then install PHP and MySQL
Use a Web Host With PHP Support
If your server has activated support for PHP you do not need to do anything.
Just create some .php files, place them in your web directory, and the server will automatically parse them for you.
You do not need to compile anything or install any extra tools. Because PHP is free, most web hosts offer PHP support.
Set Up PHP on Your Own PC
However, if your server does not support PHP, you must:
- install a web server
- install PHP
- install a database, such as MySQL
The official PHP website (PHP.net) has installation instructions for PHP: http://php.net/manual/en/install.php
Installation on Windows with Apache
To install Apache with PHP 5 on Windows follow the following steps. If your PHP and Apache versions are different then please take care accordingly.
- Download Apache server from www.apache.org/dist/httpd/binaries/win32. You want the current stable release version with the no_src.msi extension. Double-click the installer file to install; C:\Program Files is a common location. The installer will also ask you whether you want to run Apache as a service or from the command line or DOS prompt. We recommend you do not install as a service, as this may cause problems with startup.
- Extract the PHP binary archive using your unzip utility; C:\PHP is a common location.
- Copy some .dll files from your PHP directory to your system directory (usually C:\Windows). You need php5ts.dll for every case. You will also probably need to copy the file corresponding to your Web server module – C:\PHP\Sapi\php5apache.dll. to your Apache modules directory. It’s possible that you will also need others from the dlls subfolder.but start with the two mentioned previously and add more if you need them.
- Copy either php.ini-dist or php.ini-recommended (preferably the latter) to your Windows directory, and rename it php.ini. Open this file in a text editor (for example, Notepad). Edit this file to get configuration directives; At this point, we highly recommend that new users set error reporting to E_ALL on their development machines.
- Tell your Apache server where you want to serve files from and what extension(s) you want to identify PHP files (.php is the standard, but you can use .html, .phtml, or whatever you want). Go to your HTTP configuration files (C:\Program Files\Apache Group\Apache\conf or whatever your path is), and open httpd.conf with a text editor. Search for the word DocumentRoot (which should appear twice) and change both paths to the directory you want to serve files out of. (The default is C:\Program Files\Apache Group\Apache\htdocs.). Add at least one PHP extension directive as shown in the first line of the following code −
LoadModule php5_module modules/php5apache.dll AddType application/x-httpd-php .php .phtml
You may also need to add the following line −
- Stop and restart the WWW service. Go to the Start menu → Settings → Control Panel → Services. Scroll down the list to IIS Admin Service. Select it and click Stop. After it stops, select World Wide Web Publishing Service and click Start. Stopping and restarting the service from within Internet Service Manager will not suffice. Since this is Windows, you may also wish to reboot.
- Open a text editor. Type: . Save this file in your Web server’s document root as info.php.
- Start any Web browser and browse the file.you must always use an HTTP request (http://www.testdomain.com/info.php or http://localhost/info.php or http://127.0.0.1/info.php) rather than a filename (/home/httpd/info.php) for the file to be parsed correctly.
PHP delimiters are nothing but the open close tags to enclose PHP script. PHP code can be parsed if and only if it is enclosed with these delimiters.
There are various set of delimiters to recognize PHP code. These are as listed below.
– It is most probably used delimiters and also preferable, since, PHP code enclosed with in could be recognized with other PHP servers independent of the tag related configuration directives.
– This will also work anywhere, like .
<? … ?> – This is called as PHP short tags which will work based on the value set with short_open_tag directive of PHP configuration file.
, is allowed or not. This PHP language option will be set with ON/OFF values and the default value is ON. When it is set as ON, then it is allowed to use the short form ( is not recommended programming practice. Because, if we launch our code that contains <? and ?> open, close tags, into another PHP server, where the short_open_tag directive is not enabled, then the code will not work on that server.
Though PHP short tags are not portable among different servers, still they are allowed for providing backward compatibility.
This form is used to print something to the browser. For example, a PHP echo statement can be written as follows.
$statement = "PHP Open and Close Tags"; , asp style tags also depends on PHP configuration settings. So, this form of tags is also not preferable to develop PHP projects to be launched in another server, because of the lack of portability.
From the above list of PHP delimiters, short tags and the ASP style delimiters are not recommended a method to represent PHP code, since they are depending on configuration settings.
Even though, is portable, it is also not widely used for avoiding confusion in separating PHP code embedding it while embedding it HTML or XML content.
Variable Initialization with PHP
Variable is a symbol or name that stands for a value. Variables are used for storing values such as numeric values, characters, character strings, or memory addresses so that they can be used in any part of the program.
Declaring PHP variables
All variables in PHP start with a $ (dollar) sign followed by the name of the variable.
A valid variable name starts with a letter (A-Z, a-z) or underscore (_), followed by any number of letters, numbers, or underscores.
If a variable name is more than one word, it can be separated with an underscore (for example $employee_code instead of $employeecode).
'$' is a special variable that can not be assigned.
Variable initialization means assigning a value to a variable.
Here, first line $x; is the declaration part. The variable is declared but its value is not assigned. The corresponding value of $x is assigned in fourth line of the program. This step, assigning variable to a variable is known as initialization. In many of the case declaration and initialization is in same step such as given in below example.
PHP Data Types
Variables can store data of different types, and different data types can do different things
PHP supports the following data types:
- Float (floating point numbers – also called double)
A string is a sequence of characters, like “Hello world!”.
A string can be any text inside quotes. You can use single or double quotes:
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
- An integer must have at least one digit
- An integer must not have a decimal point
- An integer can be either positive or negative
- Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based – prefixed with 0x) or octal (8-based – prefixed with 0)
- In the following example $x is an integer. The PHP var_dump() function returns the data type and value:
A float (floating point number) is a number with a decimal point or a number in exponential form.
In the following example $x is a float. The PHP var_dump() function returns the data type and value:
A Boolean represents two possible states: TRUE or FALSE.
$x = true; $y = false;
Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of this tutorial.
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type and value:
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword. A class is a structure that can contain properties and methods:
PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:
A constant is a name or an identifier for a simple value. A constant value cannot change during the execution of the script. By default, a constant is case-sensitive. By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.
To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name. Unlike with variables, you do not need to have a constant with a $. You can also use the function constant() to read a constant’s value if you wish to obtain the constant’s name dynamically.
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It is stored in a variable or returned by a function.
Only scalar data (boolean, integer, float and string) can be contained in constants.
Differences between Constants and Variables are
- There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign.
- Constants cannot be defined by simple assignment, they may only be defined using the define() function.
- Constants may be defined and accessed anywhere without regard to variable scoping rules.
- Once the Constants have been set, may not be redefined or undefined.
Valid and invalid Constant Names
// Valid constant names define("ONE", "first thing"); define("TWO2", "second thing"); define("THREE_3", "third thing"); // Invalid constant names define("2TWO", "second thing"); define("__THREE__", "third value");
PHP Magic Constants
PHP provides a large number of predefined constants to any script which it runs.
There are five magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it’s used on in your script. These special constants are case-insensitive and are as follows −
A few magical PHP constants are given below –
|Sr.No||Name & Description|
The current line number of the file.
The full path and filename of the file. If used inside an include,the name of the included file is returned. Since PHP 4.0.2, __FILE__always contains an absolute path whereas in older versions it contained relative path under some circumstances.
The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. PHP language supports following type of operators.
- Arithmetic Operators
- Comparison Operators
- Logical (or Relational) Operators
- Assignment Operators
- Conditional (or ternary) Operators
Lets have a look on all operators one by one.
There are following arithmetic operators supported by PHP language −
Assume variable A holds 10 and variable B holds 20 then –
|+||Adds two operands||A + B will give 30|
|–||Subtracts second operand from the first||A – B will give -10|
|*||Multiply both operands||A * B will give 200|
|/||Divide numerator by de-numerator||B / A will give 2|
|%||Modulus Operator and remainder of after an integer division||B % A will give 0|
|++||Increment operator, increases integer value by one||A++ will give 11|
|—||Decrement operator, decreases integer value by one||A– will give 9|
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then –
|==||Checks if the value of two operands are equal or not, if yes then condition becomes true.||(A == B) is not true.|
|!=||Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.||(A != B) is true.|
|>||Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.||(A > B) is not true.|
|<||Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.||(A < B) is true.|
|>=||Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.||(A >= B) is not true.|
|<=||Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.||(A <= B) is true.|
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then –
|and||Called Logical AND operator. If both the operands are true then condition becomes true.||(A and B) is true.|
|or||Called Logical OR Operator. If any of the two operands are non zero then condition becomes true.||(A or B) is true.|
|&&||Called Logical AND operator. If both the operands are non zero then condition becomes true.||(A && B) is true.|
|||||Called Logical OR Operator. If any of the two operands are non zero then condition becomes true.||(A || B) is true.|
|!||Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.||!(A && B) is false.|
There are following assignment operators supported by PHP language −
|=||Simple assignment operator, Assigns values from right side operands to left side operand||C = A + B will assign value of A + B into C|
|+=||Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand||C += A is equivalent to C = C + A|
|-=||Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand||C -= A is equivalent to C = C – A|
|*=||Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand||C *= A is equivalent to C = C * A|
|/=||Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand||C /= A is equivalent to C = C / A|
|%=||Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand||C %= A is equivalent to C = C % A|
There is one more operator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax −
|?:||Conditional Expression||If Condition is true ? Then value X : Otherwise value Y|
All the operators we have discussed above can be categorised into following categories −
- Unary prefix operators, which precede a single operand.
- Binary operators, which take two operands and perform a variety of arithmetic and logical operations.
- The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.
- Assignment operators, which assign a value to a variable.
Precedence of PHP Operators
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
|Unary||! ++ —||Right to left|
|Multiplicative||* / %||Left to right|
|Additive||+ –||Left to right|
|Relational||< <= > >=||Left to right|
|Equality||== !=||Left to right|
|Logical AND||&&||Left to right|
|Logical OR||||||Left to right|
|Conditional||?:||Right to left|
|Assignment||= += -= *= /= %=||Right to left|
The points below summarizes the topic above:
- PHP is conceptually much simpler to use than Node.js.
- Python is aspect-oriented while PHP is object-oriented.
- PHP is free, most web hosts offer PHP support.
- PHP code can be parsed if and only if it is enclosed with these delimiters.
- By default, a constant is case-sensitive.