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.">
PHP Hand Book
PHP Hand Book
PHP Hand Book
<?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:
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
$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);
Array Functions
array()
creates and returns an array. It allows you to create indexed, associative and multidimensional
arrays.
<?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);
?>
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);
$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)
$_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
$_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.
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>
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.
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>
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
echo ("Page Views: ".$_SESSION['counter']);
?>
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.
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 )
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!";
}
?>
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());
}
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
After a database and a table have been created, we can start adding data in them.
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?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());
}
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);
$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.
<?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);
?>
<?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);
?>
<?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());
}
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
MySQL provides a LIMIT clause that is used to specify the number of records to return.
The SQL query below says "return only 10 records, start on record 16 (OFFSET 15)":
The database table we use in the example above looks like this:
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)
<!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:
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.
Here are some characters that are commonly used for dates:
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");
?>
<?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>";
?>