tags. Files use the .php extension. PHP can echo and print strings and variables. 2) Variables, constants, and data types. Variables are case sensitive. PHP automatically converts variables to the correct data type. Constants can be defined using define() or const. 3) Control structures like if/else, switch, for, foreach, while and comments. Arrays can be indexed, associative or multidimensional. Functions can take parameters, return values, use call by value or reference."> tags. Files use the .php extension. PHP can echo and print strings and variables. 2) Variables, constants, and data types. Variables are case sensitive. PHP automatically converts variables to the correct data type. Constants can be defined using define() or const. 3) Control structures like if/else, switch, for, foreach, while and comments. Arrays can be indexed, associative or multidimensional. Functions can take parameters, return values, use call by value or reference.">
Nothing Special   »   [go: up one dir, main page]

PHP Hand Book

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

1. All PHP code goes between php tag.

<?php
//your code here
?>
2. File: first.php
<!DOCTYPE>
<html>
<body>
<?php
echo "<h2>Hello First PHP</h2>";
?>
</body>
</html>
3. PHP Echo / print
printing string : echo "Hello by PHP echo"; print "Hello by PHP echo";
printing escaping characters: echo "Hello escape \"sequence\" characters";
print "Hello escape \"sequence\" characters";
printing variable value : $msg="Hello PHP";
echo "Message is: $msg";
print "Message is: $msg";
4. PHP Variables :
In PHP, variable names are case sensitive. PHP is a loosely typed language, it means PHP
automatically converts the variable to its correct data type.
Declaring String, integer, float :
$str="hello string";
$x=200;
$y=44.6;
5. PHP Constants
PHP constants can be defined by 2 ways:

Using define() function


define(name, value, case-insensitive)
Example : define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
Using const keyword
const constName= string or value;
Example : const MESSAGE="Hello const by JavaTpoint PHP";

6. PHP Comments
// this is C++ style single line comment
# this is Unix Shell style single line comment
/*
This is a
multiline
comment
*/
7. Control Structures

IF Statement SWITCH Statement


if (condition) switch(expression)
{ {
//code to be executed if true case value1:
} //code to be executed
else break;
{ case value2:
//code to be executed if false //code to be executed
} break;
......
default:
code to be executed if all cases are not
matched;
}
FOR Loop FOR EACH Loop
for(initialization; condition;incr/decr) foreach( $array as $var )
{ {
//code to be executed //code to be executed
} }
?>
Example
<?php
$season=array("summer","winter","spring","autumn");
foreach( $season as $arr ){
echo "Season is: $arr<br />";
}
?>
WHILE Statement DO..WHILE Loop
while(condition)
{ do
//code to be executed {
}
//code to be executed
( OR )
while(condition): }while(condition);
//code to be executed
endwhile;
Break statement Continue statement
It breaks the execution of current for, continue is used within looping structures to skip the
while, do-while, switch and for-each rest of the current loop iteration and continue
loop. If you use break inside inner loop, execution at the condition evaluation and then the
it breaks the execution of inner loop beginning of the next iteration.
only. Syntax : break; Syntax : continue;
8. User-defined Functions
PHP supports Call by Value (default), Call by Reference, Default argument values
function functionName(parameter_list)
{
//code to be executed
}
Example : File: functionarg2.php
<?php
function sayHello($name,$age)
{
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Call By Reference
Value passed to the function doesn't modify the actual value by default (call by value). But we can
do so by passing value as a reference. By default, value passed to the function is call by value. To
pass value as a reference, you need to use ampersand (&) symbol before the argument name.
<?php <?php
function adder(&$str2) function increment(&$i)
{ {
$str2 .= 'Call By Reference'; $i++;
} }
$str = 'Hello '; $i = 10;
adder($str); increment($i);
echo $str; echo $i;
?> ?>
Default Argument Value
<?php
function greeting($first="Sonoo",$last="Jaiswal")
{
echo "Greeting: $first $last<br/>";
}
greeting();
greeting("Rahul");
greeting("Michael","Clark");
?>
Returning Value
<?php
function cube($n)
{
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Example: Parameterized Function
<?php
function add($x,$y) //add() function with two parameter
{
$sum=$x+$y;
echo "Sum = $sum <br><br>";
}
function sub($x,$y) //sub() function with two parameter
{
$sub=$x-$y;
echo "Diff = $sub <br><br>";
}
if(isset($_POST['add'])) // call function, get two argument through input box
{ // and click on add or sub button
add($_POST['first'],$_POST['second']); //call add() function
}
if(isset($_POST['sub']))
{
sub($_POST['first'],$_POST['second']); //call add() function
}
?>
<form method="post">
Enter first number: <input type="number" name="first"/><br><br>
Enter second number: <input type="number" name="second"/><br><br>
<input type="submit" name="add" value="ADDITION"/>
<input type="submit" name="sub" value="SUBTRACTION"/>
</form>
Call By Value
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Recursive Function
<?php
function display($number)
{
if($number<=5)
{
echo "$number <br/>";
display($number+1);
}
}
display(1);
?>
Arrays
3 types of array in PHP.
Indexed Array
Associative Array
Multidimensional Array
Indexed Array
PHP index is represented by number which starts from 0. We can store number, string and object in
the PHP array. All PHP array elements are assigned to an index number by default.

$season=array("summer","winter","spring","autumn");
(OR)
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Example
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Associative Array
We can associate name with each array elements in PHP using => symbol.

$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
(OR)
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Example
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Multidimensional Array
PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an
array. PHP multidimensional array can be represented in the form of matrix which is represented by
row * column.

$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
Example
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
for ($row = 0; $row < 3; $row++)
{
for ($col = 0; $col < 3; $col++)
{
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
Loop Through an Indexed Array
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>
Loop Through an Associative Array
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

Array Functions
array()
creates and returns an array. It allows you to create indexed, associative and multidimensional
arrays.

Syntax array array ([ mixed $... ] )


Example
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
count() function counts all elements in an array.
<?php
$season=array("summer","winter","spring","autumn");
echo count($season);
?>

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
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
rsort($cars);
?>
Sort Array (Ascending Order), According to Value - asort()
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>
Sort Array (Ascending Order), According to Key - ksort()
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>
Sort Array (Descending Order), According to Value - arsort()
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
Sort Array (Descending Order), According to Key - krsort()
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>

array_reverse() function returns an array containing elements in reversed order.


<?php
$season=array("summer","winter","spring","autumn");
$reverseseason=array_reverse($season);
foreach( $reverseseason as $s )
{
echo "$s<br />";
}
?>
array_search() function searches the specified value in an array. It returns key if search is
successful
<?php
$season=array("summer","winter","spring","autumn");
$key=array_search("spring",$season);
echo $key;
?>
array_intersect() function returns the intersection of two array. In other words, it returns the
matching elements of two array.
<?php
$name1=array("sonoo","john","vivek","smith");
$name2=array("umesh","sonoo","kartik","smith");
$name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
{
echo "$n<br />";
}
?>

String
A PHP string is a sequence of characters i.e. used to store and manipulate text. There are 4 ways to
specify string in PHP.
single quoted
double quoted
Single Quoted PHP String
We can create a string in PHP by enclosing text in a single quote. It is the easiest way to specify
string in PHP.
<?php
$str='Hello text within single quote';
echo $str;
?>
Double Quoted PHP String
In PHP, we can specify string through enclosing text within double quote also. But escape sequences
and variables will be interpreted using double quote PHP strings.
<?php
$str="Hello text within double quote";
echo $str;
?>
We can store multiple line text, special characters and escape sequences in a double quoted string.
<?php
$str1="Hello text
multiple line
text within double quoted string";
$str2="Using double \"quote\" with backslash inside double quoted string";
$str3="Using escape sequences \n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>
In double quoted strings, variable will be interpreted.
<?php
$num1=10;
echo "Number is: $num1";
?>

String Functions
strtolower() function returns string in lowercase letter
strtoupper() function returns string in uppercase letter.
<?php
$str="My name is KHAN";
$str=strtolower($str);
echo $str;
$str=strtoupper($str);
echo $str;
?>
strrev() function returns reversed string.
$str=strrev($str);

strlen() function returns length of the string.


$str=strlen($str);

strpos() function searches for a specific text within a string.


If a match is found, the function returns the character position of the first match. If no match is
found, it will return FALSE.
echo strpos("Hello world!", "world"); // outputs 6
str_replace() function replaces some characters with some other characters in a string.
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
ltrim() function removes whitespace or other predefined characters from the left side of a string.
$str = "Hello World!";
echo $str . "<br>";
echo ltrim($str,"Hello");
rtrim() function removes whitespace or other predefined characters from the right side of a string
$str = "Hello World!";
echo $str . "<br>";
echo rtrim($str,"World!");
trim() function removes whitespace and other predefined characters from both sides of a string.
Example: Remove whitespaces from both sides of a string:
$str = " Hello World! ";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);

parse_str() function parses a query string into variables.


parse_str("name=Peter&age=43");
echo $name."<br>";
echo $age;
Mathematical Functions
abs() function returns absolute value of given number
abs(-7) = 7
ceil() function rounds fractions up
ceil(7.333)=8
floor() function rounds fractions down
floor(7.333)
sqrt() function returns square root of given argument
sqrt(16)

Global Variables - Superglobals


Several 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:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION

$GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere
in the PHP script (also from within functions or methods). PHP stores all global variables in an array
called $GLOBALS[index]. The index holds the name of the variable.
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
In the example above, since z is a variable present within the $GLOBALS array, it is also accessible
from outside the function!
$_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths, and script
locations.
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>

Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script
$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Interface (CGI)
the server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
$_SERVER['SERVER_NAME'] Returns the name of the host server (such as
www.w3schools.com)
$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as Apache/2.2.24)

$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information protocol


(such as HTTP/1.1)
$_SERVER['REQUEST_METHOD'] Returns the request method used to access the page (such as
POST)
$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the request (such as
1377687496)
$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query
string
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request
$_SERVER['HTTP_HOST'] Returns the Host header from the current request
$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (not reliable
because not all user-agents support it)
$_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol
$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the
current page
$_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the
current page
$_SERVER['REMOTE_PORT'] Returns the port being used on the user's machine to
communicate with the web server
$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the currently executing script
$_SERVER['SERVER_ADMIN'] Returns the value given to the SERVER_ADMIN directive in
the web server configuration file (if your script runs on a virtual
host, it will be the value defined for that virtual host) (such as
someone@w3schools.com)
$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by the web
server for communication (such as 80)
$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual host name which are
added to server-generated pages
$_SERVER['PATH_TRANSLATED'] Returns the file system based path to the current script
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page

$_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form.

The example below shows a form with an input field and a submit button. When a user submits the
data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the
<form> tag. In this example, we point to this file itself for processing form data. If you wish to use
another PHP file to process form data, replace that with the filename of your choice. Then, we can
use the super global variable $_REQUEST to collect the value of the input field:

<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>

$_POST
PHP $_POST is widely used to collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.

The example below shows a form with an input field and a submit button. When a user submits the
data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the
<form> tag. In this example, we point to the file itself for processing form data. If you wish to use
another PHP file to process form data, replace that with the filename of your choice. Then, we can
use the super global variable $_POST to collect the value of the input field:
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>

EXAMPLE
File: form1.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>
File: login.php
<?php
$name=$_POST["name"];//receiving name field value in $name variable
$password=$_POST["password"];//receiving password field value in $password variable

echo "Welcome: $name, your password is: $password";


?>

$_GET
PHP $_GET can also be used to collect form data after submitting an HTML form with
method="get". $_GET can also collect data sent in the URL.
Assume we have an HTML page that contains a hyperlink with parameters:
<html>
<body>
<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>
</body>
</html>
When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to
"test_get.php", and you can then access their values in "test_get.php" with $_GET.

The example below shows the code in "test_get.php":


<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
EXAMPLE
File: form1.html
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>
File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name variable
echo "Welcome, $name";
?>

PHP Include File


PHP allows you to include file so that a page content can be reused many times. There are two ways
to include file in PHP.
include
require

PHP include
PHP include is used to include file on the basis of given path. You may use relative or absolute path
of the file. Let's see a simple PHP include example.

File: menu.html
<a href="index.html">Home</a> |
<a href="php-tutorial.html">PHP</a> |
<a href="java-tutorial.html">Java</a> |
<a href="html-tutorial.html">HTML</a>
File: include1.php
<?php include("menu.html"); ?>
<h1>This is Main Page</h1>

PHP require
PHP require is similar to include. Let's see a simple PHP require example.

File: menu.html
<a href="index.html">Home</a> |
<a href="php-tutorial.html">PHP</a> |
<a href="java-tutorial.html">Java</a> |
<a href="html-tutorial.html">HTML</a>
File: require1.php
<?php require("menu.html"); ?>
<h1>This is Main Page</h1>

PHP include vs PHP require


If file is missing or inclusion fails, include allows the script to continue but require halts the script
producing a fatal E_COMPILE_ERROR level error.

Sessions
A session is a way to store information (in variables) to be used across multiple pages.
When you work with an application, you open it, do some changes, and then you close it. This is
much like a Session. The computer knows who you are. It knows when you start the application and
when you end. But on the internet there is one problem: the web server does not know who you are
or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages
(e.g. username, favorite color, etc). By default, session variables last until the user closes the
browser.
So; Session variables hold information about one single user, and are available to all pages in one
application.

Start a PHP Session


A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
The session_start() function must be the very first thing in your document. Before any HTML
tags.
<?php
session_start(); // Start the session
?>
<!DOCTYPE html>
<html>
<body>
<?php
$_SESSION["favcolor"] = "green"; // Set session variables
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>

Get PHP Session Variable Values


Next, we create another page called "demo_session2.php". From this page, we will access the
session information we set on the first page ("demo_session1.php").

Notice that session variables are not passed individually to each new page, instead they are retrieved
from the session we open at the beginning of each page (session_start()).
Also notice that all session variable values are stored in the global $_SESSION variable:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>

Modify a PHP Session Variable


To change a session variable, just overwrite it:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>

Destroy a PHP Session


To remove all global session variables and destroy the session, use session_unset() and
session_destroy():
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
session_unset(); // remove all session variables
session_destroy(); // destroy the session
?>
</body>
</html>
Example
File: sessioncounter.php
<?php
session_start();

if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
echo ("Page Views: ".$_SESSION['counter']);
?>

PHP File Upload

PHP allows you to upload single and multiple files through few lines of code only.
PHP file upload features allows you to upload binary and text files both. Moreover, you can have the
full control over the file to be uploaded through PHP authentication and file operation functions.

PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can
get file name, file type, file size, temp file name and errors associated with file.
Here, we are assuming that file name is filename.

$_FILES['filename']['name'] returns file name.


$_FILES['filename']['type'] returns MIME type of the file.
$_FILES['filename']['size'] returns size of the file (in bytes).
$_FILES['filename']['tmp_name'] returns temporary file name of the file which stored on server.
$_FILES['filename']['error'] returns error code associated with this file.

move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough the POST request.
It moves the file if it is uploaded through the POST request.
Syntax bool move_uploaded_file ( string $filename , string $destination )

PHP File Upload Example

File: uploadform.html
<form action="https://www.javatpoint.com/uploader.php" method="post"
enctype="multipart/form-data">
Select File: <input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
File: uploader.php
<?php
$target_path = "e:/";
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);

if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path))
{
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>

PHP Download File


PHP enables you to download file easily using built-in readfile() function. The readfile() function
reads a file and writes it to the output buffer.

PHP readfile() function


Syntax int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )

$filename: represents the file name


$use_include_path: it is the optional parameter. It is by default false. You can set it to true to the
search the file in the included_path.
$context: represents the context stream resource.
int: it returns the number of bytes read from the file.

PHP Download File Example: Text File


File: download1.php
<?php
$file_url = 'http://www.javatpoint.com/f.txt';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: utf-8");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
?>
PHP Download File Example: Binary File
File: download2.php
<?php
$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
?>
MySQL Database
PHP 5 and later can work with a MySQL database using:
MySQLi extension (the "i" stands for improved)
PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in
2012.
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL
databases.
Open a Connection to MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Close the Connection


mysqli_close($conn);

Create a MySQL Database


A database consists of one or more tables.
You will need special CREATE privileges to create or to delete a MySQL database.
The CREATE DATABASE statement is used to create a database in MySQL.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE DATABASE myDB"; // Create database
if (mysqli_query($conn, $sql))
{
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Create MySQL Tables
A database table has its own unique name and consists of columns and rows

CREATE TABLE MyGuests (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP )

EXAMPLE
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";

if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

Insert Data Into MySQL

After a database and a table have been created, we can start adding data in them.

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>

Get ID of Last Inserted Record

If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get


the ID of the last inserted/updated record immediately.
In the table "MyGuests", the "id" column is an AUTO_INCREMENT field:

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {


$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

Insert Multiple Records Into MySQL

Multiple SQL statements must be executed with the mysqli_multi_query() function.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";

if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Prepared Statements
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly
with high efficiency.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute


$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>

In our SQL, we insert a question mark (?) where we want to substitute in an integer, string, double or
blob value.
Then, have a look at the bind_param() function:
$stmt->bind_param("sss", $firstname, $lastname, $email);
This function binds the parameters to the SQL query and tells the database what the parameters are.
The "sss" argument lists the types of data that the parameters are. The s character tells mysql that the
parameter is a string.
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
We must have one of these for each parameter.
By telling mysql what type of data to expect, we minimize the risk of SQL injections.

Select Data From MySQL

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
// output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"].
"<br>";
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

Delete Data From MySQL

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";

if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

Update Data in MySQL

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Limit Data Selections From a MySQL Database

MySQL provides a LIMIT clause that is used to specify the number of records to return.

$sql = "SELECT * FROM Orders LIMIT 30";


When the SQL query above is run, it will return the first 30 records.

What if we want to select records 16 - 25 (inclusive)?

Mysql also provides a way to handle this: by using OFFSET.

The SQL query below says "return only 10 records, start on record 16 (OFFSET 15)":

$sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15";


You could also use a shorter syntax to achieve the same result:

$sql = "SELECT * FROM Orders LIMIT 15, 10";


Notice that the numbers are reversed when you use a comma.
PHP - AJAX and MySQL
AJAX can be used for interactive communication with a database.
AJAX Database Example
The following example will demonstrate how a web page can fetch information from a database with
AJAX:
Example

Example Explained - The MySQL Database

The database table we use in the example above looks like this:

id FirstName LastName Age Hometown Job


1 Peter Griffin 41 Quahog Brewery
2 Lois Griffin 40 Newport Piano Teacher
3 Joseph Swanson 39 Quahog Police Officer
4 Glenn Quagmire 41 Quahog Pilot

In the example above, when a user selects a person in the dropdown list above, a function called
"showUser()" is executed.
The function is triggered by the onchange event.
Here is the HTML code:

Example
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp. {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>

<form>
<select name="users" > <option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>

Code explanation:
First, check if person is selected. If no person is selected (str == ""), clear the content of txtHint and
exit the function. If a person is selected, do the following:
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The PHP File


The page on the server called by the JavaScript above is a PHP file called "getuser.php".
The source code in "getuser.php" runs a query against a MySQL database, and returns the result in
an HTML table:

<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}

table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>

Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:

PHP opens a connection to a MySQL server


The correct person is found
An HTML table is created, filled with data, and sent back to the "txtHint" placeholder
Date and Time

date() function is used to format a date and/or a time

date(format,timestamp)
Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current date and time

A timestamp is a sequence of characters, denoting the date and/or time at which a certain event
occurred.

Get a Simple Date


The required format parameter of the date() function specifies how to format the date (or time).

Here are some characters that are commonly used for dates:

d - Represents the day of the month (01 to 31)


m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
l (lowercase 'L') - Represents the day of the week

Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional
formatting.

Example
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>

Get a Simple Time


Here are some characters that are commonly used for times:

h - 12-hour format of an hour with leading zeros (01 to 12)


i - Minutes with leading zeros (00 to 59)
s - Seconds with leading zeros (00 to 59)
a - Lowercase Ante meridiem and Post meridiem (am or pm)

<?php
echo "The time is " . date("h:i:sa");
?>
Create a Date From a String With PHP strtotime()

The PHP strtotime() function is used to convert a human readable string to a Unix time.
Syntax strtotime(time,now)

<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>

You might also like