You are on page 1of 25

PHP Introduction

Pre-requisites:

1.XAMPP software :

2.Web browser :

3.Editors : or

What is PHP:
➢ PHP is a server-side scripting language designed for web development.

➢ PHP is the best solution for web development. Therefore, it is used to


develop web applications (an application that executes on the server
and generates the dynamic page.).
➢ With the help of PHP we can develop dynamic web applications.
➢ PHP is stands for "PHP: Hypertext Preprocessor"
➢ PHP is a widely-used, open source scripting language
➢ PHP scripts are executed on the server
What Can PHP Do?
➢ PHP can generate dynamic page content
➢ PHP can create, open, read, write, delete, and close files on the server
➢ PHP can collect form data
➢ PHP can send and receive cookies
➢ PHP can add, delete, and modify data in your database
➢ PHP can be used to control user-access

Why PHP?
➢ PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
➢ PHP is compatible with almost all servers used today (Apache, IIS,
etc.)
➢ PHP supports a wide range of databases

Example Program:

Simple Hello World Program in PHP


<?php
echo “welcome to the world of web programming!!”;
?>
o/p: welcome to the world of web programming!!
PHP Variables & Data Types
In PHP, a variable is declared using a $ sign followed by the variable
name. Here, some important points to know about variables:
As PHP is a loosely typed language, so we do not need to declare the
data types of the variables. It automatically analyzes the values and
makes conversions to its correct data type

PHP Integer Data Type: =


Integer means numeric data with a negative or positive sign. It
holds only whole numbers, i.e., numbers without fractional part
or decimal points.
Example:

<?php

$a=10;

echo $a;

?>

o/p:10

PHP Float Data Type:=


➢ A floating-point number is a number with a decimal point.
➢ Unlike integer, it can hold numbers with a fractional or
decimal point, including a negative or positive sign.
➢ Example:

<?php

$a=10.9;

echo $a; ?> o/p: 10.9


PHP String Data Type:=
➢ A string is a non-numeric data type. It holds letters or any
alphabets, numbers, and even special characters.
➢ String values must be enclosed either within single quotes or
in double quotes. But both are treated differently.

<?php

$a=”welcome”;

echo $a;

?> o/p: welcome

PHP Arrays
➢ An array is a special variable, which can hold more than one value at a time.
➢ In PHP, the array() function is used to create an array:

There are three types of arrays in PHP:

• Indexed arrays - Arrays with a numeric index


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

Indexed arrays:-
Arrays with a numeric index: The following example creates an indexed
array named $cars, assigns three elements to it, and then prints a text
containing the array values:

<?php
$fruits = array("Mango", "Apple", "Sapota");
echo "I like " . $fruits[0] . ", ". $fruits[1];
?>
o/p: I like Mango,Apple
Loop through an Indexed Array
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>";
}
?>
o/p: Volvo
BMW
Toyota
PHP Associative Arrays
➢ Associative arrays are arrays that use named keys that you assign to
them.

➢ PHP allows you to associate name/label with each array elements in PHP
using => symbol.
➢ Such way, you can easily remember the element because each element is
represented by label than an incremented number.

<?php
$cseroll=array("kiran"=>"30","Vamshi"=>"45","Rishi"=>"60");
echo "Kiran rollno is: ".$cseroll["kiran”]."<br/>";
echo "Vamshi rollno is: ".$cseroll["Vamshi"]."<br/>";
echo "Rishi rollno is: ".$cseroll["Rishi"]."<br/>";
?>
o/p: Kiran rollno is: 30
Vamshi rollno is: 45
Rishi rollno is: 60

Loop through an Associative Array


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"=>"37", "Joe"=>"43");

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


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
o/p: Key=Peter , Value=35
Key=Ben ,Value=37
Key=Joe , Value=43

PHP Multidimensional Arrays


A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more levels
deep.

<?php
$cars = array (array ("Volvo", 22, 18),
array ("BMW", 15, 13));
echo $cars[0][0].”<br>”;
echo $cars[1][0];
?>
o/p: Volvo
BMW
Control Structures:

PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is
true.

If statement is used to executes the block of code exist inside the if statement only
if the specified condition is true.

Ex:
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>

PHP If-else Statement

PHP if-else statement is executed whether condition is true or false.

If-else statement is slightly different from if statement. It executes one block of


code if the specified condition is true and another block of code if the condition
is false.
Program to find the given number is odd or even

<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>

The PHP switch Statement


Use the switch statement to select one of many blocks of code to be
executed.

First we have a single expression n (most often a variable), that is evaluated


once. The value of the expression is then compared with the values for each
case in the structure. If there is a match, the block of code associated with that
case is executed. Use break to prevent the code from running into the next case
automatically. The default statement is used if no match is found.
<?php
$favcolor = "blue";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and
over again a certain number of times. So, instead of adding several almost
equal code-lines in a script, we can use loops.

Loops are used to execute the same block of code again and again, as long as a
certain condition is true.

In PHP, we have the following loop types:

• while - loops through a block of code as long as the specified condition is


true
• do...while - loops through a block of code once, and then repeats the
loop as long as the specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array

While: The while loop - Loops through a block of code as long as the
specified condition is true.

While Loop Example:


<?php
$x = 1;

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

Example Explained
• $x = 1; - Initialize the loop counter ($x), and set the start value to 1
• $x <= 5 - Continue the loop as long as $x is less than or equal to 5
• $x++; - Increase the loop counter value by 1 for each iteration
Do-while Example:
The do...while loop - Loops through a block of code once, and
then repeats the loop as long as the specified condition is true.
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

PHP For Loop


PHP for loop can be used to traverse set of code
for the specified number of times.
It should be used if the number of iterations is
known otherwise use while loop. This means for
loop is used when you already know how many
times you want to execute a block of code.
<?php
for($x=1;$x<=10;$x++)
{
echo “welcome to CSE<br>”;
}
?>
PHP Functions: A function is a block
of statements that can be used repeatedly in a
program.
❖ A function will not execute automatically when
a page loads.
❖ A function will be executed by a call to the
function.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can
be invoked many times, like in other programming languages.

Less Code: It saves a lot of code because you don't need to


write the logic many times. By the use of function, you can write
the logic only once and reuse it.

Easy to understand: PHP functions separate the programming


logic. So it is easier to understand the flow of the application
because every logic is divided in the form of functions.

PHP User-defined Functions


<?php
function Hi()
{
echo "Hello PHP Function";
}
Hi();//calling function
?>
o/p: Hello PHP Function
PHP Function with Arguments
❖ We can pass the information in PHP function through arguments which is
separated by comma.

<?php
function Hi($name){
echo "Hello $name<br/>";
}
Hi("Benn");
?>

o/p: Hello Benn

Addition of two numbers using functions:


//Adding two numbers
<?php
function add($x, $y) {
$sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>";
}
add(100, 200);
?>

o/p: Sum of two numbers is = 300


//Multiplying two numbers
<?php
//Adding two numbers
function multiply($x, $y) {
$z = $x * $y;
echo "Multiplication of two numbers is = $z <br><br>";
}
multiply(100, 200);
?>

o/p: Multiplication of two numbers is = 2000


PHP String functions
PHP provides various string functions to access and manipulate strings.

A list of PHP string functions are given below.

1. <?php

echo strrev("Hello World");

?> o/p: dlroW olleH

2. <?php

echo strlen("Hello");

?> o/p: 5

3. <?php
echo strtolower("Hello WORLD.");
?> hello world

4 .<?php
echo strtoupper("Hello world");
?> o/p: HELLO WORLD

5. <?php
echo ucfirst("hello world!");
?> o/p: Hello world!

6.<?php

echo lcfirst(“Welcome”);

?> o/p: welcome


PHP form Handling
We can create and use forms in PHP. To get form data, we need to use PHP superglobals

$_GET or $_POST.

GET and POST

The form request may be get or post. To retrieve data from get request, we need to use
$_GET, for post request $_POST.

PHP Get Form


Get request is the default form request. The data passed through get request is visible on
the URL browser so it is not secured. You can send limited amount of data through get
request

PHP Post Form


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.

Reading data from the FORM Controls


➢ We can create and use forms in PHP. To get form data, we need to use PHP
superglobals $_GET and $_POST.
➢ The PHP superglobals $_GET and $_POST are used to collect form-data.
➢ When the user fills out the form 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 POST method.
cs.php

Welcomes.php
MySQL Connection Using PHP Script
❖ PHP provides mysqli_connect() function to open a database connection.
❖ This function takes five parameters and returns a MySQL link identifier on
success or FALSE on failure.

❖ MySQLi is an extension that only supports MySQL databases.

❖ It allows access to new functionalities found in MySQL systems (version 4.1.


and above).

❖ The MySQLi extension is included PHP version 5 and newer.

PHP program to connect with MySQL Database software:


PHP program to create a new Database with MySQL Database

PHP program to create a new Table In MySQL Database


File Uploads in PHP:

• With PHP, it is easy to upload files to the server.


• Some rules to follow for the HTML form above:
• Make sure that the form uses method="post"
• The form also needs the following attribute: enctype="multipart/form-data".
• It specifies which content-type to use when submitting the form

Without the requirements above, the file upload will not work.

Other things to notice:

The type="file" attribute of the <input> tag shows the input field as a file-select
control, with a "Browse" button next to the input control.

-----------------------------------------------------------

move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough
the POST request. It moves the file if it is uploaded through the POST request.

send.php
Receive.php:
File Handling in PHP

• Opening File
• Reading File
• Writing File
• Closing File

Modes

▪ ‘ r ’ -------→ Open for reading only.


▪ ‘r+’-----→ Open for reading and writing.
▪ ‘w’------→Open for writing only.
▪ ‘w+’-----→Open for reading and writing.
▪ ‘a’------→ Open for writing only.

Functions to perform operations on the files

fopen() ,fwrite(), fgets(), unlink()

File operations:
1.Create a file
<?php

$new=”cse.txt”;

Fopen($new,’w’);

?>

2.Write text inside a file


<?php

$new=”cse.txt”;

$result=fopen($new,’w’);
$data=”welcome”;

Fwrite($result,$data);

?>

3.Reading the content of the file


<?php

$myfile=fopen(“cse.txt”,’r’);

Echo fgets($myfile);

?>

4.Update the content of a file


<?php

$myfile=”cse.txt”;

$result=fopen($myfile,’a’);

$data=”To CSE”;

Fwrite($result,$data);

?>

5.Delete the file


<?php

$myfile=”cse.txt”;

Unlink($myfile);

?>
PHP Sessions
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.

When you work with an application, you open it, do some changes, and then
you close it. This is much like a Session. The computer knows who you are. It
knows when you start the application and when you end. But on the internet
there is one problem: the web server does not know who you are or what you
do, because the HTTP address doesn't maintain state.

Session variables solve this problem by storing user information to be used


across multiple pages (e.g. username, favorite color, etc). By default, session
variables last until the user closes the browser.

So; Session variables hold information about one single user, and are available
to all pages in one application.

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

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

echo "the favorite color is" .$_SESSION["favcolor"]."<br>";

?>

</body>

</html>

PHP Cookies
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.

Create Cookies With PHP


A cookie is created with the setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.

You might also like