PHP With Mysql Material-1
PHP With Mysql Material-1
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
What is PHP?
- 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.
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.
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.
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.
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.
<?php
// PHP code goes here
?>
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>
<?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).
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.
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>
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
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.
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;
</body>
</html>
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>
- String
- Integer
- Float (floating point numbers - also called double)
- Boolean
- Array
- Object--oops
- NULL
- Resource
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
PHP Integer
Example :
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5985;
?>
PHP Float
Example :
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10.365;
?>
</body>
</html>
PHP Boolean
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.
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
The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
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.
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:
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:
<!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>
<!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>
===================================
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.
SynTax:
if (condition)
{
code to be executed if condition is true;
}
Example :
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
</body>
</html>
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");
</body>
</html>
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;
</body>
</html>
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!";
}
?>
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
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>
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>
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>
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
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>
Example:
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
</body>
</html>
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>
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);
</body>
</html>
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");
</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");
</body>
</html>
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)
);
</body>
</html>
PHP OOPs:
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;
}
}
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
</body>
</html>
$_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>
</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"];
?>
</BODY>
</HTML>
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';
</body>
</html>
Output :
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>
</FORM>
</BODY>
</FORM>
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
$_COOKIE
An associative array of variables passed to the current script via HTTP cookies.
$_SESSION
$_PHP_SELF
$php_errormsg
$php_errormsg is a variable containing the text of the last error message generated
by PHP.
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.
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)
<?php
echo readfile("myfile.txt");
?>
</body>
</html>
<!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.
<?php
$myfile = fopen("newfile.txt", "w");
$txt = "Harish";
fwrite($myfile, $txt);
$txt = "Eranna";
fwrite($myfile, $txt);
fclose($myfile);
?>
</body>
</html>
<?php
$filename = "tmp.txt";
$file = fopen( $filename, "r" );
</body>
</html>
<body>
fclose( $file );
</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
<?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";
}
}
?>
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()
<!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()
<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
<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.
The fwrite() function accepts a file resource and a string, and then writes the string to
the file.
Example :
fwrite($fp, “hello world”);
fputs($fp, “hello world”);
The fpassthru() function reads from the current position in a file - until EOF, and then
writes the result to the output buffer.
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>
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.
Example :
40 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
<?php
$file = popen("/bin/ls","r");
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.
<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.
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>
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE
or $HTTP_COOKIE_VARS variables.
Example :
<html>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
echo $HTTP_COOKIE_VARS["name"]. "<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>
Example :
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<body>
</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 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.
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.
Session variables are stored in associative array called $_SESSION[]. These variables
can be accessed during lifetime of a session.
<?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>
<?php
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_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();
</body>
</html>
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).
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).
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
<?php
// Get current directory
echo getcwd() . "<br>";
// Change directory
chdir("images");
• 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.
• 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.
<?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>”;
?>
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.
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:
Several PHP functions can assist you in drawing shapes and lines on your canvas:
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);
?>
Example :
<?php
//create the canvas
50 Computer Science Department-AASC
PHP MATERIAL – The Arts and Science college :: Adoni
$myImage = ImageCreate(300,300);
MYSQL
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.
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.
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
client_flags
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.
Example :
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.
Example :
<?php
$dbhost = 'localhost:83';
$dbuser = 'csserver';
$dbpass = 'aasc';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! $retval )
{
die('Could not create database: ' . mysql_error());
}
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());
}
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create table: ' . mysql_error());
}
mysql_close($conn);
?>
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());
}
if(! $retval ) {
die('Could not delete database test_db: ' . mysql_error());
}
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());
}
if(! $retval ) {
die('Could not delete table employee: ' . mysql_error());
}
mysql_close($conn);
?>
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());
}
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
mysql_close($conn);
?>
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.
Example:
<?php
$dbhost = 'localhost:83';
$dbuser = 'csserver';
$dbpass = 'aasc';
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
mysql_close($conn);
?>
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';
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$emp_id = $_POST['emp_id'];
$emp_salary = $_POST['emp_salary'];
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>
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'];
if(! $retval ) {
die('Could not delete data: ' . mysql_error());
}
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?