PHP Functions
The PHP functions are real power of it, it has more than 1000 built-in functions
Def: A function is a block of statements that can be used repeatedly in a program.
PHP User Defined Functions
Create a User Defined Function in PHP
A user defined function declaration starts with the word "function":
Syntax
function functionName()
{� code to be executed;�}
Example:
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg()
{
echo "Hello world!";
}
writeMsg();
?>
</body>
</html>
PHP Function Arguments
Information can be passed to functions through arguments. An argument is just like a variable.
Example:
<?php
function familyName($fname)
{
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
Ex2: function with 2 arguments
<?php
function familyName($fname, $year)
{
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
Function with default arguments
<?php
function setHeight($minheight = 50)
{
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
Output:
The height is : 350 �The height is : 50 �The height is : 135 �The height is : 80
PHP Functions - Returning values:
<?php
function sum($x, $y)
{
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
output:
5 + 10 = 15�7 + 13 = 20�2 + 4 = 6
PHP Form Handling:
PHP - A Simple HTML Form
Example: client code in html
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
PHP file to receive the data from form
<html>
<body>
<$php
$name=$_POST[“name”];
$email=$_POST[“email”];
Echo “WELCOME: $name” ,”<br>”;
Echo “Your email address is:$email”;
?>
</body>
</html>
Output:
Welcome raj�Your email address is: kumar@gmail.com
GET vs. POST
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL).
GET also has limits on the amount of information to send. The limitation is about 2000 characters.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and
has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
Hadling Text Areas?(html file)
<html>
<body>
<h2> Entering the data from text area</h2>
<form action=“textarea.php" method="post">
Enter the pizza toppings you want:<br>
<textarea name=“data“ cols=“50” rows=“5”>
1.
2.
3.
</textarea><br>
<input type=“submit” value=“Send”>
</form>
</body>
</html>
PHP file to read data from Textarea:
<!DOCTYPE html>�<html>�<body>�<h2> Reading the data from Text Area</h2>
You ordered a pizza with:<br> �<?php
$text=$_REQUEST[“data”];
Echo”str_replace(“\n”,”<br>”,$text);
�?>��</body>�</html>
PHP Connect to MySQL:
PHP and later can work with a MySQL database using:
MySQLi extension (the "i" stands for improved)
MySQLi will only work with MySQL databases.
Open a Connection to MySQL:
Example (MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = “root";
$password = “ ";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Example (MySQLi Procedural)
<?php�$servername = "localhost";�$username = ”root";�$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:
Example (MySQLi Object-Oriented)
$conn->close();
�
Example (MySQLi Procedural)
mysqli_close($conn);
�
Create a MySQL Database Using MySQLi
The CREATE DATABASE statement is used to create a database in MySQL.
The following examples create a database named "myDB":
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql))
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
PHP Database Table creation
<?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());�}��
PHP Database Table creation(cont..)
// 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);�?>
PHP Insert Data Into MySQL
After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)�VALUES (value1, value2, value3,...)
Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP (like the "reg_date" column),
it is no need to be specified in the SQL query;
MySQL will automatically add the value.
<?php�$servername = "localhost";�$username = “root";�$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);�?>
Insert Multiple Records Into MySQL Using MySQLi and PDO
Multiple SQL statements must be executed with the mysqli_multi_query() function.
<?php�$servername = "localhost";�$username = “root";�$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);�?>
����Select Data With MySQLi��
<?php�$servername = "localhost";�$username = “root";�$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 a MySQL Table Using MySQLi and PDO
The DELETE statement is used to delete records from a table:
SQL Syntax:
DELETE FROM table_name�WHERE some_column = some_value
<?php�$servername = "localhost";�$username = “root";�$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 a MySQL Table Using MySQLi
The UPDATE statement is used to update existing records in a table:
SQL Syntax:
UPDATE table_name�SET column1=value, column2=value2,...�WHERE some_column=some_value
�
<?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());�}� // Update data�$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);�?>
File handling in PHP
File handling is an important part of any web application.
You often need to open and process a file for different tasks.
�
PHP File Open/Read/Close
PHP Open File - fopen()
A better method to open files is with the fopen() function.
Syntax:
$filehandle=fopen (filename, mode [, useincludepath [,zcontext]]);
�
Filename :- Name of the file we are openining
Mode:- How you want to open the file (purpose of opening the
file)
File opening modes:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved.
Modes Description
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
Use include path :- May be set to 1 or TRUE to specify that you want to search for the file in PHP include path
zcontext:- holds an optional file context
The fopen returns TRUE if file is opened successfully, otherwise FALSE
Example:
<?php
$handle=fopen(“file.txt”, ”r”);
If($handle)
{
Echo ”File opened ok”;
}
?>
File is opened successfully if handle is true
Reading the content of file
PHP Read File - fread()
The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and the
second parameter specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
PHP Close File - fclose()
The fclose() requires the name of the file (or a variable that holds the filename) we want to close:
Example:
<?php
�$myfile = fopen("webdictionary.txt", "r");�
// some code to be executed....�
fclose($myfile);�
?>
PHP Read Single Line - fgets()
The fgets() function is used to read a single line from a file.
<!DOCTYPE html>�<html>�<body>��<?php�$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");�echo fgets($myfile);�fclose($myfile);�?>��</body>�</html>
Note: After a call to the fgets() function, the file pointer has moved to the next line.
PHP Check End-Of-File - feof()
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
<?php�$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");�
// Output one line until end-of-file�while(!feof($myfile))
{� echo fgets($myfile) . "<br>";�}�fclose($myfile);�?>
PHP Read Single Character - fgetc()
The fgetc() function is used to read a single character from a file.
<?php�$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");�// Output one character until end-of-file�
while(!feof($myfile))
{� echo fgetc($myfile);�}�fclose($myfile);�?>
PHP 5 File Create/Write: how to create and write to a file on the server.
PHP Create File - fopen()
The example below creates a new file called "testfile.txt". The file will be created in the same directory where the PHP code resides:
Example
$myfile = fopen("testfile.txt", "w")
�
PHP Write to File - fwrite()
The fwrite() function is used to write to a file.
The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.
The example below writes a couple of names into a new file called "newfile.txt":
Example
<?php�$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");�$txt = "John Doe\n";�fwrite($myfile, $txt);�$txt = "Jane Doe\n";�fwrite($myfile, $txt);�fclose($myfile);�?>
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an existing file for writing. All the existing data will be ERASED and we start with an empty file.�
Example
<?php�$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");�$txt = "Mickey Mouse\n";�fwrite($myfile, $txt);�$txt = "Minnie Mouse\n";�fwrite($myfile, $txt);�fclose($myfile);�?>
PHP basename() Function
�
Definition and Usage
The basename() function returns the filename from a path.
Syntax
basename(path,suffix)
�Parameter Description
Path Required. Specifies the path to check
Suffix Optional. Specifies a file extension.
If the filename has this file extension, the file extension will not show
Example
<?php�$path = "/testweb/home.php";��//Show filename with file extension�echo basename($path) ."<br/>";��//Show filename without file extension�echo basename($path,".php");�?>
The output of the code above will be:
home.php�home
Reading a file into an Array:
PHP file() Function
The file() reads a file into an array.
Each array element contains a line from the file, with newline still attached.
Syntax:
file(path, include_path, context);
Parameter Description
path Required. Specifies the file to read
include_path Optional. Set this parameter to '1' if you want to search for the file in the include_path (in php.ini) as well
context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream. Can be skipped by using NULL.
Example:-
<?php�print_r(file("test.txt"));�?>
The output of the code above will be:
Array�(�[0] => Hello World. Testing testing!�[1] => Another day, another line.�[2] => If the array picks up this line,�[3] => then is it a pickup line?�)
PHP unlink() Function:��The unlink() function deletes a file.
This function returns TRUE on success, or FALSE on failure.
Syntax:
unlink(filename,context)
Parameter Description
filename Required. Specifies the file to delete
context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream
Delete a file
Example:
<?php�
$file = "test.txt";�if (!unlink($file))� {� echo ("Error deleting $file");� }�else� {� echo ("Deleted $file");� }�
?>
PHP file_get_contents() Function
The file_get_contents() reads a file into a string.
This function is the preferred way to read the contents of a file into a string.
Because it will use memory mapping techniques, if this is supported by the server, to enhance performance.
Syntax:
file_get_contents( path, include_path, context, start, max_length)
Parameter Description
Path Required. Specifies the file to read
include_path Optional. Set this parameter to '1' if you want to search for the file in the include_path (in php.ini) as well
Context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream. Can be skipped by using NULL.
Start Optional. Specifies where in the file to start reading.
max_length Optional. Specifies how many bytes to read.
Example
<?php�
echo file_get_contents("test.txt");�
?>
The output of the code above will be:
This is a test file with test text.
PHP Control Structures(Conditional Statements)
PHP - The if...elseif....else Statement
Example:
<?php�$t = date("H");��if ($t < "10")
{� echo "Have a good morning!";�}
elseif ($t < "20")
{� echo "Have a good day!";�} else
{� echo "Have a good night!";�}�?>
PHP Control Structures(Conditional Statements)
The switch statement is used to perform different actions based on different conditions.
The PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax:
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 Control Structures(Conditional Statements)
Example:
<?php�$favcolor = "red";��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 Control Structures(Looping Statements)
PHP while loops execute a block of code while the specified condition is true.
PHP Loops:
In PHP, we have the following looping statements:
PHP Control Structures(Looping Statements)
The PHP while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax: Ex:
while (condition is true)
{� code to be executed;�}
<?php �$x = 1; ��while($x <= 5)
{� echo "The number is: $x <br>";� $x++;�} �?>
PHP Control Structures(Looping Statements)
The PHP do…while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax: Ex:
do
{� code to be executed;�} while (condition is true) ;
<?php �$x = 1; ��do
{� echo "The number is: $x <br>";� $x++;�} while($x <= 5) ;�?>
PHP Control Structures(Looping Statements)
PHP for loops execute a block of code a specified number of times.
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;�}
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
PHP Control Structures(Looping Statements)
PHP for loops execute a block of code a specified number of times.
The PHP for Loop
Example: Output:
<?php �for ($x = 0; $x <= 10; $x++)
{� echo "The number is: $x <br>";�} �?>
The number is: 0 �The number is: 1 �The number is: 2 �The number is: 3 �The number is: 4 �The number is: 5 �The number is: 6 �The number is: 7 �The number is: 8 �The number is: 9 �The number is: 10
PHP Control Structures(Looping Statements)
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.
PHP Control Structures(Looping Statements)
The PHP foreach Loop
Example
<?php �$colors = array("red", "green", "blue", "yellow"); ��foreach ($colors as $value)
{� echo "$value <br>";�}�?>