Unit-2 PHP
Unit-2 PHP
Unit-2 PHP
PHP
J Vishnu Priyanka
Assistant Professor©
Dept of CSE
RGUKT-SRIKAKULAM.
Contents:
Server Programming: PHP basics: PHP Syntax,
Variables
Constants
Data Types
Strings
Conditional and Control Structures.
PHP GET and POST.
PHP Advanced: include files, File system
Parsing directories
File upload and download
Sessions
Form handling
JSON Parsing
Server Programming: PHP basics
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:
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
Example:
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
However; all variable names are case-sensitive!
Look at the example below;
only the first statement will display the value of the $color variable! This
is because $color, $COLOR, and $coLOR are treated as three different
variables:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
Comments in PHP
PHP supports several ways of commenting:
Example
<?php
// This is a single-line comment
</body>
</html>
Example
Syntax for multiple-line comments:
<!DOCTYPE html>
<html>
<body>
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body>
</html>
Example
<?php
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
PHP VARIABLES
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
PHP Variables
A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume).
The following example will show how to output text and a variable:
Example
<?php
$txt = “Srikakulam";
echo “RGUKT $txt!";
?>
The following example will output the sum of two variables:
Example
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
PHP Constants
A constant is an identifier (name) for a simple value. The value cannot
be changed during the script.
A valid constant name starts with a letter or underscore (no $ sign
before the constant name).
Syntax
define(name, value, case-insensitive)
Parameters:
name: Specifies the name of the constant
<?php
define("GREETING", "Welcome to RGUKT Srikakulam!");
echo GREETING;
?>
Example
Create a constant with a case-insensitive name:
<?php
define("GREETING", "Welcome to RGUKT Srikakulam!", true);
echo greeting;
?>
PHP Constant Arrays
In PHP7, you can create an Array constant using the define() function.
Example
Create an Array constant:
<?php
define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];
?>
Constants are Global
Constants are automatically global and can be used across the entire
script.
Example
This example uses a constant inside a function, even if it is defined
outside the function:
<?php
define("GREETING", "Welcome toRGUKT Srikakulam!");
function myTest() {
echo GREETING;
}
myTest();
?>
PHP Data Types
Variables can store data of different types, and different data types can do
different things. PHP supports the following data types:
String
Integer
Boolean
Array
Object
NULL
Resource
PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double
quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
Integers can be specified in: decimal (base 10), hexadecimal (base 16),
octal (base 8), or binary (base 2) notation
In the following example $x is an integer. The PHP var_dump() function
returns the data type and value:
Example
<?php
$x = 5985;
var_dump($x);
?>
PHP Float
A float (floating point number) is a number with a decimal point or a
number in exponential form.
In the following example $x is a float. The PHP var_dump() function
returns the data type and value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing.
PHP Array
An array stores multiple values in one single variable.
When the individual objects are created, they inherit all the properties
and behaviors from the class, but each object will have different values
for the properties.
Let's assume we have a class named Car. A Car can have properties
like model, color, etc. We can define variables like $model, $color, and
so on, to hold the values of these properties.
When the individual objects (Volvo, BMW, Toyota, etc.) are created,
they inherit all the properties and behaviors from the class, but each
object will have different values for the properties.
If you create a __construct() function, PHP will automatically call this
function when you create an object from a class.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
$myCar = new Car("black", "Volvo");
echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>
</body>
</html>
PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned
to it.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
</body>
</html>
PHP Resource
The special resource type is not an actual data type. It is the storing
of a reference to functions and resources external to PHP.
A common example of using the resource data type is a database call.
Example
Return the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
str_word_count() - Count Words in a String
The PHP str_word_count() function counts the number of words in a
string.
Example
Count the number of word in the string "Hello world!":
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
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($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Example Explained
$x = 1; - Initialize the loop counter ($x), and set the start value to 1
Example:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The PHP for Loop
The for loop is used when you know in advance how many times the script
should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE,
the loop continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value
Example:
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is
assigned to $value and the array pointer is moved by one, until it
reaches the last array element.
Example
<?php
$colors = array("red", "green", "blue", "yellow");
http://www.test.com/index.htm?name1=value1&name2=value2
The GET method produces a long string that appears in your server
logs, in the browser's Location: box.
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive
information to be sent to the server.
GET can't be used to send binary data, like images or word documents,
to the server.
The data sent by GET method can be accessed using QUERY_STRING
environment variable.
The PHP provides $_GET associative array to access all the sent
information using GET method.
Example:
<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
</body>
</html>
The POST Method
The POST method transfers information via HTTP headers. The
information is encoded as described in case of GET method and put
into a header called QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security
depends on HTTP protocol. By using Secure HTTP you can make sure
that your information is secure.
The PHP provides $_POST associative array to access all the sent
information using POST method.
Example:
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
</body>
</html>
The $_REQUEST variable
The PHP $_REQUEST variable contains the contents of both $_GET,
$_POST, and $_COOKIE
The PHP $_REQUEST variable can be used to get the result from
form data sent with both the GET and POST methods.
Example:
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields
and a submit button:
Example
<html>
<body>
</body>
</html>
When the user fills out the form above and clicks the submit button,
the form data is sent for processing to a PHP file named
"welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The
"welcome.php" looks like this:
<html>
<body>
</body>
</html>
The output could be something like this:
Welcome John
Your email address is john.doe@example.com
https://tryphp.w3schools.com/showphp.php?filename=demo_form_post
PHP - File Inclusion
You can include the content of a PHP file into another PHP file before the
server executes it. There are two PHP functions which can be used to
included one PHP file into another PHP file.
The include() Function
The require() Function
Syntax
include 'filename';
or
require 'filename';
Example
Assume we have a standard footer file called "footer.php", that looks like
this:
<?php
echo "<p>Copyright © 1999-" . date("Y") . " Rgukt.com</p>";
?>
To include the footer file in a page, use the include statement:
<html>
<body>
</body>
</html>
Example
Assume we have a standard menu file called "menu.php":
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
</body>
</html>
Example
Assume we have a file called “cars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "vars.php" file, the variables can be used in the
calling file:
Example
<html>
<body>
</body>
</html>
PHP require() Function: The require() function in PHP is basically
used to include the contents/code/data of one PHP file to another PHP
file. During this process if there are any kind of errors then
this require() function will pop up a warning along with a fatal error
and it will immediately stop the execution of the script.
</body>
</html>
Using the require statement, the echo statement will not be executed
because the script execution dies after the require statement returned a
fatal error:
<html>
<body>
</body>
</html>
PHP File Handling
PHP has several functions for creating, reading, uploading, and editing
files.
Opening a file
Reading a file
Writing a file
Closing a file
1 r
Opens the file for reading only.
Places the file pointer at the beginning of the file.
2 r+
Opens the file for reading and writing.
Places the file pointer at the beginning of the file.
3 w
Opens the file for writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attempts to create a file.
4 w+
Opens the file for reading and writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attempts to create a file.
5 a
Opens the file for writing only.
Places the file pointer at the end of the file.
If files does not exist then it attempts to create a file.
6 a+
Opens the file for reading and writing only.
Places the file pointer at the end of the file.
If files does not exist then it attempts to create a file.
Reading a file
Once a file is opened using fopen() function it can be read with a
function called fread(). This function requires two arguments. These
must be the file pointer and the length of the file expressed in bytes.
The files length can be found using the filesize() function which takes
the file name as its argument and returns the size of the file expressed
in bytes.
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );?>
<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>
<?php
$filename = "newfile.txt";
$file = fopen( $filename, "r" );
fclose( $file );
print_r($a);
print_r($b);
?>
Create The HTML Form
Next, create an HTML form that allow users to choose the image file
they want to upload:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Some rules to follow for the HTML form above:
Make sure that the form uses method="post"
You will need to create a new directory called "uploads" in the directory
where "upload.php" file resides. The uploaded files will be saved there.
Session variables are set with the PHP global variable: $_SESSION.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
<?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
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
JSON
JSON stands for JavaScript Object Notation, and is a syntax for
storing and exchanging data.
Since the JSON format is a text-based format, it can easily be sent to
and from a server, and used as a data format by any programming
language.
PHP and JSON
PHP has some built-in functions to handle JSON.
First, we will look at the following two functions:
json_encode()
json_decode()
PHP - json_encode()
The json_encode() function is used to encode a value to JSON format.
Example
This example shows how to encode an associative array into a JSON
object:
<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>35, "Ben"=>37, "Joe"=>43);
echo json_encode($age);
?>
</body>
</html>
Example
This example shows how to encode an indexed array into a JSON
array:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo json_encode($cars);
?>
</body>
</html>
PHP - json_decode()
The json_decode() function is used to decode a JSON object into a PHP
object or an associative array.
Example
This example decodes JSON data into a PHP object:
<!DOCTYPE html>
<html>
<body>
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
var_dump(json_decode($jsonobj));
?>
</body>
</html>