The latest version of PHP is 7.1.0 released at December 1, 2016 .
PHP is an open source server side scripting language used to develop dynamic websites . PHP stands for Hypertext Preprocessor , also stood for Personal Home Page . Now the implementations of PHP is produced by The PHP group .It was created by Rasmus lerdorf in 1995 . It is a free software released under the PHP license .
Die() first terminate the script and then print message. Exit() first print message and then terminate the script. if you comment to die() statement then exit also print
In PHP == is equal operator and returns TRUE if $a is equal to $b after type juggling and === is Identical operator and return TRUE if $a is equal to $b, and they are of the same data type.
<?php
$a=true ;
$b=1;
// Below condition returns true and prints a and b are equal
if($a==$b){
echo "a and b are equal";
}else{
echo "a and b are not equal";
}
//Below condition returns false and prints a and b are not equal because $a and $b are of different data types.
if($a===$b){
echo "a and b are equal";
}else{
echo "a and b are not equal";
}
?>
As HTTP is a stateless protocol. To maintain states on the server and share data across multiple pages PHP session are used. PHP sessions are the simple way to store data for individual users/client against a unique session ID. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data, if session id is not present on server PHP creates a new session, and generate a new session ID.
Example Usage:-
<?php
// starting a session
session_start();
// Creating a session
$_SESSION['user_info'] = ['user_id' =>1,
'first_name' =>
'Ramesh', 'last_name' =>
'Kumar', 'status' =>
'active'];
// checking session
if (isset($_SESSION['user_info']))
{
echo "logged In";
}
// un setting remove a value from session
unset($_SESSION['user_info']['first_name']);
// destroying complete session
session_destroy();
?>
In PHP 5.3 or below we can register a variable session_register() function.It is deprecated now and we can set directly a value in $_SESSION Global.
<?php
// Starting session
session_start();
// Use of session_register() is deprecated
$username = "PhpScots";
session_register("username");
// Use of $_SESSION is preferred
$_SESSION["username"] = "PhpScots";
?>
PHP sessions are stored on server generally in text files in a temp directory of server. That file is not accessible from outside word. When we create a session PHP create a unique session id that is shared by client by creating cookie on clients browser.That session id is sent by client browser to server each time when a request is made and session is identified. The default session name is ?PHPSESSID?.
Default session time in PHP is 1440 seconds (24 minutes) and Default session storage path is temporary folder/tmp on server.
You can change default session time by using below code
<?php
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
?>
In PHP all functions starting with __ names are magical functions/methods. Magical methods always lives in a PHP class.The definition of magical function are defined by programmer itself. Here are list of magic functions available in PHP __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo() .
Include :-Include is used to include files more than once in single PHP script.You can include a file as many times you want.
Syntax:- include(?file_name.php?);
Include Once:-Include once include a file only one time in php script.Second attempt to include is ignored.
Syntax:- include_once(?file_name.php?);
Require:-Require is also used to include files more than once in single PHP script.Require generates a Fatal error and halts the script execution,if file is not found on specified location or path.You can require a file as many time you want in a single script.
Syntax:- require(?file_name.php?);
Require Once :-Require once include a file only one time in php script.Second attempt to include is ignored. Require Once also generates a Fatal error and halts the script execution ,if file is not found on specified location or path.
Syntax:- require_once(?file_name.php?);
PHP constructor and a destructor are special type functions which are automatically called when a PHP class object is created and destroyed. Generally Constructor are used to intializes the private variables for class and Destructors to free the resources created /used by class .
<?php
class Foo {
private $name;
private $link;
public function __construct($name) {
$this->name = $name;
}
public function setLink(Foo $link){
$this->link = $link;
}
public function __destruct() {
echo 'Destroying: ', $this->name, PHP_EOL;
}
}
?>
PHP supports 9 primitive types
4 scalar types:
integer
boolean
float
string
3 compound types:
array
object
callable
And 2 special types:
resource
NULL
In PHP Type hinting is used to specify the excepted data type of functions argument.
Type hinting is introduced in PHP 5.
Example usage:-
//send Email function argument $email Type hinted of Email Class. It means to call this function you must have to pass an email object otherwise an error is generated.
<?php
function sendEmail (Email $email)
{
$email->send();
}
?>
The default max execution time for PHP scripts is set to 30 seconds. If a php script runs longer than 30 seconds then PHP stops the script and reports an error.
You can increase the execution time by changing max_execution_time directive in your php.ini file or calling ini_set(?max_execution_time?, 300); //300 seconds = 5 minutes function at the top of your php script.
In PHP @ is used to suppress error messages.When we add @ before any statement in php then if any runtime error will occur on that line, then the error handled by PHP
There are 13 types of errors in PHP, We have listed all below
E_ERROR: A fatal error that causes script termination.
E_WARNING: Run-time warning that does not cause script termination.
E_PARSE: Compile time parse error.
E_NOTICE: Run time notice caused due to error in code.
E_CORE_ERROR: Fatal errors that occur during PHP initial startup.
(installation)
E_CORE_WARNING: Warnings that occur during PHP initial startup.
E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
E_USER_ERROR: User-generated error message.
E_USER_WARNING: User-generated warning message.
E_USER_NOTICE: User-generated notice message.
E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
E_ALL: Catches all errors and warnings.
In PHP both functions are used to find the first occurrence of substring in a string except
stristr() is case-insensitive and strstr is case-sensitive,if no match is found then FALSE will be returned.
Sample Usage:
<?php
$email = ?abc@xyz.com?;
$hostname = strstr($email, ?@?);
echo $hostname;
output: @xyz.com
stristr() does the same thing in Case-insensitive manner
?>
PHP count function is used to get the length or numbers of elements in an array
<?php
// initializing an array in PHP
$array=['a','b','c'];
// Outputs 3
echo count($array);
?>
You can open a file download dialog in PHP by setting Content-Disposition in the header.
Here is a usage sample:-
// outputting a PDF file
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
Defining a Constant in PHP
define('CONSTANT_NAME',value);
func_get_args() function is used to get number of arguments passed in a PHP function.
Sample Usage:
function foo() {
return func_get_args();
}
echo foo(1,5,7,3);//output 4;
echo foo(a,b);//output 2;
echo foo();//output 0;
crypt(),Mcrypt(),hash() are used for encryption in PHP
Unlink: Is used to remove a file from server.
usage:unlink(?path to file?);
Unset: Is used unset a variable.
usage: unset($var);
<?php
$tomorrow = mktime(0, 0, 0, date(?m?) , date(?d?)+1, date(?Y?));
$lastmonth = mktime(0, 0, 0, date(?m?)-1, date(?d?), date(?Y?));
echo ($tomorrow-$lastmonth)/86400;
?>
<?Php
$date1 = date('Y-m-d');
$date2 = '2015-10-2';
$days = (strtotime($date1)-strtotime($date2))/(60*60*24);
echo $days;
?>
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side script into web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-origin policy.
Difference between echo and print in PHP
echo in PHP
echo is language constructs that display strings.
echo has a void return type.
echo can take multiple parameters separated by comma.
echo is slightly faster than print.
Print in PHP
print is language constructs that display strings.
print has a return value of 1 so it can be used in expressions.
print cannot take multiple parameters.
print is slower than echo.
PHP Namespaces provide a way of grouping related classes, interfaces, functions and constants.
# define namespace and class in namespace
namespace Modules\Admin\;
class CityController {
}
# include the class using namesapce
use Modules\Admin\CityController ;
PHP is a server side scripting language for creating dynamic web pages. There are so many functions available for displaying output in PHP. Here, I will explain some basic functions for displaying output in PHP. The basic functions for displaying output in PHP are as follows:
print() Function
echo() Function
printf() Function
sprintf() Function
Var_dump() Function
print_r() Function
You can add 301 redirect in PHP by adding below code snippet in your file.
header("HTTP/1.1 301 Moved Permanently");
header("Location: /option-a");
exit();
GD is an open source library for creating dynamic images.
PHP uses GD library to create PNG, JPEG and GIF images.
It is also used for creating charts and graphics on the fly.
GD library requires an ANSI C compiler to run.
Sample code to generate an image in PHP
<?php
header("Content-type: image/png");
$string = $_GET['text'];
$im = imagecreatefrompng("images/button1.png");
$mongo = imagecolorallocate($im, 220, 210, 60);
$px = (imagesx($im) - 7.5 * strlen($string)) / 2;
imagestring($im, 3, $px, 9, $string, $mongo);
imagepng($im);
imagedestroy($im);
?>
You can use $_SERVER['REMOTE_ADDR'] to get IP address of user/client in PHP, But sometime it may not return the true IP address of the client at all time. Use Below code to get true IP address of user.
function getTrueIpAddr(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
Zend Engine is used by PHP. The current stable version of Zend Engine is 3.0. It is developed by Andi Gutmans and Zeev Suraski at Technion ? Israel Institute of Technology.
Session and cookie both are used to store values or data.
cookie stores data in your browser and a session is stored on the server.
Session destroys that when browser close and cookie delete when set time expires.
The result set can be handled using mysqli_fetch_array, mysqli_fetch_assoc, mysqli_fetch_object or mysqli_fetch_row.
The function mysqli_num_rows() returns the number of rows in a result set.
mysqli_affected_rows() return the number of entries affected by an SQL query.
is_numeric() to check whether it is a number or not.
ctype_alnum to check whether it is an alphanumeric value or not.
empty() function.
It simply deletes the file given as entry.
It will make a variable undefined.
The addslashes function enables us to escape data before storage into the database.
The strip_tags() function enables us to clean a string from the HTML tags.
To be able to pass a variable by reference, we use an ampersand in front of it, as follows $var1 = &$var2
The function func_num_args() is used to give the number of parameters passed into a function.
We can change the maximum size of files to be uploaded by changing upload_max_filesize in php.ini.
PHP sessions are stored on server generally in text files in a temp directory of server. That file is not accessible from outside word. When we create a session PHP create a unique session id that is shared by client by creating cookie on clients browser.That session id is sent by client browser to server each time when a request is made and session is identified. The default session name is ?PHPSESSID?.
Default session time in PHP is 1440 seconds (24 minutes) and Default session storage path is temporary folder/tmp on server.
You can change default session time by using below code
<?php
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
?>
Here is a usage sample:-
// outputting a PDF file
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
$url='https://www.itechtuto.com/get_details';
$jsonData='{"name":"phpScots",
"email":"info@itechtuto.com"
,'age':36
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_close($ch);
crypt(), Mcrypt(), hash() are used for encryption in PHP
Trending Tutorials