Advanced Internet Programming Notes
Advanced Internet Programming Notes
DILLA CAMPUS
Amanuel Tadiwos
Dilla, Ethiopia
Nov, 2022
Contents
Chapter 1: - Server Side Scripting Basics in PHP ......................................................................................... 3
1.1 Overview of Client Side Script ........................................................................................................... 3
1.2. Introduction to Server Side Script ...................................................................................................... 3
1.3. PHP Basic Syntax .............................................................................................................................. 5
1.4. Variables and Constants ..................................................................................................................... 9
1.5. PHP Operators (Reading Assignment) ............................................................................................. 15
1.6. Manipulate Strings ........................................................................................................................... 16
Chapter 2: PHP Statements and Form Creations ........................................................................................ 18
2.1. PHP statements: - Use Conditionals/Decision Making, LOOP, Arrays........................................... 18
2.1.1. Conditionals/Decision Making Statements ............................................................................... 18
2.2PHP GET, POST & REQUIST Methods ........................................................................................... 26
2.3 Creating PHP Forms ..................................................................................................................... 28
2.4 Form Validation ............................................................................................................................ 30
Chapter 3 Files and Directories in PHP ...................................................................................................... 33
3.1. Reading files/ Directories ................................................................................................................. 33
3.2. Upload Files ..................................................................................................................................... 36
3. 3 PHP Cookies and Session ................................................................................................................ 37
3.4 PHP - File Inclusion .......................................................................................................................... 41
Chapter 4:- PHP Database / PHP with MYSQL ......................................................................................... 44
Create MySQL Database Using PHP ...................................................................................................... 46
Creating Database Tables ........................................................................................................................ 47
Server-side scripting language, which means that the scripts are, executed on the server, the
computer where the Web site is located.
Server-side scripting is a web server technology in which a user's request is fulfilled by running a
script directly on the web server to generate dynamic web pages. It is usually used to provide
interactive web sites that interface to databases or other data stores. This is different from client-
side scripting where scripts are run by the viewing web browser.
Prepared by Amanuel Tadiwos Page 3
Lecture Note: Advanced internet programming 2015 E.C
The primary advantage to server-side scripting is the ability to highly customize the response based
on the user's requirements, access rights, or queries into data stores. From security point of view,
server-side scripts are never visible to the browser as these scripts are executes on the server and
emit HTML corresponding to user's input to the page.
In contrast, server-side scripts, written in languages such as PHP, [Link], Java, ColdFusion,
Perl, Ruby, Go, Python, and server-side JavaScript, are executed by the web server when the user
requests a document. They produce output in a format understandable by web browsers (usually
HTML), which is then sent to the user's computer. The user cannot see the script's source code
(unless the author publishes the code separately), and may not even be aware that a script was
executed. Documents produced by server-side scripts may, in turn, contain client-side scripts.
Server-side Web scripting is mostly about connecting Web sites to back end servers, such as
databases. This enables two-way communication:
Server-side scripting is about "programming" the behavior of the server while client-side scripting
is about "programming" the behavior of the browser. Normally, when a browser requests an HTML
file, the server returns the file. However, if the file contains a server-side script, the script is
executed on the server before the file is returned to the browser as plain HTML.
In server side script, since the scripts are executed on the server, the browser that displays the file
does not need to support scripting at all. The followings are server-side scripts:
• PHP (*.php)
• Active Server Pages (ASP)
• ANSI C scripts Java via JavaServer Pages (*.jsp)
• JavaScript using Server-side JavaScript (*.ssjs)
• Lasso (*.lasso) etc
The main focus here is PHP, which is a server-side scripting language, which can be embedded
in HTML or used as a standalone binary, and could be run with open source software like
WAMP server.
PHP can dynamically create the HTML code that generates the Web page.
Web page visitors see the output from scripts, but not the scripts themselves.
PHP stands for PHP: Hypertext Preprocessor. It is a server-side scripting language, which can be
embedded in HTML. Over the past few years, PHP and server-side Java have gained momentum,
while ASP has lost mindshare.
PHP is a server-side scripting language, which means that the scripts are executed on the server,
the computer where the Web site is located. This is different than JavaScript, another popular
language for dynamic Web sites. JavaScript is executed by the browser, on the user‘s computer.
Thus, JavaScript is a client-side language.
Because PHP scripts execute on the server, PHP can dynamically create the HTML code that
generates the Web page, which allows individual users to see customized Web pages. Web page
visitors see the output from scripts, but not the scripts themselves.
PHP is particularly strong in its ability to interact with databases. PHP handles connecting to the
database and communicating with it, so we don‘t need to know the technical details for connecting
to a database or for exchanging messages with it, it is enough telling PHP the name of the database
and where it is, and PHP handles the details. It connects to the database, passes our instructions to
the database, and returns the database response to us.
Hence, PHP scripts in the Web site can store data in and retrieve data from any
supported database. PHP also can interact with supported databases outside a Web
environment. Database use is one of PHP‘s best features.
Use of PHP:
PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can
send data, return data to the user.
Using php, it is possible to add, delete, and modify elements within our database.
It helps to assign sessions and cookies for privacy.
Using PHP, we can restrict users to access some pages of the website.
It can encrypt data and so mores
The syntax of PHP is: - There are four ways to write php syntaxes:-
3. ASP-style tags: ASP-style tags mimic the tags used by Active Server Pages to delineate
code blocks. ASP-style tags look like this:
<%... %>
To use ASP-style tags, we should set the configuration option in your [Link] file.
4. HTML script tags: HTML script tags look like this:
<script language= “php”>… </script>
To work with server script, for example with PHP, we need to install a web server, programming
itself, and database server. For PHP, we install PHP as a programming. There are many web servers
to choose for PHP uses; the most commonly used web server is called Apache which we can
download from the internet freely. Similarly, for database, there are many options to use; the most
popular database server for web pages is MySQL which again can be downloaded freely from
internet.
PHP is also available freely on the internet. In order to develop and run PHP Web pages three vital
components need to be installed on 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.
• 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.
For the apache code to execute properly, it should be saved in web directory. The web directory
depends on what web server is used. For example, for xampp web server, our web directory can
be install in C:\xampp\htdocs‖. Hence, we should save PHP files in this folder, www.
For XAMPP server, we save the php code in C:\xampp\htdocs\your file here.
A comment is the portion of a program that exists only for the human reader and stripped out
before displaying the programs result. There are two commenting formats in PHP:
Single-line comments: They are generally used for short explanations or notes relevant
to the local code. Here are the examples of single line comments.
<?php
#This is a single line comment and
// This also a single line comments too. Each style comments only print "An example
with single line comments";
?>
Multi-lines comments: They are generally used to provide pseudo code algorithms and
more detailed explanations when necessary. Use /* and */ Here are the example of multi
lines comments.
<?php
/* This is a comment with multiline
………………………………………
………………………………………
…………………………………….
*/
Print "An example with multi
line comments";
?>
Output Statements:-
The two most basic constructs for displaying output in PHP are echo and print. Both can be used either
with parentheses or without them.
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 echo or print statement can be used with or without parentheses: echo or echo().
The general format of the echo statement is as follows: echo outputitem1, outputitem2, outputitem3, . . .;
echo (output);
The parameterized version of echo does not accept multiple arguments. The general format of the print
statement is as follows:
print output;
print(output);
Example: different ways of echoand print
echo 123; //output: 123
echo “Hello World!”; //output: Hello world!
echo (“Hello World!”); //output: Hello world!
echo “Hello”,”World!”; //output: Hello World!
echo Hello World!; //output: error, string
should be enclosed in quotes
print (“Hello world!”); //output: Hello world!
The command print is very similar to echo, with two important differences:
A variable is a special container that can be defined to hold a value such as number, string, object,
array, or a Boolean. The main way to store information in the middle of a PHP program is by using
a variable. Here are the most important things to know about variables in PHP.
All variables in PHP are denoted with a leading dollar sign ($).
The value of a variable is the value of its most recent assignment.
Variables are assigned with the = operator, with the variable on the left-hand side
and the expression to be evaluated on the right.
Variables can, but do not need, to be declared before assignment.
Variables in PHP do not have intrinsic types - a variable does not know in
advance whether it will be used to store a number or a string of characters.
Variables used before they are assigned have default values.
PHP does a good job of automatically converting types from one to another when
necessary.
As shown above, Numbers are not enclosed in quotes when they are assigned to variable. However,
strings should be enclosed in either single or double quotes (― or ‗). The quotes tell PHP that the
characters are a string, handled by PHP as a unit. Without the quotes, PHP doesn‘t know the
characters are a string and won‘t handle them correctly. PHP has a total of eight data types which
we use to construct our variables:
Strings:
They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables
with their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";
There are no artificial limits on string length - within the bounds of available memory, we ought
to be able to make arbitrarily long strings. Strings that are delimited by double quotes (as in "this")
are preprocessed in both the following two ways by PHP:
Certain character sequences beginning with backslash (\) are replaced with special
characters
Variable names (starting with $) are replaced with string representations of their values.
PHP provides a large number of predefined variables to all scripts. The variables represent everything
from external variables to built-in environment variables, last error messages to last retrieved headers.
Superglobals — Superglobals are built-in variables that are always available in all scopes
$GLOBALS — References all variables available in global scope
Many of these variables, however, cannot be fully documented as they are dependent upon which
server are running, the version and setup of the server, and other factors.
Removing Variables
Variable Scope:
Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of three scope types:
Local variables:- The variable is only accessible from within the function (or method) that created
it A variable declared in a function is considered local; that is, it can be referenced solely in that
function. Any assignment outside of that function will be considered to be an entirely different
variable from the one contained in the function:
$x = 4;
function assignx () {
$x = 0;
echo "\$x inside function is $x. ";
}
assignx()
;
echo "\$x outside of function is $x. ";
?>
The output will be:-
o $x inside function is 0.
o $x outside of function is 4.
Global variables: - The variable is accessible from anywhere in the script. Global variable can be
accessed in any part of the program. However, in order to be modified, a global variable must be
explicitly declared to be global in the function in which it is to be modified. This is accomplished,
conveniently enough, by placing the keyword GLOBAL in front of the variable that should be
recognized as global. Placing this keyword in front of an already existing variable tells PHP to use
the variable having that name. Consider an example:
<?php
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++ ; echo
"Somevar is $somevar";
} addit();
?>
o Somevar is 16
Static variables:- this type of variables be either a global or local variable. Both are created by
preceding the variable declaration with the keyword static. In contrast to the variables declared as
function parameters, which are destroyed on the function's exit, a static variable will not lose its
value when the function exits and will still hold that value should the function be called again.
<?php
function keep_track() {
STATIC $count = 0;
$count++;
echo $count; print " ";
}
keep_track();
keep_track();
keep_track();
?>
B. PHP Constants
A constant is a name or an identifier for a simple value. A constant value cannot change during the
execution of the script. By default a constant is case-sensitive. By convention, constant identifiers
are always uppercase. A constant name starts with a letter or underscore, followed by any number
To define a constant we have to use define() function and to retrieve the value of a constant. Unlike
with variables, you do not need to have a constant with a $. We can also use the function constant()
to read a constant's value if we wish to obtain the constant's name dynamically.
constant () function is used to return the value of the constant. This is useful when we want to
retrieve value of a constant, but we do not know its name, i.e. It is stored in a variable or returned
by a function. constant () example:
<?php
define("MINSIZE", 50); echo MINSIZE; echo‖<br>‖;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (boolean, integer, float and string) can be contained in constants. PHP provides
a large number of predefined constants to any script which it runs. There are five magical
constants that change depending on where they are used. For example, the value of __LINE__
depends on the line that it's used on in script.
The name of a constant follows the same rules as any label in PHP. A valid constant name starts
with a letter or underscore, followed by any number of letters, numbers, or underscores. As a
regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
1.5. PHP Operators (Reading Assignment)
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
One especially useful construct is the ternary conditional operator, which plays a role somewhere
between a Boolean operator and a true branching construct. Its job is to take three expressions and
use the truth value of the first expression to decide which of the other two expressions to evaluate
and return. The syntax looks like:
The value of this expression is the result of yes-expression if test-expression is true; otherwise, it
is the same as no-expression. For example, the following expression assigns to $max_num either
$first_num or $second_num, whichever is larger: $max_num = $first_num > $second_num ?
$first_num : $second_num;
Example:-
<?php
$x=2;
?>
i. String concatenation operation: - To concatenate two string variables together, use the
dot (.) operator like echo $string1 . " " . $string2;
ii. strpos() function:- used to search for a string or character within a string. If a match is
found in the string, this function will return the position of the first match. If no match is
found, it will return FALSE.
Written as strops(orginal string, new string) Example: the following
code used to show from where the word ―world‖ started.
If more than one line should be executed in a condition of true/false, the lines should be enclosed
within curly braces as shown below.
Example
<?php
$d=date("D");
if ($d=="Fri"){
echo "Have a nice weekend!";
echo “have good refreshment”;
}
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following loop types with continue and break keywords which uses to control the
loops execution.
While Loop
• The while loop executes a block of code as long as the specified condition is true.
Syntax
The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to run as long
as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;):
Example
<?php $x=1;
while($x<=5) {
echo "The number is: $x <br>";
$x++;
}
?>
Do…While Loop
The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
Syntax
do { code to be executed;
The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write some output,
and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?),
and the loop will continue to run as long as $x is less than, or equal to 5:
Example
<?php $x=1; do {
echo "The number is:
$x <br>";
$x++;
} while ($x<=5); ?>
Notice that in a do while loop the condition is tested AFTER executing the statements within the loop.
This means that the do while loop would execute its statements at least once, even if the condition fails
the first time.
Parameters:
Example
<?php
for ($x=0; $x<=10; $x++)
{
echo "The number is: $x <br>";
}
?>
The for each loop works only on arrays, and is used to loop through each key/value pair in an array.
Syntax
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.
Example
<?php
$colors =array("red","green","blue","yellow");
for each ($colors as $value) { echo "$value
<br>";
}
?>
Php Arrays
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " .
$cars[1] . " and " . $cars[2] .
".";
?>
What is an Array?
An array is a special variable, which can hold more than one value at a time.
• array();
$cars=array("Volvo","BMW","Toyota");
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " .
$cars[1] . " and " . $cars[2] . ".";
?>
The count() function is used to return the length (the number of elements) of an array:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
To loop through and print all the values of an indexed array, you could use a for loop, like this:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++) {
echo
$cars[$x];
echo
"<br>";
}
?>
• Associative arrays are arrays that use named keys that you assign to them.
• There are two ways to create an associative array:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
Example
<?php
$age=array("Peter"=>"35","Ben"=>"3
7","Joe"=>"43"); echo "Peter is "
. $age['Peter'] . " years old.";
?>
To loop through and print all the values of an associative array, you could use a foreach loop, like this:
Example
<?php
$age=array("Peter"=>"35","Ben"=>"3
7","Joe"=>"43"); foreach($age as
$x=>$x_value) { echo "Key=" .
Usually used when we create forms to make communication between interfaces and
databases.
The GET Method:-
Has restriction to send to server/ database parts up to 1024 characters only.
GET can't be used to send binary data, like images or word documents, to the server
because the GET method sends the encoded user information.
The data sent by GET method can be accessed using QUERY_STRING environment
variable. Never use GET method for systems which have password or other sensitive
information to be sent to the server.
The $_GET variable is used to collect values from a form with method="get".
Information sent from a form with the GET method is visible to everyone (it will be displayed in
the browser's address bar) For example [Link]
<?php
if($_GET["name"] || $_GET["age"])
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="GET">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
The above code‘s action attribute value can be represented as the file names itself like:-
<form action=”[Link]” method=”Get”>
The POST method transfers information via HTTPs headers. The information is encoded as described in
case of GET method and put into a header called QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
Relatively secured and could large data in requesting and responding data
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header is secured enough on HTTP protocol.
The PHP provides $_POST associative array to access all the sent information using POST
method.
Variables sent with HTTP POST are not shown in the URL
The $_POST variable is used to collect values from a form with method="post".
Information sent from a form with the POST method is invisible to others For example
[Link]
The PHP $_REQUEST variable contains the contents of $_GET, $_POST, and
$_COOKIE variables
This variable can be used to get the result from form data sent with both the GET and
POST methods.
Example:- <?php
Where
• action=―…‖ is the page that the form should submit its data to, and
• method=―…‖ is the method by which the form data is submitted. If the method
is get the data is passed in the url string, if the method is post it is passed as a
separate file.
The form variables are available to PHP in the page to which they have been submitted. The
variables are available in two superglobal arrays created by PHP called $_POST and $_GET.
The basic concept that is important to understand is that any form element will automatically be
available to PHP scripts. See the following example:
</form>
When the user fills in this form and hits the submit
button, the [Link] page is called. In this file we
would write something like this:
<?php echo (―you are
($_POST['name']‖);
echo $_POST['age'];
years old.
?>
If a user who forgot to enter one of the fields or enter wrong input, we need to validate the form to
make sure it‘s complete and filled out with valid information. We can use JavaScript for this
validation. Validations can also be done with simple PHP if statements as shown below.
When the process is done, if it is done making validations, it will check to see if there is an error
message. If there is, it displays the error message. If there are no errors, it displays a success
message.
<Html>
<Body>
<form action="[Link]" method="post">
Your Name: <input type="text"
name="yourname" /><br /> E-mail:
<input type="text" name="email"
/><br/> <p>Do you like this website?
<input type="radio" name="likeit" value="Yes"
checked="checked" /> Yes
<input type="radio" name="likeit" value="No" /> No
<input type="radio" name="likeit" value="Not sure" /> Not
sure</p><br/>
<p>Your comments:<br />
All variables passed to the current script via the HTTP POST method are stored in
associative array $_POST. For example, in PHP we can access data from each field using
$_POST['NAME'], where NAME is the actual field name.
If we submit the above form, we would have access to a number of $_POST array values
inside the [Link] file:
In php, we can check the validity of inputs such as URL, E-mail, digits, letters and other special
characters etc using functions. For example preg_match() function used to match list of inputs with
defined lists. For example, see the following rules:-
i. URL Address:- If there is an input field named "website" we can check for a valid URL
address like this:
$url =
htmlspecialchars($_POST['website'])
; if
(!preg_match("/^(https?:\/\/+[\w\-
]+\.[\w\-]+)/i",$url)) { die("URL
address not valid"); }
From the code given above, if the input held by $url is not match with the given string , then the
die() function force the system to terminate the running .
ii. Digits 0-9 only: - This uses to check whether an input is digit/ number or not.
The following is a syntax to check if $age is a number or not. If not number, it display
―Please enter numbers only for Age‖ .
iii. Validate e-mail address:- Used to check an email is valid, i.e to have valid forms.
There is a simple way to check if data entered into input field named "email" is an e-mail
address without any unnecessary complications and fancy regular expressions.
$email = htmlspecialchars($_POST['email']); if
(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-
]+)/",$email)) { die("E-mail address not valid");
}
iv. Letters a-z and A-Z only:- This code will check if $text is made of letters a-z and A-Z
only (no spaces, digits or any other characters): $name = test_input($_POST["name"]);
if (preg_match("/[^a-zA-Z]/",$text)) { die("Please enter letters a-z and A-Z only!"); }
Please read Lab tutorials more about the forms and form validations.
Files and directories have three levels of access: User, Group and Other. The three typical
permissions for files and directories are: Read (r), Write (w) and Execute (x) A stream is a channel
used for accessing a resource that we can read from and write to. The input stream reads data from
a resource (such as a file) while the output stream writes data to a resource.
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 file‘s length can be found using the filesize() function which takes the file name as
its argument and returns the size of the file expressed in bytes.
Open a file using fopen() function. Syntax:- variable= fopen(―text file‖, ―mode‖);
where mode mean r, r+, w, w+ etc as shown in the next page.
Get the file's length using filesize() function. The syntax is filesize($filename );
Read the file's content using fread() function. Has syntax variable = fread( filename,
filesize);
Close the file with fclose() function. It uses when finished working with a file stream to
save space in memory.
Syntax:- fclose(file name that contains the opened files);
$handle from the following example.
Example:- Files modes can be specified as one of the six options in this table.
Mode Descriptions /Purpose
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.
<?php
?>
Deleting a Directory
• The first parameter of fread() contains the name of the file to read from and the second parameter
specifies the maximum number of bytes to read.
• Example:-
<?php
$myFile = "[Link]";
$fh = fopen($myFile, 'r');
$myFileContents =
fread($fh,filesize("[Link]"));
fclose($fh);
echo $myFileContents;
?>
• Web applications allow visitors to upload files to and from their local computer. The files that are
uploaded and downloaded may be simple text files or more complex file types, such as images,
documents, or spreadsheets
• Files are uploaded through an HTML form using the ―post‖ method and enctype attribute with
value of ―multipart/form-data,‖ which instructs the browser to post multiple sections – one for
regular form data and one for the file contents.
• The file input field creates a browser button for the user to navigate to the appropriate file to
upload <form method=‖post‖ action=‖ ‖ enctype= multipart/form-data >
<input type="file" name="picture_file" /> </form>
• The MAX_FILE_SIZE (uppercase) attribute of a hidden form field specifies the maximum
number of bytes allowed in the uploaded file and it must appear before the file input field.
• When the form is posted, information for the uploaded file is stored in the $_FILES auto global
array.
• Example:-The following HTM code below creates an uploaded form. This form is having method
attribute set to post and enctype attribute is set to multipart/form-data
<html> <body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="<?php $_PHP_SELF ?>" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
<?php
if( $_FILES['file']['name'] != "" ){
copy( $_FILES['file']['name'],
"C:\wamp\www\Leture\[Link]" ) or die( "Could not
copy file!");
}
else
{
die("No file specified!");}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name']; ?>
<li>File size: <?php echo $_FILES['file']['size']; ?> bytes
<li>File type: <?php echo $_FILES['file']['type']; ?>
</ul>
</body>
</html>
</body></html>
• 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
• Only the name parameter is required. All other parameters are optional.
• 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:
Note: The setcookie() function must appear BEFORE the <html> tag.
Example
<?php
$cookie_name = "user";
$cookie_value = "John
Doe";
setcookie($cookie_name, $cookie_value, time() + (86400
* 30), "/"); // 86400 = 1 day ?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else { echo "Cookie '" .
$cookie_name . "' is set!<br>";
echo "Value is: " .
$_COOKIE[$cookie_name];
}
?>
</body>
</html>
PHP Session
• A session is a way to store information (in variables) to be used across multiple pages.
• Unlike a cookie, the information is not stored on the users computer.
• Session variables hold information about one single user, and are available to all pages in
one application.
• If you need a permanent storage, you may want to store the data in a database.
• A session is started with the session_start() function.
• Session variables are set with the PHP global variable: $_SESSION.
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Note: The session_start() function must be the very first thing in your document. Before
any HTML tags.
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were
set on previous page echo "Favorite
color is " . $_SESSION["favcolor"] .
".<br>"; echo "Favorite animal is " .
$_SESSION["favanimal"] . ".";
?>
</body>
</html>
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>
This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be
reused on multiple pages. This will help developers to make it easy to change the layout of complete
website with minimal effort. If there is any change required then instead of changing thousand of files just
change included file.
The include() function takes all the text in a specified file and copies it into the file that uses the
include function.
If there is any problem in loading a file then the include() function generates a warning but the
script will continue execution.
Assume you want to create a common menu for your website. Then create a file [Link] with
the following content.
<a href="[Link]
<a href="[Link]
<a href="[Link]
<a href="[Link] <br />
Now create as many pages as you like and include this file to create header. For example now your
[Link] file can have following content.
<html>
<body>
<?php
include("[Link]");
?>
The require() function takes all the text in a specified file and copies it into the file
that uses the include function. If there is any problem in loading a file then the
require() function generates a fatal error and halt the execution of the script.
So there is no difference in require() and include() except they handle error
conditions.
It is recommended to use the require() function instead of include(), because scripts
should not continue executing if files are missing or misnamed.
You can try using above example with require() function and it will generate same
result. But if you will try following two examples where file does not exist then you
will get different results.
<html>
<body>
<?php
include("[Link]");
?>
<p>This is an example to show how to include wrong PHP file!</p> </body>
</html>
<html>
<body>
<?php
require("[Link]");
?>
<p>This is an example to show how to include wrong PHP
file!</p>
</body>
</html>
NOTE:-You may get plain warning messages or fatal error messages or nothing at all. This
depends on your PHP Server configuration.
What is MySQL?
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.
Database Queries
Connecting to databases
To connect PHP with database, four important things must be taken place. Those
are:-
Define constants
Create connection using mysql_connect.
Select database.
Close connection.
To connect php with database, defining constants is very important. Constants that must be
defined are:-
After defining constants using php, opening or creating connection is very important. To open or create
database connection, we use mysql_connect function.
db_server,db_user,db_pass.
Db_server:-The host name running database server
Db_user:-The username accessing the database
Db_pass:-The password of the user accessing the database.
From the above the host name running database server is ―localhost‖, the username accessing
the database is ―user‖, and the password of the user accessing the database is empty. Connection
can opened or created as follows:
$connection=mysql_connect(db_server,db_user,db_pass);
Once you establish a connection with a database server then it is required to select a particular
database where your all the tables are associated.
This is required because there may be multiple databases residing on a single server and you can
do work with a single database at a time.
$db_select=mysql_select_db(db_name,$connection);
Its simplest function mysql_close PHP provides to close a database connection. This function
takes connection resource returned by mysql_connect function. For example, to close the
connection that you use in the above; you use mysql_close function as follows:-
mysql_close($connection);
Create MySQL Database Using PHP
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. For example to
create the database test_db using php, you can write as follows:-
<?php
define("db_server","loca
lhost");
define("db_user","root")
; define("db_pass","");
$connection=mysql_connect(db_server,db_user,db
_pass); if(!$connection)
{ die("error connection to db
server".mysql_error());
} echo ―Connected
successfully‖;
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.
$sqldb=mysql_select_db(db_na
me,$con); if (!$sqldb){
die("incorrectly
selected".mysql_error());
}
'primary key (
emp_id ))';
$retval =
mysql_query($sql,$con);
if(!$retval ) {
die('Could not create table: ' .
mysql_error());
}
?>
In case you need to create many tables then its better to create a text file first and put all the SQL
commands in that text file and then load that file into $sql variable and execute those commands.
Consider the following content in sql_query.txt file.
<?php
define("db_server","localhost");
define("db_user","root");
define("db_pass","");
define("db_name","test_db");
$con=mysql_connect(db_server,db_u
$sqldb=mysql_select_db(db_na
me,$con); if (!$sqldb){
die("incorrectly
selected".mysql_error());
}
$query_file = 'sql_query.txt';
$fp = fopen($query_file,
'r'); $sql = fread($fp,
filesize($query_file));
fclose($fp);
$retval = mysql_query($sql,$con);
if(!$retval ) {
die('Could not create table: '.mysql_error());
?>
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. sql = 'INSERT INTO
employee '.
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. next
is a simple example to fetch records from employee table.
$retval = mysql_query($sql,$con);
if(!$retval ) {
die('Could not create table: ' .
mysql_error());
}
while($row = mysql_fetch_array($retval,
MYSQL_ASSOC)) { echo "EMP ID
:{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".
"--------------------------------<br>";
The content of the rows are assigned to the variable $row and the values in row are then
[Link] remember to put curly brackets when you want to insert an array value directly
into a string.
PHP provides another function called mysql_fetch_assoc() which also returns the row as an
associative array.
"--------------------------------<br>";
Using MYSQL_NUM
while($row = mysql_fetch_array($retval,
MYSQL_NUM)) { echo "EMP ID :{$row[0]}
<br> ".
"EMP NAME : {$row[1]} <br> ".
"--------------------------------<br>";
Data can be deleted from MySQL tables by executing SQL DELETE statement through PHP function
mysql_query.
Below is a simple example to delete records into employee table. To delete a record in any table it is
required to locate that record by using a conditional clause. Below example uses primary key to match a
record in employee table.
$emp_id = $_POST['emp_id'];
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.
Data can be updated into MySQL tables by executing SQL UPDATE statement through PHP function
mysql_query.
Below is a simple example to update records into employee table. To update a record in any table it is
required to locate that record by using a conditional clause. Below example uses primary key to match a
record in employee table.
$emp_id=$_POST['emp_id‘];
$emp_salary = $_POST['emp_salary‘];
Server-side scripts enhance web page interactivity and user experience by dynamically generating content based on user interactions and data inputs. These scripts allow customization of web pages according to user preferences, access privileges, or historical data, creating a personalized experience. Server-side scripting can also manage complex data operations such as retrieving and displaying data from databases in real-time, which is crucial for interactive applications like e-commerce sites. By offloading data processing to the server, developers can create more efficient interactions and streamline user experiences with less reliance on client-side resources .
PHP handles form data by utilizing superglobal arrays $_GET and $_POST, which store data sent through corresponding HTTP methods. When submitting a form with the GET method, PHP collects data appended to the URL and stores it in the $_GET array, making it accessible in the script using $_GET['fieldname']. For the POST method, PHP stores data in the $_POST array, sent via HTTP headers, and retrieves it using $_POST['fieldname']. The process involves specifying the method in the HTML form tag, which dictates how the server receives the data, enabling PHP to process or validate the incoming user input accordingly. The choice between GET and POST affects data security, visibility, and the amount of data transferable .
Client-side scripting involves code execution by the user's web browser and is typically used for creating interactive features within a webpage. These scripts are visible to the user and run after the page has been loaded, often allowing users to manipulate page content without reloading. Common client-side scripting languages include JavaScript and HTML. In contrast, server-side scripting occurs on the web server, where the script is executed before the content is delivered to the user's browser. The resulting output is typically in HTML, which the browser displays. Server-side scripting languages, such as PHP, Java, and ASP.NET, provide dynamic responses based on user input and interaction with databases, thereby offering more control over website behavior and data security .
PHP indexed arrays are collections of values assigned indices starting from zero, either automatically or manually. For instance, an indexed array $cars can be created as $cars = array('Volvo', 'BMW', 'Toyota');. This allows for accessing elements using numeric indices, e.g., $cars[0] returns 'Volvo'. Associative arrays, on the other hand, use named keys instead of numeric indices, allowing elements to be accessed by their key names. An example of an associative array is $age = array('Peter' => 35, 'Ben' => 37, 'Joe' => 43);, where $age['Peter'] returns the value 35. The choice between the two depends on whether the data is more meaningfully represented by numeric indices or descriptive keys .
PHP can restrict user access to specific web pages by implementing session-based authentication measures. This can be achieved by starting a session on the server and storing user roles or access privileges when they log in. For example, a PHP script can check if a session variable, such as $_SESSION['user_role'], matches the required role for accessing a particular page. If the condition fails, the script can redirect users to an access denied page or require re-authentication. This approach ensures that only authorized users, whose session indicates the necessary privileges, can access sensitive content .
The GET method is less appropriate in scenarios requiring the transmission of sensitive information, such as passwords, due to its inclusion of request data in the URL, making it visible and less secure. It is also limited by the URL length restriction, which is unsuitable for large amounts of data or files. Furthermore, GET is less optimal for modification operations due to the semantics associated with retrieving data, not changing it. The POST method, which sends data through HTTP headers, is preferred for secure and large data transactions as its data does not appear in the URL and has no size limitations compared to GET .
The count() function in PHP is used to determine the number of elements in an array or count the number of properties in an object implementing Countable interface. This function can be particularly useful in loops to calculate the number of iterations needed when processing array elements. For example, in a for loop iterating over an indexed array, count() can determine the stopping condition: for($i = 0; $i < count($array); $i++) {...}. This offers a way to dynamically handle arrays without hardcoding the array size, thus providing flexibility in code management particularly for applications dealing with data manipulation or dynamically-changing datasets .
Server-side scripting provides significant security advantages over client-side scripting because the source code executed on the server is not visible to the end user, reducing the risk of code tampering or exposure to potential attacks. Server-side scripts also restrict direct access to sensitive operations by validating user requests on the server, where code can be managed more securely. In contrast, client-side scripts are downloaded and executed on the user's browser, making them accessible and potentially modifiable by users, which could lead to security vulnerabilities if not properly managed .
PHP can perform several common file handling tasks on a web server, including creating, opening, reading, writing, and closing files. PHP scripts can upload files from a user to the server, process their content, and store the data in various formats. It also allows listing directory contents and managing file permissions. This versatility makes PHP a powerful tool for managing web-based applications that rely on file manipulation and storage .
PHP facilitates interactions with databases by abstracting the complexities of database connectivity and queries, allowing programmers to execute database operations using simple instructions. PHP supports multiple database management systems, including MySQL, Oracle, PostgreSQL, and Microsoft SQL Server, making it versatile for various application requirements. It simplifies database interactions by handling connectivity, data exchange, and query execution, allowing developers to focus on application logic without delving into the specifics of each database technology .