PHP Notes 2
PHP Notes 2
Php Basics -2
Learning objectives
Structure
3.1 Introduction
3.2 Definition
3.4 Loop
3.9 References
3.2 Definition
1. Condition Statement :- A conditional statement is a set of rules
performed if a certain condition is met.
2. Loop :- A loop is a sequence of instructions that is continually repeated
until a certain condition is reached.
3. Array :- A special variable used to hold multiple values at the same
time in a continuous memory.
3.3.1 If Statement
Syntax
if (condition)
{
Code to be executed starts here
}
Example
<?php
$i =10;
if($i< 20)
{
echo ('The number is less than 20');
}
?>
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
<?php
$i =21;
if($i< 20)
{
echo ('The number is less than 20');
}
else
{
echo(The number is greater than 20);
}
?>
Output
Syntax
if (condition) {
code to be executed if this condition is true;
Example
<?php
$i = 15;
if($i> 20)
{
echo ('The number is greater than 20');
}
else if($i > 10 && $i < 20)
{
echo('The number is in between 10 and 20');
}
else
{
echo ('Not a valid number');
}
?>
Output
Syntax
switch (c) {
case label1:
code to be executed if c=label1;
break;
case label2:
code to be executed if c=label2;
break;
Example
<?php
$carcolor = "blue";
switch ($carcolor) {
case "red":
echo "Your car color is red!";
break;
case "blue":
echo "Your car color is blue!";
break;
case "green":
echo "Your car color is green!";
break;
default:
echo "Your car color is neither red, blue, nor green!";
}
?>
Output
3.4 Loop
The loop is of 4 types in PHP
1. While loop
2. Do While loop
3. For loop
4. For each loop /* We shall discuss about this in arrays */
Syntax
Example
<?php
$n = 1;
while($n <= 15) {
echo "The number is: $n <br>";
$n++;
}
?>
Output
Syntax
do {
code to be executed;
} while (condition is true);
Example
<?php
$n = 1;
do {
echo "The number is: $n <br>";
$n++;
} while ($n <= 15);
?>
Output
Description
In the above example the do loop runs as long as $n<=15
Syntax
Example
<?php
for ($n = 0; $n <= 20; $n++) {
echo "The number is: $n <br>";
}
?>
Output
Description
In the above example the for loops runs from 0 to 20 and displays the output
as shown above.
3.4.3 For each loop
Syntax
foreach ($array as $value) {
code to be executed;
}
Example
<?php
$names = array("sandy","susie","alice","williams");
foreach ($names as $value) {
Description
In the above example we have defined an array $names where we defined 4
variables sandy, Susie, Alice and Williams. foreach ($names as $value) retrieves
each name from the array names and assigns it to variable $value. echo $value
displays the names in loop fashion.
Q.1 What is a condition Statement? What are the various kinds of condition
statements?
A._____________________________________________________________
A._____________________________________________________________
_____________________________________________________________
Q.3 What is a super global? What are the various kinds of SuperGlobal?
A._____________________________________________________________
_____________________________________________________________
1. W3schools.com
2. Google.com.
A.3 Super global are those variables that can be accessed from any part of the
program irrespective of the scope of the variable. The super global are
$_POST, $_GET, $_FILES, $_REQUEST, $GLOBALS,
$_SERVER,$_ENV,$_COOKIE, $_SESSION
Learning objectives
1) Form Design
2) Form Validation.
3) Form navigation
Structure
4.1 Introduction
4.2 Definition
4.6 References
1. Textbox
2. Text area
3. Password
4. Check boxes
5. Radio buttons
6. Drop down box
7. File
8. Submit
9. Reset
10. Button
In this section we shall be working on Text box and a super global $_POST.
Example :-
<html>
<body>
<form action="welcome.php" method="post">
Name Of Person: <input type="text" name="person_name"><br>
E-mail Of Person: <input type="text" name="person_email"><br>
<input type="submit">
</form>
</body>
</html>
Description
In the above example we have defined
<html>
<body>
Welcome To This Page <br>
The name of the person is : <?php echo $_POST["person_name"]; ?><br>
The email address of the person is: <?php echo $_POST["person_email"]; ?>
</body>
</html>
Output
Description
The data sent from index.php is received by welcome.php and this is receive by
command $_POST[ ].
4.3.1.2 Working With Textbox an $_GET method
In this section we shall be working on Text box and a super global $_GET
<html>
<body>
<form action="welcome.php" method="get">
Name Of Person: <input type="text" name="person_name"><br>
E-mail Of Person: <input type="text" name="person_email"><br>
<input type="submit">
</form>
</body>
</html>
Output
Description
In the above example we have defined
Q.1 What is a form ? What are input types and their use ?
A._____________________________________________________________
_____________________________________________________________
A._____________________________________________________________
_____________________________________________________________
index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<form method="post" action="welcome.php">
<textarea id="work_list" name="work_list" rows="20" cols="20"></textarea>
<input type="submit" name="submit" value="Send" id="submit"/>
</form>
</body>
</html>
welcome.php
<table>
<tr>
<td width="140">
<?php
if ($_POST['submit']) {
echo $_POST['work_list'];
}
?>
</td>
</tr>
</table>
Output
Step-1
Step-2
Description
This means that once a person clicks on the send button the person is directed to
the page welcome.php page and the method is post.
index.php
<!DOCTYPE html>
<html>
<body>
<form action="welcome.php" method="POST">
User name: <input type="password" name="user_name"><br>
User password: <input type="password" name="passwd"><br>
<input type="submit">
</form>
</body>
</html>
Output
Step-2
Description
In the above example we have defined a file named index.php which is
comprised of the code as <input type="password" name="user_name"> which
means input type is password and the name is user_name.
Description
<?php
echo('My favourite vegetables are :');
if (isset($_POST['brinjal'])){
echo $_POST['brinjal']; // Displays value of checked checkbox.
echo(",");
}
if (isset($_POST['pumpkin'])){
echo $_POST['pumpkin']; // Displays value of checked checkbox.
}
?>
Output
if (isset($_POST['city'])){
?>
Output
Description
The output is received by $_POST[CITY] which we received from the drop
down box.
Source:-
https://www.developphp.com/video/PHP/Build-an-Image-Upload-
Application-to-Enable-Working-With-Images-On-the-Fly
Images are a kind of data that are uploaded to the folder of the server.
Step-1:
Here we have defined a folder named uploads in e:\ drive and the folder path
comes to
e:\uploads.
Step-2:
Step-3:
<?php
// Access the $_FILES global variable for this specific file being uploaded
// and create local PHP variables from the $_FILES array of information
$fileName = $_FILES["my_file"]["name"]; // The file name
$fileTmpLoc = $_FILES["my_file"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["my_file"]["type"]; // The type of file it is
$fileSize = $_FILES["my_file"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["my_file"]["error"]; // 0 = false | 1 = true
$moveResult = move_uploaded_file($fileTmpLoc, "e:/uploads/$fileName");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
//unlink($fileTmpLoc);
// Remove the uploaded file from the PHP temp folder
exit();
}
// Display things to the page so you can see what is happening for testing purposes
echo "The file named <strong>$fileName</strong> uploaded successfully.<br /><br />";
echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
echo "It is an <strong>$fileType</strong> type of file.<br /><br />";
//echo "The Error Message output for this upload is: $fileErrorMsg";
?>
Output
Step-1:-
Step-2 :-
Step-4
Clicking on the upload it button the image is uploaded into it we are directed to
the screen as shown below.
Step-5
Output
Description
In the above example we prepared a button and on click an event occurs and
shows an alert message You Have Clicked Me.
Index.php
<!DOCTYPE html>
<html><body>
<form action= 'php_test.php' method='post'>
Select your favorite color:
<input type=color name=mycolor value=#ff0000>
<input type=submit>
</form>
</body>
</html>
Let us write the code for php_test.php as shown below
php_test.php
<html>
<head>
<Title> My first PHP program </title>
</head>
<body>
<?php
$p= $_POST['mycolor'];
echo $p;
?>
</body> </html>
Output
Now clicking on the submit button the control goes to php_test.php and the output is as
shown below
In the above code we have defined a input type as color and gave it a name as
mycolor and defined the value as ff0000 which is red and on clicking the
submit button we are directed to php_test.php which is #ff0000.
index.php
<!DOCTYPE html>
<html>
<body>
<form action="php_test.php" method="post">
Please enter the date of birth :
<input type="date" name="dob" >
<input type="submit"> </form> </body></html>
php_test.php
<html>
<head>
<Title> My first PHP program </title>
</head>
<body>
<?php
$p= $_POST['dob'];
echo $p;
?>
</body>
</html>
Output
Step-1
Step-3
Step-4
<!DOCTYPE html>
<html>
<body>
<input type="submit">
</form>
</body>
</html>
Output
Step-1
Step-2
After clicking the submit button we are directed to page php_test.php as shown below.
index.php
<!DOCTYPE html>
<html>
<body>
<form action="php_test.php" method="post">
<h3>A demonstration of how to access a Datetime field</h3>
<input type="datetime-local" id="myDatetime" name= "myDatetime">
<input type="submit">
------------------
<head>
<Title> My first PHP program </title>
</head>
<body>
<?php
$p= $_POST['myDatetime'];
echo ($p);
?>
</body>
</html>
Output
Step-1
Step-2
Step-3
index.php
<!DOCTYPE html>
<html>
<body>
<form action="php_test.php" method="post">
<input type="time" id="myTime" name="myTime"><br>
<input type="submit">
</form>
</body>
</html>
php_test.php
-----------------
<html>
<head>
<Title> My first PHP program </title>
</head>
<body>
<?php
$date= $_POST['myTime'];
echo date('h:i:s a', strtotime($date));
?></body></html>
Output
Open the chrome browser
Step-1
Step-3
index.php
<!DOCTYPE html>
<html>
<body>
<form action="php_test.php" method="post">
<input type="week" id="myWeek" name="myWeek"><br>
<input type="submit">
</form>
</body>
</html>
php_test.php
----------------
<html>
<head> <Title> My first PHP program </title></head>
<body>
<?php
echo $_POST['myWeek'];
?> </body></html>
Step-2
Step-3
index.php
<!DOCTYPE html>
<html>
<body>
<form action="php_test.php" method="post">
<input type="month" id="mymonth" name="mymonth"><br>
<input type="submit">
</form>
</body>
</html>
php_test.php
-----------------
<html>
<body>
<?php
echo $_POST['mymonth'];
?> </body></html>
Step-2
Step-3
index.php
<!DOCTYPE html>
<html>
<body>
<form action="php_test.php" method="post">
<input type="email" id="myemail" name="myemail"><br>
<input type="submit">
</form>
</body>
</html>
The email control is used to allow email entry only as shown below.
Step-1
Step-2
Below I entered a wrong email id and clicked the submit button and therefore got
an warning message that email address is not proper as shown below
Step-3
index.php
<!DOCTYPE html>
<html>
<body>
<form action="php_test.php" method="post">
<input type="number" id="mynumber" name="mynumber"><br>
<input type="submit">
</form>
</body>
</html>
php_test.php
<html>
<head> <Title> My first PHP program </title></head>
<body>
<?php
echo $_POST['mynumber'];
?> </body></html>
Step-1
Step-2
<!DOCTYPE html>
<html>
<body>
<form action="php_test.php" method="post">
<input type="range" id="myrange" name="myrange"><br>
<input type="submit">
</form></body></html>
php_test.php
----------------
<html>
<head>
<Title> My first PHP program </title>
</head>
<body>
<?php
echo $_POST['myrange'];
?>
</body>
</html>
Output
Step-1
Step-2
Step-1
Step-2
Clicking on the submit button directs us to the php_test.php. Clicking on the blue
cross clears the search box
index.php
<!DOCTYPE html>
<html>
<body>
<form method="post" action="php_test.php">
Your phonenumber: <input type="tel" id='tel1' name='tel1' required />
<input type="submit" value="Submit" />
</form>
</body>
</html>
php_test.php
------------------
<html>
<head>
<Title> My first PHP program </title>
</head>
<body>
<?php
echo $_POST['tel1'];
?>
</body>
</html>
Output
Step-1
Step-2
index.php
<!DOCTYPE html>
<html>
<body>
<form method="post" action="php_test.php">
Your url: <input type="url" id='url1' name='url1' required />
<input type="submit" value="Submit" />
</form></body></html>
php_test.php
-----------------
<html>
<head><Title> My first PHP program </title></head>
<body>
<?php
echo $_POST['url1'];
?>
</body>
</html>
Output
Step-1
When I enter gmail.com web page shows an error that I have to enter the url.
Step-2
The $Globals is a super global that is used to access the global variables.
<?php
$x = 100;
$y = 200;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z; ?>
Output
<?php
echo ($_SERVER['PHP_SELF']);
echo("<br>");
echo($_SERVER['SERVER_PORT']);
Output
<?php
putenv("USER=fred");
?>
Output
<?php
$_SESSION["USER_NAME"]="SHANU";
?>
Output
1. Cookie name
2. Cookie value
3. Time span of the Cookie
Create A Cookie
To create a Cookie we use the following syntax as shown below.
Setcookie(sandy,1000, time()+86400*10,/,True,False);
expire :- This parameter defines when the cookie will expire. The above cookie
will expire after 10 days. As 1 day = 86400 seconds and time()+86400*10 sets the
cookie to 10 days from the current time.
path (optional) :- This option is used to set the path. If / is written over here it
means that cookie is available for the entire domain or website that we create
like abc.com. If /process is written it means that the cookie is available for the
folder /process and is accessible by all the sub folders of the /process. If this is
not defined it means that it is accessible by the current folder.
Secure(optional) :- This option if set to true accepts only https secure connection.
If set to false data can be accessed by http and https. If this is set to blank it means
false
Httponly (optional) :- If set to true it can be accessed by http protocol only. default
is false
Example :-
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "Rohit";
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
} else {
?>
<p><strong>Note:</strong> You might have to reload the page to see the new
value of the cookie.</p>
</body>
</html>
Output
Modify A Cookie
To modify a Cookie we change the name and the value of the Cookie as shown
below.
<!DOCTYPE html>
<?php
$cookie_name = "user1";
$cookie_value = "Reshma";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<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];
}
Delete A Cookie
Delete a cookie option is used to remove the cookie from the domain or the folder.
To delete a cookie set the time value to a time which was 1 hour before. This
means that set the time to 2:30 PM if it is now 3:30 PM. Example
<!DOCTYPE html>
<?php
// set the expiration date to one hour ago
setcookie("user1", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user1' is deleted.";
?>
</body>
</html>
Output
A.____________ _________________________________________________
____________________________________________________________
____________________________________________________________
1. Text fields do not contain blank fields in case names are being entered
2. Text files contain valid email address in case email address is being
entered is a valid email.
Upon clicking the submit button without the text field being entered
Upon clicking the submit button with the text field being entered.
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email = test_input_email($_POST["email"]);
<h2>Email Verification</h2>
<?php
if ($emailErr)
{
$rr = "<p><span class = 'error'>* required field.</span></p>";
echo($rr);
}
?>
<form method = "post" action = "#">
<table>
<tr>
<td>E-mail: </td>
<td>
<input type = "text" name = "email" value=<?php echo($email); ?> >
<?php
if ($emailErr)
{
$ss = "<span class = 'error'>* <?php echo
$emailErr;?></span>";
echo($ss);
}
?>
</td>
</tr>
<tr>
<td>
<input type = "submit" name = "submit" value = "Submit">
</td>
</tr>
</table>
</form>
<?php
if ($emailErr)
{
}
Step-1
Step-2
Step-3
not allowed.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr ="";
$name ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
echo("<p><span class='error'>* required field.</span></p>");
$nameErr = "Name is required";
}
else
{
$name = test_input($_POST["name"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER['PHP_SELF']);?>">
Name: <textarea name="name" value=<?php echo($name); ?>></textarea>
<?php
if($name=='')
{
echo('<span class="error">* <?php echo $nameErr;?></span>');
}
?>
<br><br>
<input type="submit" name="submit" value="Submit">
Step-2
Upon clicking the submit button without entering anything in the text area
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
(isset($_POST["company"])) ? $company = $_POST["company"] : $company=0;
if($company==0)
{
echo("<p><span class='error'>* required field.</span></p>");
}
?>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER['PHP_SELF']);?>">
<select id="company" name="company">
<option <?php if ($company == 0 ) echo 'selected' ; ?> value="0">Select</option>
<option <?php if ($company == 1 ) echo 'selected' ; ?> value="1">Apple</option>
<option <?php if ($company == 2 ) echo 'selected' ; ?> value="2">Samsung</option>
<option <?php if ($company == 3 ) echo 'selected' ; ?> value="3">HTC</option>
</select>
<input type='submit' name='submit' value="submit">
</form>
</body>
</html>
Output
Step-1
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
Step-1
Step-2
Step-1
Step-2
Description
We shall be discussing about the code what we have written. First thing we shall
do is dissect the code into very small parts.
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
In the above part of the code we have defined a CSS class named error by the colour red.
We have defined it as color:#FF0000.
<body>
<?php
(isset($_POST["egg"])) ? $egg = $_POST["egg"] : $egg="";
Q.1 What is Form Validation? What are the various types of Form Validation
A._____________________________________________________________
_____________________________________________________________
<?php
if(isset($_POST['google']))
{
header('Location: http://google.com');
exit;
}
if(isset($_POST['yahoo']))
{
header('Location: http://yahoo.com');
exit;
}
?>
<html>
<head></head>
<body>
<form action="index.php" method="post">
<input type='submit' name='google' value='google' />
<input type='submit' name='yahoo' value ='yahoo' />
</form>
</body>
</html>
Output
Step-1
Step-2
as shown below.
In the above example we have defined two submit buttons. Upon clicking these
two submit buttons we are directed to the websites google.com and yahoo.com.
In this unit we have learnt that data is entered into the form using the form
controls. The form controls are 23 in number. These are Textbox, Text Area,
Password, Check boxes, Radio buttons, Drop down box, file, Submit, Reset,
Button, Color, Date, Date time, Date time-local, Time, Week, Month, Email,
Number, Range, Search, Tel, Url. All these controls are used for various
purposes. We use Textbox controls to enter text values such as name of the
person. The password control is used to enter passwords and other confidential
matters such as atm pin number etc. The check boxes are used to enter multiple
values such as vegetables that you like. The radio buttons are used to select one
value among multiple values such as gender of the person can be male or female.
The drop down box is used to select one item among multiple items that are
visible in a drop box such country, state and city where country is a drop down,
state is a drop down and city is a drop down. To upload images and other files
from the computer that we are using the file control. To submit the form the
submit button is used. The reset button is used to clear the form so that fresh data
can be entered into the form. The button control is used for clicking various kinds
of buttons. The color control is used to select a colour among multiple colours
that are seen. The color control is used to set the background colour of the form.
The Date control is used to enter dates such as date of birth, The date time
control is used to enter date and the time such as date of birth and time of birth but
this control is confined to Safari. The date time-local control is also used to enter
the data and time control. The time control is used to enter the time values only.
The week control is used to enter the week of the year. The month control is used
4.7 References
1. W3schools.com
2. Google.com.
or spaces to enter or view or edit or delete data. Each field holds a field label
so that any user who views the form gets an idea of its contents.These fields
are called Form controls. The Form controls are 23 in number and they are
Textbox, Text area, Password, Check boxes, Radio buttons, Drop down box,file,
Submit, Reset, Button, Color, Date, Date time, Date time-local, Time, Week,
Month, Email, Number, Range, Search, Tel, Url.
Super globals those that are used are 9 in number and they are
1. $_POST
2. $_GET
3. $_FILES
4. $_REQUEST
5. $GLOBALS
6. S_SERVER
7. $_ENV