Php and Mysql
Php and Mysql
AND
COMPUTER APPLICATION
LEARNING RESOURCE
1
Introduction to PHP & Features
PHP is a server scripting language, and a powerful tool for making dynamic and
interactiveWeb pages.
PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
Example
<html>
<body>
<?php
echo "My first
PHPscript!"; ?>
</body>
</html>
Before you continue you should have a basic understanding of the following:
• HTML
• CSS
• JavaScript
What is PHP?
2
What is a PHP File?
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain
HTML
PHP files have extension ".php"
With PHP you are not limited to output HTML. You can output images, PDF
files, andeven Flash movies. You can also output any text, such as XHTML and
XML.
Why PHP?
3
To start using PHP, you can:
• If your server has activated support for PHP you do not need to do anything.
• Just create some .php files, place them in your web directory, and the server
willautomatically parse them for you.
• You do not need to compile anything or install any extra tools.
• Because PHP is free, most web hosts offer PHP support.
• Set Up PHP on Your Own PC
PHP Scripts
<?php
4
Example
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
• PHP statements end with a semicolon (;)
Comments in PHP
5
Example
<html>
<body>
<?php
Example
<html>
<body>
<?php
ECHO "Hello
World!<br>";echo
"Hello World!<br>";
EcHo "Hello
World!<br>";
6
?></body>
</html>
In the example below, only the first statement will display the value of the
$color variable (this is because $color, $COLOR, and $coLOR are treated as
three differentvariables):
Example
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR .
"<br>"; echo "My boat is " .
$COLOR ."<br>"; ?>
</body>
</html>
Data Types
• Variables can store data of different types, and different data types
can do different things.
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
7
PHP String
Example
<html>
<body>
<?php
$x = "Hello world!";
$y = 'Hello
world!';echo $x;
echo
"<br>";
echo $y;
?>
</body>
</html>
OUTPUT:
Hello
world!
Hello
world!
8
String Functions
• Get The Length of a String
• The PHP strlen() function returns the length of a string.
• The example below returns the length of the string "Hello world!":
Example
<html>
<body>
<?php
echo
strlen("Hello
world!"); ?>
</body>
</html>
OUPUT:
12
Count The Number of Words in a String
Example
<html>
<body>
Reverse a String
<body>
<?php
10
<?php
OUPUT:
• The PHP strpos() function searches for a specific text within a string.
• If a match is found, the function returns the character position of the first
match. Ifno match is found, it will return FALSE.
• The example below searches for the text "world" in the string "Hello world!":
Example
<html>
<body>
<?php
echo strpos("Hello world!", "world");
?>
</body>
</html>
OUTPUT:
6
Replace Text Within a String
<body>
<?php
echo str_replace("world", "Dolly", "Hello world!");
?>
</body>
</html>
OUPUT:
Hello Dolly!
12
PHP Integer
Example
<html>
<body>
<?php
$x = 5985;
var_dump($x);
?>
</body>
</html>
OUTPUT:
int(5985)
PHP Float
Example
<html>
<body>
<?php
$x = 10.365;
var_dump($x);
?>
</body>
</html>
OUTPUT:
float(10.365)
PHP Boolean
$x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about
conditionaltesting in a later chapter of this tutorial.
PHP Array
• An array stores multiple values in one single variable:
• An array is a special variable, which can hold more than one value at a time.
• If you have a list of items (a list of car names, for example), storing the
14
carsin single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
• However, what if you want to loop through the cars and find a specific
one?And what if you had not 3 cars, but 300?
• The solution is to create an array!
• An array can hold many values under a single name, and you can access
thevalues by referring to an index number.
Example
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
OUTPUT:
array();
15
Variables
Example
<html>
<body>
$x = 5; Output:
$y = 10.5;
Hello world!
echo $txt; 5
echo "<br>"; 10.5
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
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
• 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)
16
Output Variables
• The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
<html> Output:
<body>
I love W3Schools.com!
<?php
$txt =
"W3Schools.com";
echo "I love $txt!";
?>
</body>
</html>
Example
<html>
<body>
<?php
Output:
$txt =
I love W3Schools.com!
"W3Schools.com";
echo "I love " . $txt .
"!";
?>
17
</body>
</html>
Example
<html>
<body>
<?php
Output:
$x = 5;
9
$y = 4echo $x + $y;
?>
</body>
</html>
• local
• global
• static
A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:
18
Example
<html>
<body>
<?php
$x = 5; // global
scopefunction
myTest() {
// using x inside this function will generate an
errorecho "<p>Variable x inside function is:
$x</p>";
}
myTest();
echo "<p>Variable x outside function is:
$x</p>"; ?>
</body>
</html>
OUTPUT:
A variable declared within a function has a LOCAL SCOPE and can only be
accessedwithin that function:
Example
<html>
<body>
<?php
19
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate
anerror echo "<p>Variable x outside
function is:
$x</p>"; ?>
</body>
</html>
20
OUTPUT:
• The global keyword is used to access a global variable from within a function.
• To do this, use the global keyword before the variables (inside the function):
Example
<html>
<body> Output:
<?php
15
$x = 5;
$y = 10;
function
myTest() {
</html>
21
The static Keyword
To do this, use the static keyword when you first declare the variable:
Example
<html>
<body>
<?php
Output:
function
myTest() { 0
static $x = 0;
echo $x; 1
$x++;
} 2
myTest();
echo
"<br>";
myTest();
echo
"<br>";
myTest();
?>
</body>
</html>
echo Statement
The echo statement can be used with or without parentheses: echo or echo().
Display Text
22
The following example shows how to output text with the echo command (notice
that thetext can contain HTML markup):
Example
<html>
<body>
<?php
echo "<h2>PHP is
Fun!</h2>";echo "Hello
world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with
multipleparameters."; ?>
</body>
</html>
OUTPUT:
PHP is Fun!
Hello world!
I'm about to learn PHP!
This string was made with multiple parameters.
Display Variables
The following example shows how to output text and variables with the echo statement:
23
Example
<html>
<body>
<?php
= "W3Schools.com";
$x =5;
$y = 4;
echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>
</body>
</html>
OUTPUT:
Learn PHP
Study PHP at
W3Schools.com
9
• The print statement can be used with or without parentheses: print or print().
Display Text
The following example shows how to output text with the print command (notice
that thetext can contain HTML markup):
24
Example
<html>
<body>
<?php
print "<h2>PHP is
Fun!</h2>";print "Hello
world!<br>";
print "I'm about to
learnPHP!"; ?>
</body>
</html>
OUTPUT:
PHP is Fun!
Hello world!
I'm about to learn PHP
PHP Object
• An object is a data type which stores data and information on how to process
thatdata.
• In PHP, an object must be explicitly declared.
• First we must declare a class of object. For this, we use the class
keyword. Aclass is a structure that can contain properties and methods:
Example
<html>
25
<body>
<?php
class Car
{
</html>
OUPUT:
VW
PHP NULL Value
• Null is a special data type which can have only one value: NULL.
• A variable of data type NULL is a variable that has no value assigned to it.
• If a variable is created without a value, it is automatically assigned a
value ofNULL.
• Variables can also be emptied by setting the value to NULL:
Example
<html>
<body>
<?php
$x = "Hello world!";
26
$x = null;
var_dump($x
);
?>
</body>
</html>
27
OUTPUT:
Constants
• Constants are like variables except that once they are defined they cannot
bechanged or undefined.
• PHP Constants
• A constant is an identifier (name) for a simple value. The value
cannot bechanged during the script.
• A valid constant name starts with a letter or underscore (no $ sign
before theconstant name).
Note: Unlike variables, constants are automatically global across the entire script.
Syntax
Parameters:
28
Example
<html>
<body>
<?php
</body>
</html>
OUTPUT:
Welcome to W3Schools.com!
Example
<html>
<body>
<?php
</body>
29
</html>
OUTPUT:
Welcome to W3Schools.com!
• Constants are automatically global and can be used across the entire script.
• The example below uses a constant inside a function, even if it is defined
outsidethe function:
Example
<html>
<body>
<?php
define("GREETING", "Welcome to
W3Schools.com!"); function
myTest() {
echo GREETING;
}
myTest();
?>
</body>
</html>
OUPUT:
Welcome to W3Schools.com!
30
PHP Operators
• The PHP arithmetic operators are used with numeric values to perform
commonarithmetical operations, such as addition, subtraction,
multiplication etc.
Functions
• The real power of PHP comes from its functions; it has more than 1000
built-infunctions.
• Besides the built-in PHP functions, we can create our own functions.
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute immediately when a page loads.
• A function will be executed by a call to the function.
Create a User Defined Function in PHP
<body>
<?php
function
writeMsg()echo
"Hello world!";
}
writeMsg();
?>
32
</body>
</html>
33
OUTPUT:
Hello world!
PHP Form Handling
The PHP super globals $_GET and $_POST are used to collect form-data.
Get request is the default form request. The data passed through get request is visible
on the URL browser so it is not secured. It is an associative array of variables passed
to the current script via the URL parameters (aka. query string). Note that the array is
not only populated for GET requests, but rather for all requests with a query string.
You can send limited amount of data through get request. The GET variables are
passed through urldecode().Ingeneral, a URL with GET data will look like this:
http://www.example.com/action.php?name=xyz&age=32
$_GET examples:
<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>
Assuming the user entered
Hello Hannes!
File: form1.html
1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variable
3. echo "Welcome,
34
$name";4. ?>
When the user fills out the form above and clicks the submit button, the form data is
sent for processing to a PHP file named "welcome.php". The form data is sent with
the HTTP GETmethod.
Post request is widely used to submit form that have large amount of data such as file
upload, image upload, login form, registration form etc. The data passed through post
request is not visible on the URL browser so it is secured. You can send large amount
of data through post request. It is an associative array of variables passed to the
current script via the HTTP POST method when using application/x-www-form-
urlencoded or multipart/form-data as the HTTP Content-Type in the request.
$_POST examples:
<?php
echo 'Hello ' . htmlspecialchars($_POST["name"]) . '!';
?>
Hello Hannes!
File: form1.html
1. <?php
2. $name=$_POST["name"];//receiving name field value in $name variable
3. $password=$_POST["password"];//receiving password field value in $password
variable
4. echo "Welcome: $name, your password is:
35
$password";5. ?>
Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2,
key3 => value3, ...)). This array holds key/value pairs, where keys are the names of
the form controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are super globals,
which means that they are always accessible, regardless of scope - and you can
access them fromany function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST
method.
PHP is used to insert the form action as the current page. That's because we are
using the "redirect-after-POST" technique as illustrated here:
It prevents the form from being resubmitted if the landing page is reloaded, and
allows us to display validation error messages inline using PHP. Finally, the code
includes PHP commands to re-insert any submitted values back in to the form so
they don't have to be retyped in case of an error.
36
ARRAY
Method 1:
$ Fruits=array(' strawberry'; grape' vanilla'; caramel'}
Method 2:
$ fruits[0]=' strawberry';
$ fruits[1]=' grapes';
Method 3:
$ fruits[' red']=' apple';
$ fruits[' yellow']=' mango';
$ fruit[]=' strawberry';
To remove an element we can use array_ push or array_ pop(). These two
functions are built-in array functions in PHP.
In PHP we can process arrays using loops like for, while, etc..
We also have a special loop in PHP known as for each loop for
array processing. Example for array processing with loop
<html>
<head></head>
<body>
38
Today shopping list;
<ul>
<?php
$shoppinglist=array(‘green gram’,’bengal gram’,’rice’);
for($x=0;$x< sizeof($shoppinglist);x++)
{
echo<li>$shoppinglist[$x];
}
?>
</ul>
</body>
</html>
In this example for loop is used to interact with the array. This loops extract
elements from the array and prints in the screen one after another as an order list.
The sizeof() function returns the number of elements in the array.
foreach loop()
This loop runs for each element of the array movning through the element of
array on each interation. In for loop, we have condition statement and
iteration(increment/decrement) statement. Condition statement and iteration
statement are not needed in foreach() loop.
The syntax of foreach() loop is.
foreach (array variable as loop variable)
{
// loop statement
}
example using foreach() loop
<html>
<head></head>
<body>
39
Today’s shopping list;
<ul>
<?php
$shoppinglist=array (‘green gram’, ’bengal gram’, ‘’rice’);
foreach($shoppinglist as $ item)
{
}
?>
</ul>
There are many built-in array functions in PHP that we can use along with array.
1. is_array()
This function check whether the variable in PHP is a array variable or not. It
returns Boolean value as output
2. array_key()
This function returns the list of key in associative array for example this function will
return
'dog', cat', 'parrot’ from the array $animals.
3. array_value()
This function will return only the array element in an associative array. For
example, this function returns 'Tripsy', 'Tabitha', 'polly' from the animals array,
4. list()
This list function assigns array elements to array variable. ex:
$flavours=array(' strawberry', 'grape',
40
'vanilla'); list($f1, $f2, $f3) = $flavours;
$f1 will have strawberry
$f2 will have
grape and so on
5.extract()
The extract() function iterates through (associative array) converting the key value
pairs into corresponding variable value pairs.
$ fruits= array('red'= ‘apple’, ' yellow'=' banana', 'purple'=
‘grapes’); Extract ($ fruits):
$red will have 'apple'
$yellow will have' banana'
$purple will have' grapes'
6.Array_push() function:
7. Array_pop()
8.array-shift ()
9.array-unshift:
10.Explode ()
The explode function splits a string into smaller components on the basis of a user
defined character and then returns those element in an array.
ex:-
$string=' this is a book';
$words = explode (‘$string’, ‘ ‘);
This function returns and array variable $words will contain (‘this’, ‘is’, ‘book’)
11. implode ()
The implode function create a single string from all the element of an array
joining them together with user defined separator.
EX:-
$words=array(‘This’,’ is’, ‘a’, ‘book’, ‘of’, ’Hindi’);
$string=implode(‘ ’,$words);
$string=’This is a book of Hindi’;
Function
A function is a set of program statements that perform a specific task.
Functions can be called or executed from anywhere in the program. All the
programming languages have built-in functions and also allow us to create user
defined function. For example we can use the function with name pow from c
library math.h or we can define our own function.
Usage of function:-
42
1. Reducing repetition:
User defined function enables developer to extract commonly used pieces of
code as separate package.So it reduces unnecessary code repetition and
redundancies also makes the code easier to understand and debug.
2. Easy maintenance:-
Because functions are defined oncee and used many times, they are used to
maintain the code. During code maintenance if we want to change from values in
calculation, we need to change only in the function. We need not Traverse the
whole program for making change in one value.
3. Improves abstraction:
Function forces programmer to think in abstract terms. We need not worry
about implementation of the function. It is enough that we know the function
name, number of arguments and return type of the function.
Creating user defined function:
Consider the example below which define a function for displaying Shakespeare
quote in a webpage.
<?php
//define a function
function displayShakesphearQuote()
{
echo’some are born great, some achieve greatness and some have greatness through upon
them’
;.
}
invoking function
<?php
….
….
displayShakesphearQuote();
?>
43
PHP functions are defined with the function keyword following by
present.
It is optional and can be omitted if no argument is present.
After the first line of the function the body of the function should be
If the function had arguments we have to specify the arguments during invoking.
44
argument function
addDomainToUsername($u,$d)
{
//great empty result array
$result_array=array();
forreach($u as $element)
{
$result array[]=$element,’@’,$d;
}
return $result_array;
}
$users=array(‘John’, ‘jim’ ,’harry’);
$newusers=addDomainToUsername($users, ‘guese.me.domain’);
?>
Defining global and local variable:-
The variables defined inside functions are local variables. They cannot be
used from outside the function. If we want to use a variable throughout the script
in all functions we have to declare that variable with Global key word.
Global variable can be used in PHP script for counting the number of visitors in a
website. This is done by the following statement.
Global $count
Super Global variables:-
There are some variables provided by the PHP interpreter that we can use in
our PHP script. These variables can be accessed from anywhere in our program.
There are variables which are used commonly for creation of websites with many
web pages. All these Global variables starts with $_
They are
$_SERVER
$_POST
Used to collect data after submitting HTML form with method 10 =" post"
$_GET
Collect form data after submitting HTML form with method = "GET"
45
$_REQUEST
Used to collect data after submitting an HTML form.
$_GLOBALS
It contains all the super Global variables in installed PHP version.
$_FILES
$_SESSION
$_COOKIE
SESSION
?>
</body>
</html>
</body></html>
Another way to show all the session variable values for a user session is to run
the following code:
<?php
session_start
();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSI
ON);
?>
</body>
</html>
48
How does it work? How users are identified?
Most sessions set a user-key on the user's computer that looks something like this:
765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another
page, it scans the computer for a user-key. If there is a match, it accesses that
session, if not, it starts a new session.
Cookie
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the
server embeds on the user's computer. Each time the same computer requests a
page with a browser, it will send the cookie too. With PHP, you can both create
and retrieve cookie values.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
49
PHP Create/Retrieve a Cookie
The following example creates a cookie named "user" with the value "John
Doe". The cookie will expire after 30 days (86400 * 30). The "/" means that the
cookie is available in entire website (otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE).
We also use the isset() function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "Jegan Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_nam
e])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is
set!<br>"; echo "Value is: " .
$_COOKIE[$cookie_name];
}
?>
</body>
</html>
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the
50
cookie, and automatically decoded when received (to prevent URLencoding, use
setrawcookie() instead).
Example
<?php
$cookie_name = "user";
$cookie_value = "Atul Kailash";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_nam
e])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is
set!<br>"; echo "Value is: " .
$_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
51
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one
hour ago setcookie("user", "",
time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Check if Cookies are Enabled
The following example creates a small script that checks whether cookies are
enabled. First, try to create a test cookie with the setcookie() function, then count
the $_COOKIE array variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
Also notice that all session variable values are stored in the global $_SESSION variable
52
<?php
if(count($_COOKIE) >
0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Note: Any whitespace in the format string matches any whitespace in the input
stream. This means that a tab (\t) in the format string can match a single space
character in the input stream.
Syntax
fscanf(file, format, mixed)
Parameter Description
file Required. Specifies the file to
check format Required. Specifies the
format.
Possible format values:
53
%% - Returns a percent sign
%b - Binary number
%c - The character according to the ASCII value
%d - Signed decimal number
%e - Scientific notation (e.g. 1.2e+2)
%u - Unsigned decimal number
%f - Floating-point number (local settings aware)
%F - Floating-point number (not local settings aware)
%o - Octal number
%s - String
%x - Hexadecimal number (lowercase letters)
%X - Hexadecimal number (uppercase letters)
Additional format values. These are placed between the % and the letter (example %.2f):
+ (Forces both + and - in front of numbers. By default, only negative numbers are
marked)
' (Specifies what to use as padding. Default is space. Must be used together with the
width specifier. Example: %'x20s (this uses "x" as padding)
- (Left-justifies the variable value)
[0-9] (Specifies the minimum width held of to the variable value)
.[0-9] (Specifies the number of decimal digits or maximum string length)
Note: If multiple additional format values are used, they must be in the same order as
above.
The parse_ini_file() function parses a configuration (ini) file and returns the settings.
Tip: This function can be used to read in one’s own configuration files, and has
nothing to do with the php.ini file.
54
Note: The following reserved words must not be used as keys for ini files: null,
yes, no, true, false, on, off, none. Furthermore, the following reserved characters
must not be used in the key: {}|&~!()^".
Syntax
parse_ini_file(file, process_sections, scanner_mode)
Parameter Description
file Required. Specifies the ini file to parse
process_sections Optional. If set to TRUE, it returns is a multidimensional
array with section names and settings included. Default is FALSE
scanner_mode
Optional. Can be one of the following values:
INI_SCANNER_NORMAL (default)
INI_SCANNER_RAW (means option values will not be parsed)
INI_SCANNER_TYPED (means that boolean, null and integer types are
preserved when possible. "true", "on", "yes" are converted to TRUE. "false", "off",
"no", "none" are converted to FALSE. "null" is converted to NULL. Numeric
strings are converted to integer type if possible)
55
Getting file information with stat
Definition and Usage
The stat() function returns information about a file as an array.
Note: The results from this function will differ from server to server. The array may
contain the number index, the name index, or both.
Note: The result of this function is cached. Use clearstatcache() to clear the cache.
Syntax
stat(filename)
Parameter Description
filename Required. Specifies the path to the file
Return Value:
An array with the following elements:
[0] or [dev] - Device number
Fseek
Definition and Usage
The fseek() function seeks in an open file.
This function moves the file pointer from its current position to a new position, forward
or backward, specified by the number of bytes.
Tip: You can find the current position by using ftell()!
Syntax
fseek(file, offset, whence)
Parameter Description
file Required. Specifies the open file to seek in
offset Required. Specifies the new position (measured in bytes from the beginning
of the file)
57
whence Optional. Possible values:
SEEK_SET - Set position equal to offset. Default
SEEK_CUR - Set position to current location plus
offset
SEEK_END - Set position to EOF plus offset (to move to a position before EOF, the
offset must be a negative value)
Deleting files
58
Deletion of files is done using unlink()
function. Definition and Usage
The unlink() function deletes a file.
Syntax
unlink(filename, context)
Parameter Description
filename Required. Specifies the path to the file to delete
context Optional. Specifies the context of the file handle. Context is a set of
options that can modify the behavior of a stream
Return Value: TRUE on success, FALSE on failure
Example
Delete a file using unlink()
<?php
$file = "test.txt";
if (!unlink($file)) {
echo ("Error deleting $file");
} else {
echo ("Deleted $file");
}
?>
Reading and writing binary files
A better method to open files is with the fopen () function.
The file may be opened in one of the following modes
59
Modes Description
Open a file for read only. File pointer starts at the beginning of thefile
R
Open a file for write only. Erases the contents of the file or createsa
W new file if it doesn't exist. File pointer starts at the beginning of thefile
Open a file for write only. The existing data in file is preserved. File
A pointer starts at the end of the file. Creates a new file if the file doesn't
exist
Creates a new file for write only. Returns FALSE and an error if file
X already exists
Open a file for read/write. File pointer starts at the beginning ofthe
r+ file
Open a file for read/write. Erases the contents of the file or createsa
w+ new file if it doesn't exist. File pointer starts at the beginning of the file
Creates a new file for read/write. Returns FALSE and an error iffile
x+ already exists
• File handling is an important part of any web application. You often need to
60
openand process a file for different tasks.
PHP Manipulating Files
PHP has several functions for creating, reading, uploading, and editing files.
• The readfile() function reads a file and writes it to the output buffer.
• Assume we have a text file called "webdictionary.txt", stored on the
server, thatlooks like this:
• The PHP code to read the file and write it to the output buffer is as
follows (thereadfile() function returns the number of bytes read on
success):
61
Example
<html>
<body>
<?php
echo readfile("webdictionary.txt");
?>
</body>
OUTPUT:
</html>
AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML =
Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured
Query Language SVG = Scalable Vector Graphics XML = EXtensible Markup
Language236
62
File Open/Read/Close
PHP Open File -
fopen()
• A better method to open files is with the fopen() function. This function
gives you more options than the readfile() function.
We will use the text file, "webdictionary.txt", during the
lessons:AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup
LanguagePHP = PHP Hypertext
Preprocessor SQL = Structured
Query Language SVG = Scalable
Vector Graphics
XML = EXtensible Markup Language
The first parameter of fopen() contains the name of the file to be opened and the
second parameter specifies in which mode the file should be opened. The
following example also generates a message if the fopen() function is unable to
open the specified file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
63
?>
OUTPUT:
AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper
Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language
SVG = Scalable Vector Graphics XML = EXtensible Markup Language
The file may be opened in one of the following modes:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if itdoesn't
exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts atthe end
of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file
if it doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer
starts at the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already
Exists
64
PHP Read File - fread()
65
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");echo fgets($myfile);
fclose($myfile);
?>
OUTPUT:
After a call to the fgets() function, the file pointer has moved to the next line.
• The feof() function checks if the "end-of-file" (EOF) has been reached.
• The feof() function is useful for looping through data of unknown length.
• The example below reads the "webdictionary.txt" file line by line, until
end-of-fileis reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-
filewhile(!feof($myfile)) {
echo fgets($myfile) . "<br>";
66
}
fclose($myfile);
?>
OUTPUT:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
67
while(!feof($myfil
e)) { echo
fgetc($myfile);
}
fclose($myfile);
?>
OUTPUT:
• After a call to the fgetc() function, the file pointer moves to the next character.
File Create/Write
• The fopen() function is also used to create a file. Maybe a little confusing,
but inPHP, a file is created using the same function used to open files.
• If you use fopen() on a file that does not exist, it will create it, given that the
file isopened for writing (w) or appending (a).
• The example below creates a new file called "testfile.txt". The file will be
createdin the same directory where the PHP code resides:
68
Example
If you are having errors when trying to get this code to run, check that you have
granted your PHP file access to write information to the hard drive.
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable
to openfile!"); $txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane
Doe\n";
fwrite($myfile,
$txt);
fclose($myfile);
?>
69
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file
we sent the string $txt that first contained "John Doe" and second contained
"Jane Doe". After we finished writing, we closed the file using the fclose()
function.
John
DoeJane
Doe
PHP Overwriting
• Now that "newfile.txt" contains some data we can show what happens when
we open an existing file for writing. All the existing data will be ERASED
and we startwith an empty file.
• In the example below we open our existing file "newfile.txt", and write some
new data into it:
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable
to openfile!"); $txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie
Mouse\n";
70
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, both John and Jane have vanished, and
only thedata we just wrote is present:
OUTPUT:
Mickey
Mouse
Minnie
Mouse
71
PHP ftp_fput()
FunctionExample
• Open local file, and upload it to a file on the FTP server:
<?php
$ftp_server = "ftp.example.com";
What is MySQL?
• Employees
• Products
• Customers
73
• Orders
74
• Both are object-oriented, but MySQLi also offers a procedural API.
• Both support Prepared Statements. Prepared Statements protect from
SQLinjection, and are very important for web application security.
75
MySQL Examples in Both MySQLi and PDO Syntax
• MySQLi (object-oriented)
• MySQLi (procedural)
• PDO
MySQL Installation
• PDO Installation
• For installation details, go to: http://php.net/manual/en/pdo.installation.php
Open a Connection to MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
76
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo
"Connected
successfully";
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check
connection if
(!$conn) {
$servername = "localhost";
$username = "username";
$password = "password";
try {
Notice that in the PDO example above we have also specified a database (myDB). PDO
require a valid database to connect to. If no database is specified, an exception is
thrown.
$conn->close();
mysqli_close($conn);
Example (PDO)
$conn = null;
PHP Create a MySQL Database
<?php
$servername = "localhost";
$username = "username";
79
$password = "password";
// Create connection
$conn = new mysqli($servername, $username,
$password); // Check
connectionif ($conn-
>connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
echo "Database
createdsuccessfully"; }
else {
echo "Error creating database: " . $conn->error;
}
$conn-
>close(); ?>
lastname VARCHAR(30)
NOTNULL, email
VARCHAR(50),
reg_date TIMESTAMP
)
After the data type, you can specify other optional attributes for each column:
• NOT NULL - Each row must contain a value for that column, null
values arenot allowed
• DEFAULT value - Set a default value that is added when no other
valueis passed
• UNSIGNED - Used for number types, limits the stored data to
positivenumbers and zero
• AUTO INCREMENT - MySQL automatically increases the value of the
field by1 each time a new record is added
• PRIMARY KEY - Used to uniquely identify the rows in a table. The
columnwith PRIMARY KEY setting is often an ID number, and is
often used with AUTO_INCREMENT
81
Each table should have a primary key column (in this case: the "id"
column). Itsvalue must be unique for each record in the table.
82
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
lastname VARCHAR(30)
NOTNULL, email
VARCHAR(50),
reg_date TIMESTAMP
)";
83
if ($conn->query($sql) === TRUE)
• After a database and a table have been created, we can start adding data
inthem.
Here are some syntax rules to follow:
• The SQL query must be quoted in PHP
• String values inside the SQL query must be quoted
•
• Numeric values must not be quoted
• The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL table:
// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname); // Check
connectionif ($conn-
>connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn->query($sql) ===
TRUE) {echo "New record
created
successfully"; } else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn-
>close(); ?>
Example:
Mysqlaa.html:
85
<!DOCTYPE HTML>
<html>
<head>
<title>Student
Table</title>
</head>
<body>
type="text" name="regno"><br>
Mark1<br><input type="text"
name="m1"><br> Mark2<br><input
type="submit" value="ok">
</form>
</div>
</body>
</html>
86
Conn.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sample";
// Create connection
if ($conn->connect_error)
echo "Connected
successfully"; //connect
table
echo "<br>";
else
echo "error";
//Inserting the
contents echo
"<br>";
$sname=$_POST['sname'];
$regno=$_POST['regno'];
$m1=$_POST['m1'];
$m2=$_POST['m2'];
values('$sname',$regno,$m1,$m2)"; if($conn-
>query($sql11)==TRUE)
echo "inserted";
}
88
else
{echo
"error";}
echo "<br>";
$result = $conn-
>query($sql1); if ($result-
>num_rows > 0) {
} else {
89
90
91