PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
PHP 7 is the latest stable release.
This is the BASIC levels, required for starting working on basic levels at SmartinfoLogiks
Before proceeding with this tutorial you should have at least basic understanding of computer programming, Internet, Database, and MySQL etc is very helpful.
Level 1
- Core PHP
- MD5, SHA1
Level 2
- Error and Exceptions
- Form Handling (Submit, HTML5 Validation, Input Type)
- PHP Server, Sessions, Globals, Cookies
- PHP post, get, [=
- PHP AJAX, XML, JSON, Array
Level 3
- File Handling
- PHP mysql, cache
- PHP CURL, EMails
- PHP regex
- Cookie Handling
Level 4
- PHP Design patterns (Singleton, Factory, Strategy, Model View Control, SRTP)
- Callback
Please refer to below links for study and reference purpose
Artical Updated By Harshal on 06-09-2021 Artical Updated By Harshal on 02-11-2021
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases.
PHP is basically used for developing web based software applications. This tutorial helps you to build your base with PHP.
- PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.
- PHP is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning PHP:
- PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
- PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites.
- It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
- PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time.
- PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time.
- PHP is forgiving: PHP language tries to be as forgiving as possible.
- PHP Syntax is C-Like.
Five important characteristics make PHP's practical nature possible −
- Simplicity
- Efficiency
- Security
- Flexibility
- Familiarity
Basic PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to output the text "Hello World!" on a web page:
Example
PHP Case Sensitivity
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not case-sensitive.
Comments
A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is to be read by someone who is looking at the code.
Comments can be used to:
Let others understand your code Remind yourself of what you did - Most programmers have experienced coming back to their own work a year or two later and having to re-figure out what they did. Comments can remind you of what you were thinking when you wrote the code.
(// This is a single-line comment) (# This is also a single-line comment) (/This is a multiple-lines comment block that spans over multiple lines/)
PHP Variables
Creating (Declaring) PHP Variables In PHP, a variable starts with the $ sign, followed by the name of the variable:
<?php $txt = "Hello world!"; $x = 5; $y = 10.5; ?>
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable A variable name must start with a letter or the underscore character A variable name cannot start with a number A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case-sensitive ($age and $AGE are two different variables)
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
local global static
PHP echo and print Statements
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.
echo example-
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
echo $txt1 ;
echo "Study PHP at " . $txt2 ;
echo $x + $y;
print PHP is Fun!";
print "Hello world!";
print "I'm about to learn PHP!";
?>
PHP Data Types
Variables can store data of different types, and different data types can do different things.
PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can be categorized further in 3 types:
Scalar Types (predefined)
- boolean
- integer
- float
- string
Compound Types (user-defined)
- array
- object
Special Types
- resource
- NULL
PHP String Functions In this chapter we will look at some commonly used functions to manipulate strings.
- addcslashes( ) It is used to return a string with backslashes.
- addslashes( ) It is used to return a string with backslashes.
- bin2hex( ) It is used to converts a string of ASCII characters to hexadecimal values.
- chop( ) It removes whitespace or other characters from the right end of a string
- chr( ) It is used to return a character from a specified ASCII value.
- chunk_split( ) It is used to split a string into a series of smaller parts.
- convert_cyr_string( ) It is used to convert a string from one Cyrillic character-set to another.
- convert_uudecode( ) It is used to decode a uuencoded string.
- convert_uuencode( ) It is used to encode a string using the uuencode algorithm.
- count_chars( ) It is used to return information about characters used in a string.
- crc32( ) It is used to calculate a 32-bit CRC for a string.
- crypt( ) It is used to create hashing string One-way.
- echo( ) It is used for output one or more strings.
- explode( ) It is used to break a string into an array.
- fprint( ) It is used to write a formatted string to a stream.
- get_html_translation_table( ) Returns translation table which is used by htmlspecialchars( ) and htmlentities( ).
- hebrev( ) It is used to convert Hebrew text to visual text.
- hebrevc( ) It is used to convert Hebrew text to visual text and new lines ( ) into < br>.
- hex2bin( ) It is used to convert string of hexadecimal values to ASCII characters.
- htmlentities( ) It is used to convert character to HTML entities.
- html_entity_decode( ) It is used to convert HTML entities to characters.
- htmlspecialchars( ) Converts the special characters to html entities.
- htmlspecialchars_decode( ) Converts the html entities back to special characters.
- Implode( ) It is used to return a string from the elements of an array.
- Join( ) It is the Alias of implode( ) function.
- Levenshtein( ) It is used to return the Levenshtein distance between two strings.
- Lcfirst( ) It is used to convert the first character of a string to lowercase.
- localeconv( ) Get numeric formatting information
- ltrim( ) It is used to remove whitespace from the left side of a string.
- md5( ) It is used to calculate the MD5 hash of a string.
- md5_files( ) It is used to calculate MD5 hash of a file.
- metaphone( ) It is used to calculate the metaphone key of a string.
- money_format( ) It is used to return a string formatted as a currency string.
- nl2br( ) It is used to insert HTML line breaks in front of each newline in a string.
- nl_langinfo( ) Query language and locale information
- number_format( ) It is used to format a number with grouped thousands.
- ord( ) It is used to return ASCII value of the first character of a string.
- parse_str( ) It is used to parse a query string into variables.
- print( ) It is used for output one or more strings.
- printf( ) It is used to show output as a formatted string.
- quoted_printable_decode( ) Converts quoted-printable string to an 8-bit string
- quoted_printable_encode( ) Converts the 8-bit string back to quoted-printable string
- quotemeta( ) Quote meta characters
- rtrim( ) It is used to remove whitespace from the right side of a string.
- setlocale( ) It is used to set locale information.
- sha1( ) It is used to return the SHA-1 hash of a string.
- sha1_file( ) It is used to return the SHA-1 hash of a file.
- similar_text( ) It is used to compare the similarity between two strings.
- Soundex( ) It is is used to calculate the soundex key of a string.
- sprintf( ) Return a formatted string
- sscanf( ) It is used to parse input from a string according to a format.
- strcasecmp( ) It is used to compare two strings.
- strchr( ) It is used to find the first occurrence of a string inside another string.
- strcmp( ) Binary safe string comparison (case-sensitive)
- strcoll( ) Locale based binary comparison(case-sensitive)
- strcspn( ) It is used to reverses a string.
- stripcslashes( ) It is used to unquote a string quoted with addcslashes( ).
- stripos( ) It is used to return the position of the first occurrence of a string inside another string.
- stristr( ) Case-insensitive strstr
- strlen( ) It is used to return the length of a string.
- strncasecmp( ) Binary safe case-insensitive string comparison
- strnatcasecmp( ) It is used for case-insensitive comparison of two strings using a "natural order" algorithm
- strnatcmp( ) It is used for case-sensitive comparison of two strings using a "natural order" algorithm
- strncmp( ) It is used to compare of the first n characters.
- strpbrk( ) It is used to search a string for any of a set of characters.
- strripos( ) It finds the position of the last occurrence of a case-insensitive substring in a string.
- strrpos( ) It finds the length of the last occurrence of a substring in a string.
- strpos( ) It is used to return the position of the first occurrence of a string inside another string.
- strrchr( ) It is used to find the last occurrence of a string inside another string.
- strrev( ) It is used to reverse a string.
- strspn( ) Find the initial length of the initial segment of the string
- strstr( ) Find the occurrence of a string.
- strtok( ) Splits the string into smaller strings
- strtolower( ) Convert the string in lowercase
- strtoupper( ) Convert the strings in uppercase
- strtr( ) Translate certain characters in a string or replace the substring
- str_getcsv( ) It is used to parse a CSV string into an array.
- str_ireplace( ) It is used to replace some characters in a string (case-insensitive).
- str_pad( ) It is used to pad a string to a new length.
- str_repeat( ) It is used to repeat a string a specified number of times.
- str_replace( ) It replaces all occurrences of the search string with the replacement string.
- str_rot13( ) It is used to perform the ROT13 encoding on a string.
- str_shuffle( ) It is used to randomly shuffle all characters in a string.
- str_split( ) It is used to split a string into an array.
- strcoll( ) It is locale based string comparison.
- strip_tags( ) It is used to strip HTML and PHP tags from a string.
- str_word_count( ) It is used to count the number of words in a string.
- substr( ) Return the part of a string
- substr_compare( ) Compares two strings from an offset up to the length of characters. (Binary safe comparison)
- substr_count( ) Count the number of times occurrence of a substring
- substr_replace( ) Replace some part of a string with another substring
- trim( ) Remove whitespace or other characters from the beginning and end of the string.
- ucfirst( ) Make the first character of the string to uppercase
- ucwords( ) Make the first character of each word in a string to uppercase
- vfprintf( ) Write a formatted string to a stream
- vprintf( ) Display the output as a formatted string according to format
- vsprintf( ) It returns a formatted string
- wordwrap( ) Wraps a string to a given number of characters
PHP Operators PHP divides the operators in the following groups:
Arithmetic operators
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power
Assignment operators
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
Comparison operators
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.
Increment/Decrement operators
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
Logical operators
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
String operators
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1
Array operators
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y
PHP Conditional Statements
In PHP we have the following conditional statements:
if statement - executes some code if one condition is true
if (condition) {
code to be executed if condition is true;
}
if...else statement - executes some code if a condition is true and another code if that condition is false`
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
if...elseif...else statement - executes different codes for more than two conditions
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
switch statement - selects one of many blocks of code to be executed
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
--
PHP Loops Loops are used to execute the same block of code again and again, as long as a certain condition is true.
In PHP, we have the following loop types:
while - loops through a block of code as long as the specified condition is true
while (condition is true) {
code to be executed;
}
do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
do {
code to be executed;
} while (condition is true);
for - loops through a block of code a specified number of times
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
foreach - loops through a block of code for each element in an array
foreach ($array as $value) {
code to be executed;
}
PHP Break The break statement can also be used to jump out of a loop.
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
PHP Continue The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
PHP Arrays
Indexed arrays - Arrays with a numeric index
he index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota"); or the index can be assigned manually:
$cars[0] = "Volvo"; $cars[1] = "BMW"; $cars[2] = "Toyota";
Associative arrays - Arrays with named keys
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); or:
$age['Peter'] = "35"; $age['Ben'] = "37"; $age['Joe'] = "43";
Multidimensional arrays - Arrays containing one or more arrays A multidimensional array is an array containing one or more arrays.
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select an element.
For a two-dimensional array you need two indices to select an element For a three-dimensional array you need three indices to select an element
PHP - Sort Functions For Arrays In this chapter, we will go through the following PHP array sort functions:
sort( ) - sort arrays in ascending order
rsort( ) - sort arrays in descending order
asort( ) - sort associative arrays in ascending order, according to the value
ksort( ) - sort associative arrays in ascending order, according to the key
arsort( ) - sort associative arrays in descending order, according to the value
krsort( ) - sort associative arrays in descending order, according to the key
PHP Global Variables - Superglobals
Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
The PHP superglobal variables are:
$_POST
$_GET
$GLOBALS
$_REQUEST
$_SERVER
$_FILES
$_ENV
$_COOKIE
$_SESSION
https://www.splessons.com/lesson/php-global-variables/
What is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe what you are searching for.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text replace operations.
Syntax
In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers.
$exp = "/w3schools/i";
In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.
The delimiter can be any character that is not a letter, number, backslash or space. The most common delimiter is the forward slash (/),
but when your pattern contains forward slashes it is convenient to choose other delimiters such as # or ~.
Regular Expression Functions
PHP provides a variety of functions that allow you to use regular expressions. The preg_match( ), preg_match_all( ) and preg_replace( ) functions are some of the most commonly used ones:
Function Description
preg_match( ) Returns 1 if the pattern was found in the string and 0 if not
preg_match_all( ) Returns the number of times the pattern was found in the string, which may also be 0
preg_replace( ) Returns a new string where matched patterns have been replaced with another string
PHP Cookies https://www.geeksforgeeks.org/php-cookies/
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer.
Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
A cookie is a small file with the maximum size of 4KB that the web server stores on the client computer.
They are typically used to keeping track of information such as a username that the site can retrieve to personalize the page when the user visits the website next time.
A cookie can only be read from the domain that it has been issued from.Cookies are usually set in an HTTP header but JavaScript can also set a cookie directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP,the setcookie( ) function is used.The setcookie( ) function needs to be called prior to any output generated by the script otherwise the cookie will not be set.
Syntax :
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie( ) function requires six arguments in general which are:
Name: It is used to set the name of the cookie.
Value: It is used to set the value of the cookie.
Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t be accessed.
Path: It is used to specify the path on the server for which the cookie will be available.
Domain: It is used to specify the domain for which the cookie is available.
Security: It is used to indicate that the cookie should be sent only if a secure HTTPS connection exists.
PHP Session
PHP session is used to store and pass information from one page to another temporarily (until user close the website).
PHP session technique is widely used in shopping websites where we need to store and pass cart information e.g. username, product code, product name, product price etc from one page to another.
PHP session creates unique user id for each browser to recognize the user and avoid conflict between multiple browsers.
php session working
PHP session_start( ) function
PHP session_start( ) function is used to start the session. It starts a new or resumes existing session. It returns existing session if session is created already. If session is not available, it creates and returns new session.
Best Practices
1)Use Proper naming convension as per behavior ,Use Meaningful, Consistent Naming Conventions
Naming this isn't just for your own good.
There's nothing worse than trying to find your way through some other programmer's nonsensical naming conventions.
Help yourself and others by using names that make sense for your classes and functions.
2)Learn the DRY(Don't Repeat Yourself) Approach
3)Always Use <?php ?>
4)Know the Difference Between Single and Double Quotes
It is more efficient to use single quotes in strings as the parser doesn't have to sift through the code to look for
escaped characters and other things that double quotes allow. Always try to use single quotes whenever possible.
5)Protect your Script From SQL Injection
If you don't escape your characters used in SQL strings, your code is vulnerable to SQL injections.
You can avoid this by either using the mysql_real_escape_string, or by using prepared statements.
6)Don't Copy Extra Variables Some people like to try and make their code more appealing by copying predefined variables to smaller-named variables.
This is redundant and could potentially double the memory of your script. Google Code has bad and good examples of variable usage.
7)Reduce the Number of Database Queries
8)Beware of XSS attacks (Cross-site scripting)
9)Avoid remote file inclusion
10)Remember, documentation matters