0% found this document useful (0 votes)
561 views63 pages

PHP With Mysql Material-1

Php with mysql

Uploaded by

Vijay Dhama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
561 views63 pages

PHP With Mysql Material-1

Php with mysql

Uploaded by

Vijay Dhama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

PHP MATERIAL – The Arts and Science college :: Adoni

SEMESTER-VI
Paper-VIII : Elective–E
Programming with PHP and MySQL
UNIT I
Installing and Configuring MySQL: Current and Future Versions of MySQl, How to Get MySQL, Installing MySQL
on Linux, Windows, Trouble Shooting your Installation, Basic Security Guidelines, Introducing MySQL Privilege
System, Working with User Privileges. Installing and Configuring Apache: Current and future versions of Apache,
Choosing the Appropriate Installation Method, Installing Apache on Linux, Windows, Apache Configuration File
Structure, Apache Log Files, Apache Related Commands, Trouble Shooting. Installing and Configuring PHP:
Building PHP on Linux with Apache, Windows, php.ini.Basics, The Basics of PHP scripts. The Building blocks of
PHP: Variables, Data Types, Operators and Expressions, Constants. Flow Control Functions in PHP: Switching
Flow, Loops, Code Blocks and Browser Output.

UNIT II
Working with Functions: What is function?, Calling functions, Defining Functions, Returning the values from
User-Defined Functions, Variable Scope, Saving state between Function calls with the static statement, more
about arguments. Working with Arrays: What are Arrays?, Creating Arrays, Some Array-Related Functions.
Working with Objects: Creating Objects, Object Instance. Working with Strings, Dates and Time: Formatting
strings with PHP, Investigating Strings with PHP, Manipulating Strings with PHP, Using Date and Time Functions
in PHP.

UNIT III
Working with Forms: Creating Forms, Accessing Form Input with User defined Arrays, Combining HTML and
PHP code on a single Page, Using Hidden Fields to save state, Redirecting the user, Sending Mail on Form
Submission, Working with File Uploads. Working with Cookies and User Sessions: Introducing Cookies, Setting a
Cookie with PHP, Session Function Overview, Starting a Session, Working with session variables, passing session
IDs in the Query String, Destroying Sessions and Unsetting Variables, Using Sessions in an Environment with
Registered Users.

UNIT IV
Working with Files and Directories: Including Files with include(), Validating Files, Creating and Deleting Files,
Opening a File for Writing, Reading or Appending, Reading from Files, Writing or Appending to a File, Working
with Directories, Open Pipes to and from Process Using popen(), Running Commands with exec(), Running
Commands with system() or passthru(). Working with Images: Understanding the Image-Creation Process,
Necessary Modifications to PHP, Drawing a New Image, Getting Fancy with Pie Charts, Modifying Existing
Images, Image Creation from User Input.

UNIT V
Introduction to MySQL and Interfacing with Databases through PHP : Understanding the database design
process: The Importance of Good Database Design, Types of Table Relationships, Understanding Normalization.
Learning basic SQL Commands: Learning the MySQL Data types, Learning the Table Creation Syntax, Using Insert
Command, Using SELECT Command, Using WHERE in your Queries, Selecting from Multiple Tables, Using the
UPDATE command to modify records, Using RELACE Command, Using the DELETE Command, Frequently used
string functions in MySQL, Using Date and Time Functions in MySQL. Using Transaction and stored procedures
in MySQL: What is Transaction?, What are Stored Procedures? Interacting with MySQL using PHP: MySQL
Versus MySQLi Functions, Connecting to MySQL with PHP, Working with MySQL Data. Creating an Online

1 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
Address Book: Planning and Creating Database Tables, Creating Menu, Creating Record Addition Mechanism,
Viewing Records, Creating the Record Deletion Mechanism, Adding Sub-entities to a Record.

What is PHP?

PHP is an acronym for "PHP: Hypertext Pre-processor".


PHP is a widely-used, open source scripting language.
PHP scripts are executed on the server.
PHP is free to download and use.
PHP files can contain text, HTML, CSS(Cascading Style Sheets), JavaScript, and PHP
code.
PHP code is executed on the server, and the result is returned to the browser as plain
HTML.
PHP files have extension ".php".

2 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni

- FEATURES –
PHP can generate dynamic page content.
PHP can create, open, read, write, delete, and close files on the server.
PHP can collect form data
PHP can send and receive cookies.
PHP can add, delete, modify data in your database. – SQL COMMANDS
3 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
PHP can be used to control user-access.
PHP can encrypt data.

- Set Up PHP on Your Own PC -


However, if your server does not support PHP, you must:

• install a web server(Apache)


• install PHP
• install a database, such as MySQL(GUI)
• PHP runs on various platforms OS(Windows, Linux, Unix, Mac OS X, etc.)
• PHP is compatible with almost all servers used today (Apache, IIS, etc.)

Client-side Scripting
• It helps work with the front end.(UI)
• It is visible to the users.
• The scripts are run on the client browser.
• It runs on the user/client’s computer.
• It depends on the browser’s version.
• It doesn’t interact with the server to process data.
• Client side scripting involves languages such as HTML, CSS, JavaScript.
• It helps reduce the load on the server.
• It is considered to be less secure in comparison to client side scripting.

Server-side Scripting
• It helps work with the back end.
• It doesn’t depend on the client.-PROGRAMMING
• It runs on the web server.(APACHE – DUMMY)
• It helps provide a response to every request that comes in from the user/client.

4 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
• This is not visible to the client side of the application.
• It requires the interaction with the server for the data to be process.
• Server side scripting requires languages such as PHP, ASP.net, ColdFusion,
Python, Ruby on Rails.
• It is considered to be a secure way of working with applications.
• It can be used to customize web pages.
• It can also be used to provide dynamic websites.

History
PHP started out as a small open source project that evolved as more and
more people found out how useful it was. Rasmus Lerdorf unleashed the
first version of PHP way back in 1994.

PHP is a MUST for students and working professionals to become a great


Software Engineer specially when they are working in Web Development
Domain. I will list down some of the key advantages of learning PHP:

PHP is a recursive acronym for "PHP: Hypertext Preprocessor".

PHP is a server side scripting language that is embedded in HTML. It is


used to manage dynamic content, databases, session tracking, even build
entire e-commerce sites.

It is integrated with a number of popular databases, including MySQL,


PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.

• PHP is pleasingly zippy in its execution, especially when compiled as


an Apache module on the Unix side. The MySQL server, once
started, executes even very complex queries with huge result sets in
record-setting time.
• PHP supports a large number of major protocols such as POP3,
IMAP, and LDAP. PHP4 added support for Java and distributed
object, making n-tier development a possibility for the first time.
• PHP Syntax is C-Like.

In order to develop and run PHP Web pages three vital components need
to be installed on your computer system.
Web Server − PHP will work with virtually all Web Server software,
including Microsoft's Internet Information Server (IIS) but then most
often used is freely available Apache Server.

5 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
Database − PHP will work with virtually all database software, including
Oracle and Sybase but most commonly used is freely available MySQL
database.
PHP Parser − In order to process PHP script instructions a parser must
be installed to generate HTML output that can be sent to the Web
Browser. This tutorial will guide you how to install PHP parser on your
computer.
PHP Syntax

A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

<?php
// PHP code goes here
?>

The default file extension for PHP files is ".php".

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 - 1:
<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).

Rules for PHP variables:

A variable starts with the $ sign, followed by the name of the variable.
A variable name must start with a letter or the underscore character.
A variable name cannot start with a number.

6 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ ).
Variable names are case-sensitive ($age and $AGE are two different variables).

Output Variables
The PHP echo statement is often used to output data to the screen.

Example 2 :
<!DOCTYPE html>
<html>
<body>

<?php
$x = 5;
$y = 4;
echo $x + $y;
?>

</body>
</html>

PHP Variables Scope


In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
- Local
- Global
- Static

PHP echo and print Statements


echo and print are more or less the same. They are both used to output data to the screen.

The differences are small: echo has no return value while print has a return value of 1 so it can be used
in expressions. echo can take multiple parameters (although such usage is rare) while print can take
one argument. echo is marginally faster than print.

The PHP echo Statement


The echo statement can be used with or without parentheses: echo or echo().
Display Text

Example :
<!DOCTYPE html>
<html>
<body>

<?php
echo "<h2>WELCOME</h2>";
echo "Hello world!<br>";
7 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>

</body>
</html>

Display Variables

The following example shows how to output text and variables with the echo
statement:
Example :
<!DOCTYPE html>
<html>
<body>

<?php
$txt1 = "Iam Variable-1";
$txt2 = "Iam Variable-2";
$x = 5;
$y = 4;

echo "<h2>" . $txt1 . "</h2>";


echo "This is " . $txt2 . "<br>";
echo $x + $y;
?>

</body>
</html>

The PHP print Statement

The print statement can be used with or without parentheses: print or print().

Display Text

<!DOCTYPE html>
<html>
<body>

<?php
print "<h2>Hi to all</h2>";
print "Hello world!<br>";
print "My Message";
?>

</body>
8 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
</html>

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
- Float (floating point numbers - also called double)
- Boolean
- Array
- Object--oops
- NULL
- Resource

PHP String - Example


<!DOCTYPE html>
<html>
<body>

<?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>

</body>
</html>

PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and


2,147,483,647.

Example :
<!DOCTYPE html>
<html>
<body>

<?php
$x = 5985;
?>

9 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
</body>
</html>

PHP Float

A float (floating point number) is a number with a decimal point or a number in


exponential form.

Example :
<!DOCTYPE html>
<html>
<body>

<?php
$x = 10.365;
?>

</body>
</html>

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.

Example :
$x = true;
$y = false;

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

Note: Unlike variables, constants are automatically global across the entire script.

Create a PHP Constant


To create a constant, use the define() function.

Syntax :
define(name, value, case-insensitive)

Parameters:
- name: Specifies the name of the constant
10 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
- value: Specifies the value of the constant
- case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false

Example :

<!DOCTYPE html>
<html>
<body>

<?php
// case-sensitive constant name
define("GREETING", "Welcome to PHP Class");
echo GREETING;
?>

</body>
</html>

PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
• Conditional assignment operators

PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.

Operator Name Example Result


+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power

11 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
PHP Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a
variable.

The basic assignment operator in PHP is "=". It means that the left operand gets set
to the value of the assignment expression on the right.

Assignment Same as... Description


x=y x=y The left operand gets set to the value of the
expression on the right
x += y x = x +y Addition
x -= y x = x -y Subtraction
x *= y x = x *y Multiplication
x /= y x = x /y Division
x %= y x = x %y Modulus

PHP Comparison Operators


The PHP comparison operators are used to compare two values (number or string):

Operator Name Example Result


== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they
are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or
they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater equal to $x >= $y Returns true if $x is greater than or equal
to $y
<= Less or equal to $x <= $y Returns true if $x is less than or equal to
$y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or
greater than zero, depending on if $x is
less than, equal to, or greater than $y.

PHP Increment / Decrement Operators

The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

Operator Name Description


++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x

12 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator Name Example Result


and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

PHP Strings – methods/functions

PHP String Functions

- strlen() - Return the Length of a String


- str_word_count() - Count Words in a String
- strrev() - Reverse a String
- strpos() - Search For a Text Within a String
- str_replace() - Replace Text Within a String

PHP Date & Time Functions


Get a 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.

Get a Time

Here are some characters that are commonly used for times:

H - 24-hour format of an hour (00 to 23)


h - 12-hour format of an hour with leading zeros (01 to 12)
13 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
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)
=======================================

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

===================================

<!DOCTYPE html>
<html>
<body>

<?php
echo "The time is " . date("h:i:sa");
?>

</body>
</html>

===================================

<!DOCTYPE html>
<html>
<body>

<?php
// Prints the day
echo date("l") . "<br>";
?>

</body>
</html>

14 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
==========================================

<!DOCTYPE html>
<html>
<body>

<?php
$mydate=getdate(date());
echo "$mydate[weekday], $mydate[month] $mydate[mday],
$mydate[year]";
?>

</body>
</html>

===================================
</body>
</html>

<!DOCTYPE html>
<html>
<body>

<?php
// Prints the day
echo gmdate("l") . "<br>";
?>

</body>
</html>

=================================

<!DOCTYPE html>
<html>
<body>

<?php
$date=date_create("2013-05-01");

date_time_set($date,13,24);
echo date_format($date,"Y-m-d H:i:s") . "<br>";

date_time_set($date,12,20,55);
echo date_format($date,"Y-m-d H:i:s");
?>
15 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni

</body>
</html>

=======================================

<!DOCTYPE html>
<html>
<body>

<?php
$t=time();
echo(date("Y-m-d",$t));
?>

</body>
</html>

=======================================

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

===================================

PHP Conditional Statements

Very often when you write code, you want to perform different actions for different
conditions. You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:

- if statement - executes some code if one condition is true.


- if...else statement - executes some code if a condition is true and another code if
that condition is false
16 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
- if...elseif...else statement - executes different codes for more than two
conditions.
- switch statement - selects one of many blocks of code to be executed.

PHP - The if Statement

SynTax:

if (condition)
{
code to be executed if condition is true;
}

Example :
<!DOCTYPE html>
<html>
<body>

<?php
$t = date("H");

if ($t < "20")


{
echo "The Value is true";
}
?>

</body>
</html>

PHP - The if...else Statement

Syntax :
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

Example :
17 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
<!DOCTYPE html>
<html>
<body>

<?php
$t = date("H");

if ($t < "20")


{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>

</body>
</html>

PHP - The if...elseif...else Statement

Syntax:
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}

Example :
<!DOCTYPE html>
<html>
<body>

<?php
$t = 25;

if ($t < "10") {


echo "Greater than 10";
} elseif ($t < "20") {
echo "Greater than 20";
} else {
echo "The number is greater than 10 and 20";
}
18 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
?>

</body>
</html>

PHP - The switch Statement

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

Example :
<!DOCTYPE html>
<html>
<body>

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

19 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
</body>
</html>

PHP Loops

- 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

The PHP while Loop

Syntax:
while (condition is true) {
code to be executed;
}

Example:
<!DOCTYPE html>
<html>
<body>

<?php
$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>

</body>
</html>

The PHP do...while Loop

Syntax :
do {
code to be executed;
} while (condition is true);

Example:
<!DOCTYPE html>
<html>
<body>
20 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni

<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

</body>
</html>

The PHP for Loop

Syntax:
for (init counter; test counter; increment counter)
{
code to be executed for each iteration;
}

Example:
<!DOCTYPE html>
<html>
<body>

<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

</body>
</html>

PHP Break and Continue

Example : Break
<!DOCTYPE html>
<html>
<body>

<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
21 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
}
echo "The number is: $x <br>";
}
?>

</body>
</html>

Example : Continue
<!DOCTYPE html>
<html>
<body>

<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>

</body>
</html>

PHP Functions

PHP User Defined Functions


Besides the built-in PHP functions, it is possible to create your own functions.

A function is a block of statements that can be used repeatedly in a program.


A function will not execute automatically when a page loads.
A function will be executed by a call to the function. Science

Syntax:
function functionName()
{
code to be executed;
}

Example:
<!DOCTYPE html>
<html>
<body>

<?php
22 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
function writeMsg() {
echo "Hello world!";
}

writeMsg();
?>

</body>
</html>

PHP Function Arguments

Example:
<!DOCTYPE html>
<html>
<body>

<?php

function addNumbers(int $a, int $b)


{
return $a + $b;
}
echo addNumbers(5, 5);

?>

</body>
</html>

PHP Functions - Returning values

<!DOCTYPE html>
<html>
<body>

<?php
function sum(int $x, int $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);
?>
23 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni

</body>
</html>

PHP Return Type Declarations

To declare a type for the function return, add a colon ( : ) and the type right before
the opening curly ( { )bracket when declaring the function.

<!DOCTYPE html>
<html>
<body>

<?php
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>

</body>
</html>

Create an Array in PHP

In PHP, the array() function is used to create an array:

In PHP, there are three types of arrays:

Indexed arrays - Arrays with a numeric index


Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays

Example :
<!DOCTYPE html>
<html>
<body>

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>

</body>
24 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
</html>

Example :
<!DOCTYPE html>
<html>
<body>

<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

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


echo $cars[$x];
echo "<br>";
}
?>

</body>
</html>

PHP Associative Arrays

PHP foreach Loop : 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.

Syntax:
foreach ($array as $value) {
code to be executed;
}

Example :
<!DOCTYPE html>
<html>
<body>

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

foreach ($colors as $value) {


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

</body>
</html>
25 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
Example :
<!DOCTYPE html>
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

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


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

</body>
</html>

PHP - Two-dimensional Arrays


A two-dimensional array is an array of arrays (a three-dimensional array is an array
of arrays of arrays).

Example :
<!DOCTYPE html>
<html>
<body>

<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";


echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>

</body>
</html>

PHP OOPs:

OOP stands for Object-Oriented Programming.


26 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni

Procedural programming is about writing procedures or functions that perform


operations on the data, while object-oriented programming is about creating objects
that contain both data and functions.

Object-oriented programming has several advantages over procedural programming:

OOP is faster and easier to execute


OOP provides a clear structure for the programs
OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
OOP makes it possible to create full reusable applications with less code and shorter
development time

Define a Class & Objects

Syntax :
<?php
class Fruit {
// code goes here...
}
?>

Example :
<!DOCTYPE html>
<html>
<body>

<?php
class Fruit {
// Properties
public $name;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit();


$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
27 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>

</body>
</html>

Unit-III Working with Forms

$_PHP_SELF Variable
The PHP default variable $_PHP_SELF is used for the PHP script name and when you
click "submit" button then same PHP script will be called and will produce following
result.

Example :
<?php
echo "Welcome ". $_POST["uname"]. "<br>";
echo "Your email address is ". $_POST["email"];
?>

<HTML>
<BODY>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name : <input type = "text" name="uname"> <br>
E-mail : <input type = "text" name="email"> <br>
<input type="Submit">
</form>

</BODY>
</HTML>

$_REQUEST Variable
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and
$_COOKIE. It is used to get the result from form data sent with both the GET and
POST methods.

Example :
<?php
echo "Welcome ". $_REQUEST["uname"]. "<br>";
echo "Your email address is ". $_REQUEST["email"];
?>

28 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
<HTML>
<BODY>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name : <input type = "text" name="uname"> <br>
E-mail : <input type = "text" name="email"> <br>
<input type="Submit">
</form>

</BODY>
</HTML>

PHP Include/require Files

The include (or require) statement takes all the text/code/markup that exists in the
specified file and copies it into the file that uses the include statement.

Including files is very useful when you want to include the same PHP, HTML, or text
on multiple pages of a website.

- require will produce a fatal error (E_COMPILE_ERROR) and stop the script
- include will only produce a warning (E_WARNING) and the script will continue

Syntax :
include 'filename';
or
require 'filename';

Example : Create “footer.php” file


<?php
echo "<p>Copyright &copy; 2021-" . date("Y") . "adonicollege.com</p>";
?>

Example : Create “myfile.html” file


<html>
<body>

<h1>Welcome to my home page!</h1>


<p>Welcome</p>
<?php include 'footer.php';?>

</body>
</html>

Output :

29 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
Welcome to my home page!
Welcome
Copyright © 2020-2021 adonicollege.com

FORM ELEMENTS
<HTML>
<BODY>
<H1> Form Elements Syntax </H1>
<FORM>

<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="pwd">Password:</label><br>
<input type="password" id="pwd" name="pwd">
<br>
<br>
<label for="email">Enter your email:</label>
<input type="email" id="email" name="email">
<br>
<br>
<select name="FRUITS">
<option value="f1">BANANA</option>
<option value="f2">GRAPES</option>
<option value="f3">APPLE</option>
<option value="f4">MANGO</option>
<option value="f5">PINEAPPLE</option>
<option value="f6">WATER MELON</option>
</select>
<br>
<br>

<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">


<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
<br>
<br>
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label><br><br>
30 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
<br>
<br>
<input type="date">
<label for="bdaymonth">Birthday (month and year):</label>
<input type="month" id="bdaymonth" name="bdaymonth">
<br>
<br>

<textarea rows="4" cols="50">Address:</textarea>


<br>
<br>

<label for="quantity">Quantity (between 1 and 5):</label>


<input type="number" id="quantity" name="quantity" min="1" max="5">
<br>
<br>

<label for="appt">Select a time:</label>


<input type="time" id="appt" name="appt">
<br>
<br>
<label for="homepage">Add your homepage:</label>
<input type="url" id="homepage" name="homepage">
<br>
<br>
<input type="submit">
<br>
<br>
<input type="reset">

</FORM>
</BODY>
</FORM>

PHP - Predefined Variables

PHP provides a large number of predefined variables to any script which it runs. PHP
provides an additional set of predefined arrays containing variables from the web
server the environment, and user input. These new arrays are called superglobals −

PHP Superglobals
• $GLOBALS
• $_SERVER
• $_GET
• $_POST
• $_FILES
31 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
• $_REQUEST
• $_COOKIE
• $_SESSION
• $_PHP_SELF
• $php_errormsg

$GLOBALS

Contains a reference to every variable which is currently available within the global
scope of the script. The keys of this array are the names of the global variables.

$_SERVER

This is an array containing information such as headers, paths, and script locations.
The entries in this array are created by the web server.

$_GET

An associative array of variables passed to the current script via the HTTP GET
method.

$_POST

An associative array of variables passed to the current script via the HTTP POST
method.

$_FILES

An associative array of items uploaded to the current script via the HTTP POST
method.

$_REQUEST

An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.

$_COOKIE

An associative array of variables passed to the current script via HTTP cookies.

$_SESSION

An associative array containing session variables available to the current script.

$_PHP_SELF

A string containing PHP script file name in which it is called.

$php_errormsg

$php_errormsg is a variable containing the text of the last error message generated
by PHP.

PHP - Files & I/O

32 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
• Opening a file
• Reading a file
• Writing a file
• Closing a file
Opening and Closing Files

fopen() : The PHP fopen() function is used to open a file. It requires two arguments
stating first the file name and then mode in which to operate.

fclose() : The fclose() function requires a file pointer as its argument and then
returns true when the closure succeeds or false if it fails.

Modes
r - Opens the file for reading only. Places the file pointer at the beginning of the file.
r+ - Opens the file for reading and writing. Places the file pointer at the beginning of
the file.
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.
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.
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.
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.

• Open a file using fopen() function.


• Get the file's length using filesize() function.
• Read the file's content using fread() function.
• Close the file with fclose() function.

PHP readfile() Function

The PHP code to read the file and write it to the output buffer is as follows (the
readfile() function returns the number of bytes read on success)

Example : program on readfile() function

33 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
<html>
<body>

<?php
echo readfile("myfile.txt");
?>

</body>
</html>

Example : fopen() program

<!DOCTYPE html>
<html>
<body>

<?php
$myfile = fopen("myfile.txt", "r");
echo fread($myfile, filesize("myfile.txt"));
fclose($myfile);
?>

</body>
</html>

A new file can be written or text can be appended to an existing file using the PHP
fwrite() function. This function requires two arguments specifying a file pointer and
the string of data that is to be written.

Example: fwrite() program


<html>
<body>

<?php
$myfile = fopen("newfile.txt", "w");
$txt = "Harish";
fwrite($myfile, $txt);
$txt = "Eranna";
fwrite($myfile, $txt);
fclose($myfile);
?>

</body>
</html>

Example : on reading a file


34 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>

<?php
$filename = "tmp.txt";
$file = fopen( $filename, "r" );

if( $file == false ) {


echo "Error in opening file" ;
exit();
}

$filesize = filesize( $filename );


$filetext = fread( $file, $filesize );
fclose( $file );

echo "File size : $filesize bytes" ;


echo "<pre>$filetext</pre>" ;
?>

</body>
</html>

Example : Writing a file


<?php
$filename = "/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>

35 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
<?php
$filename = "newfile.txt";
$file = fopen( $filename, "r" );

if( $file == false ) {


echo "Error in opening file";
exit();
}

$filesize = filesize( $filename );


$filetext = fread( $file, $filesize );

fclose( $file );

echo "File size : $filesize bytes";


echo "$filetext" ;
echo "file name: $filename";
?>

</body>
</html>

File Uploads

Web browsers support file uploads, PHP makes available to deal with this kind of
input. Information about the uploaded file becomes available to you in the $_FILES
superglobal, which is indexed by the name of the upload field (or fields) in the form.
The corresponding value for each of these keys is an associative array. These fields
are :

$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is not used yet (will be used later)
$imageFileType holds the file extension of the file (in lower case)
Next, check if the image file is an actual image or a fake image

Element Contains Example


$_FILES[‘fileupload’][‘name’] Original name of uploaded File flower.gif
$_FILES[‘fileuploaad’] Path of temporary file /tmp/image[‘fname’]
$_FILES[‘fileupload’][‘size’] Size(in bytes) of uploaded file 6835
$_FILES[‘fileupload’][‘type’] MIME (Multipurpose Internet Image/gif
Mail Extensions) type of
uploaded file

Some rules to follow for the HTML form above:

36 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
• Make sure that the form uses method="post"
• The form also needs the following attribute: enctype="multipart/form-data". It
specifies which content-type to use when submitting the form.

Example : create myupload.html file


<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">

Select image to upload:


<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>

Example : create upload.php file

<?php
$target_dir = "file/";
$target_file = $target_dir.basename($_FILES["fileToUpload"]["name"]);
if(isset($_POST["submit"]))
{
if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$target_file))
{
echo "the file".basename($_FILES["fileToUpload"]["name"])."has been uploaded";
}
else
{
echo "sorry there was an error";
}
}
?>

Reading Lines from a File with fgets() and feof()

fgets() : The fgets() function reads the file until it reaches a newline character (“\n”),
the number of bytes specified in the length argument, or the end of the file—
whichever comes first:

Example: fgets()

Create a file in notepad : text.txt


Hello, this is a test file.
There are three lines here.

37 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
This is the last line.
Create a php file with the following code

<!DOCTYPE html>
<html>
<body>

<?php
$file = fopen("test.txt","r");
//Output lines until EOF is reached

while(! feof($file))
{
$line = fgets($file);
echo $line. "<br>";
}

fclose($file);
?>

</body>
</html>

Output :
Hello, this is a test file.
There are three lines here.
This is the last line.

fgetc: The fgetc() function returns a single character from an open file.

Example: fgetc()

Create a file in notepad : text.txt


Hello, this is a test file.
There are three lines here.
This is the last line.

Create a php file with the following code

<html>
<body>

<?php
$file = fopen("test.txt","r");
echo fgetc($file);
38 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
fclose($file);
?>

</body>
</html>

Output :
H

Example program on fgetc with feof()

<html>
<body>

<?php
$file = fopen("test.txt","r");
while (! feof($file))
{
echo fgetc($file);
}
fclose($file);
?>

</body>
</html>

Output :
Hello, this is a test file. There are three lines here. This is the last line.

Writing to a File with fwrite() or fputs()

The fwrite() function accepts a file resource and a string, and then writes the string to
the file.

The fputs() function works in exactly the same way:

Example :
fwrite($fp, “hello world”);
fputs($fp, “hello world”);

PHP fpassthru() Function

The fpassthru() function reads from the current position in a file - until EOF, and then
writes the result to the output buffer.

39 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
Note: When using fpassthru() on a binary file on Windows, remember to open the file
in binary mode.

Example program :

<html>
<body>

<?php
$file = fopen("test.txt","r");
// Read first line
fgets($file);

// Read from the current position in file - until EOF, and then write the
result to the output buffer
echo fpassthru($file);

fclose($file);
?>

</body>
</html>

Open Pipes - popen()

The popen() function used to open a pipe to the program specified by the user using
the command parameter. It returns a file pointer which is identical to that returned by
fopen(), but it is unidirectional in nature i.e it can be only used for reading or writing.
The popen() pointer can be used with fgets(), fgetss(), and fwrite(). The file pointer
initiated by the popen() function must be closed with pclose().

The command and the mode are sent as parameters to the popen() function and it
returns a unidirectional file pointer on success or FALSE on failure.

Syntax: popen(command, mode)

Parameters Used: The popen() function in PHP accepts two parameters.

command : It is a mandatory parameter which specifies the command to be executed.


mode : It is a mandatory parameter which specifies the connection mode such as
read only(r) or write only(w).

It returns a file pointer which is identical to that returned by fopen(), but it is


unidirectional in nature.

Example :
40 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni

<?php
$file = popen("/bin/ls","r");

//some code to be executed


pclose($file);
?>

Hidden fields

Hidden fields allow us to send all kinds of information along with a form message,
without the user having to be involved in the process. Hidden fields can also be used
to pass information back to scripts. This may include security tokens, or the name of
the relevant row in the database. The user does not need to see this data, but it is
passed back to the server on submission so that scripts function correctly behind the
scenes

A hidden field let web developers include data that cannot be seen or modified by
users when a form is submitted.

A hidden field often stores what database record that needs to be updated when the
form is submitted.

Example : on hidden fields

<form action=#>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<input type="hidden" id="cid" name="cid" value="3487">
<input type="submit" value="Submit">
</form>

COOKIES

Cookies are text files stored on the client computer and they are kept of use tracking
purpose. PHP transparently supports HTTP cookies.

There are three steps involved in identifying returning users −

• Server script sends a set of cookies to the browser.


For ex: name, age, or identification number etc.
• Browser stores this information on local machine for future use.
• When next time browser sends any request to web server then it sends those
cookies information to the server and server uses that information to identify
the user.

41 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
Setting Cookies with PHP

PHP provided setcookie() function to set a cookie. This function requires upto six
arguments and should be called before <html> tag. For each cookie this function has
to be called separately.

Syntax :
setcookie(name, value, expire, path, domain, security);

• Name − This sets the name of the cookie and is stored in an environment
variable called HTTP_COOKIE_VARS. This variable is used while accessing
cookies.
• Value − This sets the value of the named variable and is the content that you
actually want to store.
• Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan
1970. After this time cookie will become inaccessible. If this parameter is not
set then cookie will automatically expire when the Web Browser is closed.
• Path − This specifies the directories for which the cookie is valid. A single
forward slash character permits the cookie to be valid for all directories.
• Domain − This can be used to specify the domain name in very large domains
and must contain at least two periods to be valid. All cookies are only valid for
the host and domain which created them.
• Security − This can be set to 1 to specify that the cookie should only be sent
by secure transmission using HTTPS otherwise set to 0 which mean cookie can
be sent by regular HTTP.

Example :

<?php
setcookie("name", "Adoni", time()+3600, "/","", 0);
setcookie("age", "60", time()+3600, "/", "", 0);
?>

<html>
<body>
<?php
echo "Set Cookies"
?>
</body>
</html>

Accessing Cookies with PHP

PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE
or $HTTP_COOKIE_VARS variables.

42 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
Following example will access all the cookies set in above example.

Example :
<html>
<body>

<?php
echo $_COOKIE["name"]. "<br />";
echo $HTTP_COOKIE_VARS["name"]. "<br />";

echo $_COOKIE["age"] . "<br />";


echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>

</body>
</html>

isset()
You can use isset() function to check if a cookie is set or not.

Example :
<html>
<body>

<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>

</body>
</html>

Deleting Cookie with PHP


To delete a cookie you should call setcookie() with the name argument only.

Example :
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>

<html>
<body>

43 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
<?php echo "Deleted Cookies" ?>

</body>
</html>

PHP Session

An alternative way to make data accessible across the various pages of an entire
website is to use a PHP Session.

A session creates a file in a temporary directory on the server where registered


session variables and their values are stored. This data will be available to all pages
on the site during that visit.

A session ends when the user loses the browser or after leaving the site, the server
will terminate the session after a predetermined period of time, commonly 30 minutes
duration.

What is a PHP Session?


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 PHP session is easily started by making a call to the session_start() function.This


function first checks if a session is already started and if none is started then it starts
one. It is recommended to put the call to session_start() at the beginning of the page.

Session variables are stored in associative array called $_SESSION[]. These variables
can be accessed during lifetime of a session.

Example : Program on setting Session variables


File name : setsession1.php

<?php
session_start();
44 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
?>

<!DOCTYPE html>
<html>
<body>

<?php
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

Example : Program on getting Session variables


File name : setsession2.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>

Example : Program on display all session variable created

<?php
session_start();
?>

<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

45 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
</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>

Redirecting the user

The header function in PHP can be used to redirect the user from one page to
another. It is an in-built function that sends raw HTTP header to the destination
(client).

Syntax: header( $header_value, $replace_value, $http_response_code)

Following are the parameters −

• The ‘header_value’ in the function is used to store the header string.


• The ‘replace_value’ parameter stores the value that needs to be replaced.
• The ‘response_code’ is used to store the HTTP response code.

Example:

<?php
header("Location: http://www.google.com");
46 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
exit;
?>

Note: The die() or exit() function after header is mandatory. If die() or exit() is not
put after the header(‘Location: ….’) then script may continue resulting in
unexpected behavior. For example, result in content being disclosed that actually
wanted to prevent with the redirect (HTTP 301).

PHP Directory Functions

The directory functions allow you to retrieve information about directories and their
contents.

Function - Description
mkdir() - Create a directory
chdir() - Changes the current directory
dir() - Returns an instance of the Directory class
opendir() - Opens a directory handle
rmdir() - Remove directory
readdir() - Returns an entry from a directory handle

mkdir() - Create a directory


The mkdir() function enables you to create a directory. The mkdir() function returns
true if it successfully creates a directory or false if it doesn’t.

chdir() - Changes the current directory


The chdir() function changes the current directory.

Example : chdir() php program

<?php
// Get current directory
echo getcwd() . "<br>";

// Change directory
chdir("images");

// Get current directory


echo getcwd();
?>

dir() - Returns an instance of the Directory class

The dir() function returns an instance of the Directory class

47 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
Example : dir()

Executing external programs

• exec()
• passthru()
• system()

In PHP there are two important methods to execute programs, and these are exec()
and passthru(). Both of these two take a minimum of one parameter, which is the
name of the program you want to run, but the difference between them is that exec()
runs the program then sends back the last line outputted from that program as its
return value. The passthru() function, on the other hand, runs the program specified
and prints out all the output that program generates. Calling exec() is usually
preferred when the output of your program is irrelevant, whereas passthru()
automatically prints your output.

exec(string COMMAND, array OUTPUT, int RETURN_VARIABLE);

• COMMAND is the command we want to execute with the exec() function. The
command should be a string value or variable. COMMAND is a mandatory
parameter.
• OUTPUT is the output of the COMMAND execution. OUTPUT is an array that can
hold multiple values or lines. OUTPUT is optional where it can be omitted.
• RETURN_VARIABLE is the return value of the given COMMAND. RETURN _VALUE
is generally the process status of the command. RETURN_VALUE is an integer
and optional to use.

Example: exec() and passthru()

<?php
print exec("uptime");
passthru("who");
?>

system() : The system() function is similar to the exec() function in that it launches
an external application, and it utilizes a scalar variable for storing a return value:

system(“/path/to/somecommand”,$return_val);

The system() function differs from exec() in that it outputs information directly to the
browser, without programmatic intervention.

Example: system()

<?php
48 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
system(“calc”);
system(“notepad”);
?>

Example: system()

<?php
echo “<pre>”;
system(“cmd”);
echo “<hr><h3>”;
system(“dir”);
echo “</h3><hr>”;
echo “</pre>”;
?>

Working with Images:

Understanding the Image

A standard installation of PHP has many built-in functions for dynamically creating and
manipulating images. Popular uses include the creation of charts and graphs and the
modifications of existing images to display watermarks. With a few adjustments, we
can expand the functionality even more.

A Word About Color

We use the RGB color system. Using decimal values from 0 to 255 for each of the red,
green, and blue (R, G, and B) entries, you can define a specific color. A value of 0
indicates no amount of that specific color, and a value of 255 indicates the highest
amount of that color.

Examples:-
pure red is (255,0,0),
pure green has a value of (0,255,0),
pure blue has a value of (0,0,255). (255,255,255)

The basic PHP function used to create a new image is called ImageCreate(), but
creating an image is not as simple as just calling the function. Creating an image is a
stepwise process and includes the use of several different PHP functions.

The following line creates a drawing area that is 300 pixels wide by 300 pixels
high:

$myImage = ImageCreate(300,300);

The following examples define five such colors (black, white, red, green, and
49 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
blue, respectively), using the ImageColorAllocate() function and RGB values:

$black = ImageColorAllocate($myImage, 0, 0, 0);


$white = ImageColorAllocate($myImage, 255, 255, 255);
$red = ImageColorAllocate($myImage, 255, 0, 0);
$green = ImageColorAllocate($myImage, 0, 255, 0);
$blue = ImageColorAllocate($myImage, 0, 0, 255);

Drawing Shapes and Lines

Several PHP functions can assist you in drawing shapes and lines on your canvas:

. ImageEllipse() is used to draw an ellipse.


. ImageArc() is used to draw a partial ellipse.
. ImagePolygon() is used to draw a polygon.
. ImageRectangle() is used to draw a rectangle.
. ImageLine() is used to draw a line.

Example program:-
<?php
$im = ImageCreate(200,200);
$white = ImageColorAllocate($im,0xFF,0xFF,0xFF);
$black = ImageColorAllocate($im,0x00,0x00,0x00);
ImageFilledRectangle($im,50,50,150,150,$black);
header('Content-Type: image/png');
ImagePNG($im);
?>

Using a Color Fill

PHP has image functionsdesigned to fill areas as well:


. ImageFilledEllipse() is used to fill an ellipse.
Ex: ImageFilledEllipse($im, 180, 220, 150, 50, $blue);
. ImageFilledArc() is used to fill a partial ellipse.
Ex: imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE);

. ImageFilledPolygon() is used to fill a polygon.


Ex: ImageFilledPolygon($im, $points, $num_of_points, $colour);

. ImageFilledRectangle() is used to fill a rectangle


Ex: ImageFilledRectangle($im,50,50,150,150,$black);

Example :

<?php
//create the canvas
50 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
$myImage = ImageCreate(300,300);

//set up some colors for use on the canvas


$black = ImageColorAllocate($myImage, 0, 0, 0);
$white = ImageColorAllocate($myImage, 255, 255, 255);
$red = ImageColorAllocate($myImage, 255, 0, 0);
$green = ImageColorAllocate($myImage, 0, 255, 0);
$blue = ImageColorAllocate($myImage, 0, 0, 255);

//draw some rectangles


ImageFilledRectangle($myImage, 15, 15, 95, 155, $red);
ImageFilledRectangle($myImage, 95, 155, 175, 295, $white);
ImageFilledRectangle($myImage, 175, 15, 255, 155, $red);

//output the image to the browser


header (“Content-type: image/png”);
ImagePng($myImage);

//clean up after yourself


ImageDestroy($myImage);
?>

MYSQL

MySQL is an open-source relational database management system (RDBMS). Its


name is a combination of "My", the name of co-founder Michael Widenius's
daughter,and "SQL", the abbreviation for Structured Query Language. A relational
database organizes data into one or more data tables in which data types may be
related to each other; these relations help structure the data. SQL is a language
programmers use to create, modify and extract data from the relational database, as
well as control user access to the database. In addition to relational databases and
SQL, an RDBMS like MySQL works with an operating system to implement a relational
database in a computer's storage system, manages users, allows for network access
and facilitates testing database integrity and creation of backups.

MySQL is free and open-source software under the terms of the GNU General Public
License, and is also available under a variety of proprietary licenses. MySQL was
owned and sponsored by the Swedish company MySQL AB, which was bought by Sun
Microsystems (now Oracle Corporation). In 2010, when Oracle acquired Sun,
Widenius forked the open-source MySQL project to create MariaDB.

MySQL has stand-alone clients that allow users to interact directly with a MySQL
database using SQL, but more often, MySQL is used with other programs to
implement applications that need relational database capability. MySQL is a
component of the LAMP web application software stack (and others), which is an
acronym for Linux, Apache, MySQL, Perl/PHP/Python. MySQL is used by many
51 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
database-driven web applications, including Drupal, Joomla, phpBB, and WordPress.
MySQL is also used by many popular websites, including Facebook, Flickr, MediaWiki,
Twitter, and YouTube.

With PHP, you can connect to and manipulate databases.

MySQL is the most popular database system used with PHP.

What is MySQL?
MySQL is a database system used on the web
MySQL is a database system that runs on a server
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, and easy to use
MySQL uses standard SQL
MySQL compiles on a number of platforms
MySQL is free to download and use
MySQL is developed, distributed, and supported by Oracle Corporation
MySQL is named after co-founder Monty Widenius's daughter: My

The data in a MySQL database are stored in tables. A table is a collection of related
data, and it consists of columns and rows.

Databases are useful for storing information categorically. A company may have a
database with the following tables:

Employees
Products
Customers
Orders

• Connecting to MySQL database − Learn how to use PHP to open and close a
MySQL database connection.
• Create MySQL Database Using PHP − This part explains how to create MySQL
database and tables using PHP.
• Delete MySQL Database Using PHP − This part explains how to delete MySQL
database and tables using PHP.
• Insert Data to MySQL Database − Once you have created your database and
tables then you would like to insert your data into created tables. This session
will take you through real example on data insert.
• Retrieve Data from MySQL Database − Learn how to fetch records from MySQL
database using PHP.
• Using Paging through PHP − This one explains how to show your query result
into multiple pages and how to create the navigation link.
• Updating Data into MySQL Database − This part explains how to update existing
records into MySQL database using PHP.

52 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
• Deleting Data from MySQL Database − This part explains how to delete or
purge existing records from MySQL database using PHP.

Connecting to MySQL database :

Opening Database Connection

PHP provides mysql_connect function to open a database connection. This function


takes five parameters and returns a MySQL link identifier on success, or FALSE on
failure.

Syntax : connection mysql_connect(server,user,passwd,new_link,client_flag);

server

Optional − The host name running database server. If not specified then default value
is localhost:3306.

user

Optional − The username accessing the database. If not specified then default is the
name of the user that owns the server process.

passwd

Optional − The password of the user accessing the database. If not specified then
default is an empty password.

new_link

Optional − If a second call is made to mysql_connect() with the same arguments, no


new connection will be established; instead, the identifier of the already opened
connection will be returned.

client_flags

Optional − A combination of the following constants −

• MYSQL_CLIENT_SSL − Use SSL encryption


• MYSQL_CLIENT_COMPRESS − Use compression protocol
• MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names
• MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity
before closing the connection

Closing Database Connection

Its simplest function mysql_close PHP provides to close a database connection. This
function takes connection resource returned by mysql_connect function. It returns
TRUE on success or FALSE on failure.

Syntax : bool mysql_close ( resource $link_identifier );

Example :

53 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
<?php
$dbhost = 'localhost:83';
$dbuser = 'csserver';
$dbpass = 'aasc';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>

Creating a Database

To create and delete a database you should have admin privilege. Its very easy to
create a new MySQL database. PHP uses mysql_query function to create a MySQL
database. This function takes two parameters and returns TRUE on success or FALSE
on failure.

Syntax : bool mysql_query( sql, connection );

sql : Required - SQL query to create a database

connection : Optional - if not specified then last opend connection by mysql_connect


will be used.

Example :
<?php
$dbhost = 'localhost:83';
$dbuser = 'csserver';
$dbpass = 'aasc';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn )
{
die('Could not connect: ' . mysql_error());
}

echo 'Connected successfully';


$sql = 'CREATE Database test_db';
$retval = mysql_query( $sql, $conn );

if(! $retval )
{
die('Could not create database: ' . mysql_error());
}

54 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni

echo "Database test_db created successfully\n";


mysql_close($conn);
?>

Creating Database Tables

To create tables in the new database you need to do the same thing as creating the
database. First create the SQL query to create the tables then execute the query
using mysql_query() function.

Example :
<?php

$dbhost = 'localhost:83';
$dbuser = 'csserver';
$dbpass = 'aasc';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}

echo 'Connected successfully';

$sql = 'CREATE TABLE employee( '.


'emp_id INT NOT NULL AUTO_INCREMENT, '.
'emp_name VARCHAR(20) NOT NULL, '.
'emp_address VARCHAR(20) NOT NULL, '.
'emp_salary INT NOT NULL, '.
'join_date timestamp(14) NOT NULL, '.
'primary key ( emp_id ))';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );

if(! $retval ) {
die('Could not create table: ' . mysql_error());
}

echo "Table employee created successfully\n";

mysql_close($conn);
?>

55 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
Deleting a Database

If a database is no longer required then it can be deleted forever. You can use pass
an SQL command to mysql_query to delete a database.

Example :
<?php
$dbhost = 'localhost:83';
$dbuser = 'csserver';
$dbpass = 'aasc';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}

$sql = 'DROP DATABASE test_db';


$retval = mysql_query( $sql, $conn );

if(! $retval ) {
die('Could not delete database test_db: ' . mysql_error());
}

echo "Database deleted successfully\n";

mysql_close($conn);
?>

Deleting a Table

Its again a matter of issuing one SQL command through mysql_query function to
delete any database table. But be very careful while using this command because by
doing so you can delete some important information you have in your table.

Example :
<?php
$dbhost = 'localhost:83';
$dbuser = 'csserver';
$dbpass = 'aasc';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}

$sql = 'DROP TABLE employee';


56 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
$retval = mysql_query( $sql, $conn );

if(! $retval ) {
die('Could not delete table employee: ' . mysql_error());
}

echo "Table deleted successfully\n";

mysql_close($conn);
?>

Insert Data into MySQL Database

Data can be entered into MySQL tables by executing SQL INSERT statement through
PHP function mysql_query. Below a simple example to insert a record into employee
table.

Example:
<?php
$dbhost = 'localhost:83';
$dbuser = 'csserver';
$dbpass = 'aasc';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}

$sql = 'INSERT INTO employee '.


'(emp_name,emp_address, emp_salary, join_date) '.
'VALUES ( "guest", "XYZ", 2000, NOW() )';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );

if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}

echo "Entered data successfully\n";

mysql_close($conn);
?>

57 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
Getting Data From MySQL Database

Data can be fetched from MySQL tables by executing SQL SELECT statement through
PHP function mysql_query. You have several options to fetch data from MySQL.

The most frequently used option is to use function mysql_fetch_array(). This function
returns row as an associative array, a numeric array, or both. This function returns
FALSE if there are no more rows.

Below is a simple example to fetch records from employee table.

Example:
<?php
$dbhost = 'localhost:83';
$dbuser = 'csserver';
$dbpass = 'aasc';

$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}

$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';


mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );

if(! $retval ) {
die('Could not get data: ' . mysql_error());
}

while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {


echo "EMP ID :{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".
"EMP SALARY : {$row['emp_salary']} <br> ".
"--------------------------------<br>";
}

echo "Fetched data successfully\n";

mysql_close($conn);
?>

Updating Data into MySQL Database

58 Computer Science Department-AASC


PHP MATERIAL – The Arts and Science college :: Adoni
Data can be updated into MySQL tables by executing SQL UPDATE statement through
PHP function mysql_query.

Example:
<html>
<head>
<title>Update a Record in MySQL Database</title>
</head>

<body>
<?php
if(isset($_POST['update'])) {
$dbhost = 'localhost:83';
$dbuser = 'csserver';
$dbpass = 'aasc';

$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}

$emp_id = $_POST['emp_id'];
$emp_salary = $_POST['emp_salary'];

$sql = "UPDATE employee ". "SET emp_salary = $emp_salary ".


"WHERE emp_id = $emp_id" ;
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );

if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";

mysql_close($conn);
}
else
{
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<table width = "400" border =" 0" cellspacing = "1"
cellpadding = "2">

<tr>
<td width = "100">Employee ID</td>
59 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
<td><input name = "emp_id" type = "text"
id = "emp_id"></td>
</tr>

<tr>
<td width = "100">Employee Salary</td>
<td><input name = "emp_salary" type = "text"
id = "emp_salary"></td>
</tr>

<tr>
<td width = "100"> </td>
<td> </td>
</tr>

<tr>
<td width = "100"> </td>
<td>
<input name = "update" type = "submit"
id = "update" value = "Update">
</td>
</tr>

</table>
</form>
<?php
}
?>

</body>
</html>

Deleting Data from MySQL Database

Data can be deleted from MySQL tables by executing SQL DELETE statement through
PHP function mysql_query.

Example:
<html>

<head>
<title>Delete a Record from MySQL Database</title>
</head>

<body>
<?php
60 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
if(isset($_POST['delete'])) {
$dbhost = 'localhost:83';
$dbuser = 'csserver;
$dbpass = 'aasc';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}

$emp_id = $_POST['emp_id'];

$sql = "DELETE FROM employee WHERE emp_id = $emp_id" ;


mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );

if(! $retval ) {
die('Could not delete data: ' . mysql_error());
}

echo "Deleted data successfully\n";

mysql_close($conn);
}
else
{
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<table width = "400" border = "0" cellspacing = "1"
cellpadding = "2">

<tr>
<td width = "100">Employee ID</td>
<td><input name = "emp_id" type = "text"
id = "emp_id"></td>
</tr>

<tr>
<td width = "100"> </td>
<td> </td>
</tr>

<tr>
<td width = "100"> </td>
<td>
<input name = "delete" type = "submit"
61 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
id = "delete" value = "Delete">
</td>
</tr>

</table>
</form>
<?php
}
?>

</body>
</html>

Important questions
UNIT-1
1. Explain about Installation and configuration of MYSQL on Windows?
2. Explain about APACHE installation on windows?
3. What are the current and future versions of MySQL and Apache?
4. What is php? Explain the Advantages of php?
5. Explain about variables, datatypes and operators in PHP?
6. What is meant by switching flow(control statements)?
7. Explain about code block and Browser output?
8. Explain about XAMPP?

Unit-2
1. Explain about functions of Php in detail?
2. What is array? How to creating an Associate array with example?
3. Explain about variable Scope?(4M)
4. Discuss the array related function with an example?
5. How to creating objects with an examples?
6. Explain about formatting and investigating strings in PHP?
7. What are the various types of manipulating strings with php?
8. Explain the php by using date and time functions?

Unit-3
1. Explain about creating forms? Discuss the accessing form with user define array?
2. Explain combining html and php code in a single page?
3. Explain sending mail on form submission?
4. Explain about redirecting user using Header() method?
5. Explain about File Uploads in Detail?
6. Define cookie? Explain setting a cookie with php?
7. Explain the starting session?
8. Discuss the session in an environment with registered users?

Unit-4
1. How to include the files using include()function with syntax?
62 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
2. Explain about validating files using files?
3. What are the file creation and writing, reading or appending?(or)
Explain about File operations in PHP?
4. Explain the reading from file operation writing or appending to a file?
5. Explain about directories?
6. How to draw a new image?
7. Explain about image creation in PHP?
8. How to modifying existing images?

Unit-5
1. What are the different types of relationships?
2. Explain about SQL commands in detail?
3. What are the String Manipulation functions in MySQL?
4. What are the different Datatypes in MYSQL?(4M)
5. Difference between the mysql and mysqli functions?(4M)
6. What are the features of MySQL?(4M)
7. What are the steps require for the connecting to mysql with php?
8. Explain the planning and creating database tables?
9. Discuss creating menu?
10. Explain record adding, modifying, and deletion mechanism?

ALL THE BEST

63 Computer Science Department-AASC

You might also like