1 of 76

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.

2 of 76

PHP User Defined Functions

  • Besides the built-in PHP functions, we can create our own functions.

  • A function will not execute immediately when a page loads.

  • A function will be executed by a call to the function.

3 of 76

Create a User Defined Function in PHP

A user defined function declaration starts with the word "function":

Syntax

function functionName()

{�    code to be executed;�}

4 of 76

Example:

<!DOCTYPE html>

<html>

<body>

<?php

function writeMsg()

{

echo "Hello world!";

}

writeMsg();

?>

</body>

</html>

5 of 76

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");

?>

6 of 76

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");

?>

7 of 76

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 

8 of 76

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

9 of 76

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>

10 of 76

  • 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/ GET method.

11 of 76

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

12 of 76

GET vs. POST

  • Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)).

  • This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

  • Both GET and POST are treated as $_GET and $_POST.

  • These 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.

13 of 76

  • $_GET is an array of variables passed to the current script via the URL parameters.

  • $_POST is an array of variables passed to the current script via the HTTP POST method.

14 of 76

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!

15 of 76

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.

16 of 76

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>

17 of 76

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>

18 of 76

PHP Connect to MySQL:

PHP and later can work with a MySQL database using:

MySQLi extension (the "i" stands for improved)

19 of 76

MySQLi will only work with MySQL databases.

20 of 76

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";

?>

21 of 76

Example (MySQLi Procedural)

<?php$servername = "localhost";�$username = ”root";�$password = “ ";��// Create connection$conn = mysqli_connect($servername, $username, $password);�// Check connectionif (!$conn) 

{�    die("Connection failed: " . mysqli_connect_error());�}�echo "Connected successfully";?>

22 of 76

Close the Connection:

Example (MySQLi Object-Oriented)

$conn->close();

Example (MySQLi Procedural)

mysqli_close($conn);

23 of 76

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":

24 of 76

<?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);

?>

25 of 76

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());�}�

26 of 76

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);�?>

27 of 76

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 SQL query must be quoted in PHP
  • String values inside the SQL query must be quoted
  • Numeric values must not be quoted
  • The word NULL must not be quoted

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,...)

28 of 76

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.

29 of 76

<?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());�}��

30 of 76

��$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);�?>

31 of 76

Insert Multiple Records Into MySQL Using MySQLi and PDO

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

32 of 76

<?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());�}�

33 of 76

$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);�?>

34 of 76

����Select Data With MySQLi�

  • The following example selects the id, firstname and lastname columns from the MyGuests table and displays it on the page:

35 of 76

<?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());�}��

36 of 76

$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);�?>

37 of 76

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

38 of 76

<?php�$servername = "localhost";�$username = “root";�$password = ” ";�$dbname = "myDB";

// Create connection$conn = mysqli_connect($servername, $username, $password, $dbname);// Check connectionif (!$conn) 

{�    die("Connection failed: " . mysqli_connect_error());�}

39 of 76

// 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);�?>

40 of 76

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 

41 of 76

<?php�$servername = "localhost";�$username = "username";�$password = "password";�$dbname = "myDB";��// Create connection$conn = mysqli_connect($servername, $username, $password, $dbname);// Check connectionif (!$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);�?>

42 of 76

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.

43 of 76

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]]);

44 of 76

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.

45 of 76

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

46 of 76

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

47 of 76

Example:

<?php

$handle=fopen(“file.txt”, ”r”);

If($handle)

{

Echo ”File opened ok”;

}

?>

File is opened successfully if handle is true

48 of 76

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"));

49 of 76

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);�

?>

50 of 76

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.

51 of 76

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);�?>

52 of 76

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);�?>

53 of 76

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")

54 of 76

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);�?>

55 of 76

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);�?>

56 of 76

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.

57 of 76

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

58 of 76

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);

59 of 76

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.

60 of 76

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?�)

61 of 76

PHP unlink() Function:��The unlink() function deletes a file.

This function returns TRUE on success, or FALSE on failure.

Syntax:

unlink(filename,context)

62 of 76

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

63 of 76

Delete a file

Example:

<?php

$file = "test.txt";�if (!unlink($file))�  {�  echo ("Error deleting $file");�  }�else�  {�  echo ("Deleted $file");�  }�

?>

64 of 76

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)

65 of 76

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.

66 of 76

Example

<?php

echo file_get_contents("test.txt");�

?>

The output of the code above will be:

This is a test file with test text.

67 of 76

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!";�}�?>

68 of 76

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;�}

69 of 76

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!";�}�?>

70 of 76

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:

  • while - loops through a block of code as long as the specified condition is true
  • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array

71 of 76

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++;�} �?>

72 of 76

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) ;�?>

73 of 76

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

74 of 76

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 

75 of 76

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.

76 of 76

PHP Control Structures(Looping Statements)

The PHP foreach Loop

Example

<?php �$colors = array("red", "green", "blue", "yellow"); ��foreach ($colors as $value)

{�    echo "$value <br>";�}�?>