0% found this document useful (0 votes)
44 views

Unit 1

Uploaded by

anavadeepcs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Unit 1

Uploaded by

anavadeepcs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Introduction to PHP

PHP is a popular and widely used server-


side scripting language designed for web
development. It can be embedded into
HTML and offers a wide range of
functionality for developing dynamic
UP

websites and web applications.


PHP is server side scripting language implemented
by Rasmus Lerdorf in 1994 using C and PERL
languages. He implemented PHP 1.0 to track total
number of visitors in his server.PHP stands for
Personal Home Page. It also has an alias name
Hypertext Preprocessor
What is PHP?

• PHP is an acronym for "PHP: Hypertext


Preprocessor"
• PHP is a widely-used, open source scripting
language
• PHP scripts are executed on the server
• PHP is free to download and us
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"
History of PHP

1 Early Beginnings
PHP was created in 1994 by Rasmus Lerdorf. Originally, it stood for "Personal Home
Page", but it was later changed to "Hypertext Preprocessor".

2 PHP 3 and 4
The first official release of PHP was PHP 3, which added additional features and
improved functionality. PHP 4, released in 2000, introduced a new extension model.

3 PHP 5 and Beyond


PHP 5 brought more advanced features, better performance, and support for object-
oriented programming. Subsequent versions continued to enhance its capabilities.
•PHP 7 is much faster than the previous popular stable release
(PHP 5.6)
•PHP 7 has improved Error Handling
•PHP 7 supports stricter Type Declarations for function
arguments
Features of PHP
1.Open Source: PHP is free to use, distribute, and modify. It has a large community of
developers contributing to its improvement and support.

2.Cross-Platform Compatibility: PHP is compatible with various operating systems,


including Windows, Linux, macOS, and Unix. This makes it versatile for different hosting
environments.
3.Server-Side Scripting: PHP is primarily used for server-side scripting, meaning it runs on
the server and generates HTML or other output that is sent to the client's browser. This
allows for dynamic content generation on the server before sending it to the client.

4. Embedded in HTML: PHP code can be embedded directly within HTML, making it
easy to mix server-side logic with HTML code. This integration facilitates the creation of
dynamic web pages.
5. Extensive Library Support: PHP has a vast collection of built-in functions and libraries
that simplify common tasks, such as database access, file manipulation, and more.
6. Database Support: PHP supports a wide range of databases, including MySQL,
PostgreSQL, SQLite, and more. It makes it easy to connect to databases and perform
operations like querying and updating data.
Features of PHP
Database Integration Server Compatibility Scalability

PHP has built-in support for It is compatible with most PHP provides great
working with various servers used today, scalability for web
databases, such as MySQL, including Apache, Nginx, applications, making it
PostgreSQL, and and Microsoft IIS. suitable for small personal
MongoDB. websites to large enterprise
systems.
PHP vs Other Programming
Languages
Flexibility
PHP is known for its flexibility and ability to be embedded into HTML, unlike many
other programming languages.

Performance
While PHP is a server-side scripting language, it offers great performance and can
handle a significant amount of web traffic.

Community and Support


PHP has a large community and extensive documentation, providing strong support for
developers. Other languages may have different levels of community backing.
SOFTWARES REQUIRED FOR TO WORK WITH PHP:
1. Browser - Internet Explorer
2. Server - Apache
3. Server side script - PHP
4. Database – MYSQL

TOOLS TO WORK WITH PHP:

1. XAMPP - Cross Apache MYSQL PHP Perl


2. WAMPP - Window Apache MYSQL PHP Perl
3. LAMPP - Linux Apache MYSQL PHP Perl
4. MAMPP - Macintosh Apache MYSQL PHP Per
HOW TO DOWNLOAD AND INSTALL XAMPP TOOL?
1. Go to Google
2. XAMPP download in Google Search
3. Select the appropriate version of XAMPP based on the OS
4. Click on download

INSTALLATION
5. Double-click on the downloaded file
6. Click on the Next button
7. Select the drive where you want to install
8. Click on the Next button until you get the finished button
9. Click on the Finish button
Setting up a PHP Development
Environment
1 Web Server
Choose a web server that best fits your needs, such as Apache or Nginx.

2 Database
Select a compatible database, like MySQL, to store and manage your PHP application data.

3 Integrated Development Environment (IDE)


Install an IDE like Visual Studio Code or PHPStorm for a smooth development experience.
Installing PHP
When installing PHP on your system, it's important to
select the appropriate version to match your operating
system. Ensure to follow the installation instructions
precisely and confirm that the install is successful before
proceeding.
Configuring PHP Settings
Performance Optimization Security Considerations

Adjusting PHP settings can significantly Configuring PHP settings includes ensuring
impact the performance of your web that security measures, such as input validation
applications. Address memory limits, error and error handling, are properly implemented.
reporting, and execution time to optimize This helps to protect your system from
performance. potential vulnerabilities.
Embedding PHP Code in HTML
1 Script Tags 2 Inline PHP
Utilize PHP code within HTML by Embed PHP code directly within the
encapsulating it within opening and HTML body to generate dynamic
closing script tags, allowing for content and leverage PHP's powerful
seamless integration of dynamic capabilities for enhancing web pages.
functionality.
COMMON USES OF PHP

• It is used to create dynamic websites. To Interact with


web servers (Apache etc)
• To interact with any back-end/database server e.g.
MySQL
• To implement the business logical layers (one or more)
• Access the Cookies variable and set the cookies
HOW TO WRITE PHP PROGRAM
1. Open ant Editor
2. Create a New file
3. Save the file name with extension .php inside “htdocs”
folder
C:/XAMPP/htdocs(Ex: abc.php)
4. We need to write PHP code inside saved file
Ex: <?php
……..
……..
?>
5. Save again php file
• Open notepad or any editor and implement the PHP script.

<?php
Print “WELCOME”;
Print “<br>”;
$x=100;
Print $x;
?>

• Save this file in htdocs folder with .php extension.


• To display output, open the browser and enter the URL address by
Providing the site name with the server name.Notepad
Basic PHP Syntax

A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:


Example:
<?php

// php code
?>
The default file extension for PHP files is
".php".

A PHP file normally contains HTML tags, and


some PHP scripting code.
Example

<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
It will produce following result –
Hello, World
All PHP code must be included inside one of the
three special
markup tags,are recognized by the PHP Parser.

<?php PHP code goes here ?>


<? PHP code goes here ?>
<% PHP code goes here %>

<script language = "php"> PHP code goes here


</script>
A most common tag is the <?php...?> .
PHP is whitespace insensitive

Whitespace is the stuff you type that is typically invisible on the


screen, including spaces, tabs, and carriage returns (end-of-line
characters).
PHP whitespace insensitive means that it almost never matters
how many whitespace characters you have in a row. one whitespace
character is the same as many such characters

For example,
<?php
echo "This is some text with spaces preserved.";
?>
Comments in PHP
A comment in PHP code is a line that is not executed as a part of the program. Its only
purpose is to be read by someone who is looking at the code.

Single Line Comments


Single-line comments start with //.

Any text between // and the end of the line will be ignored (will not be executed).

You can also use # for single line comments.


Multi-line Comments

Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored.

/*
The next statement will
print a welcome message
*/
echo "Welcome Home!";
TYPES OF ERRORS: Mistake or fault occurs in a program is called
error. There are basically 4 types of errors in PHP:
1. Notice
2. Warning
3. Fatal Error
4. Parse Error

Notice
the error occurs when you try to access the undefined variable, and
then produce a notice error.
Example
<?php
$a="Uday ";
echo "Notice Error !!";
echo $b;
?>
warning
The main reason for warning errors is to include a missing file or
using the incorrect number of parameters in a function.
Example:
<?php
echo "Warning Error!!";
include ("Welcome.php");
?>
fatal error
If you are trying to access the undefined functions, then the
output is a fatal error.
Example
<?php
function fun1(){ fun2();
echo "Uday Kumar"; echo "Fatal Error !!";
} ?>
PARSE ERROR
The parse error occurs if there is a syntax mistake in the
script; the output is a Parse errors. The common reason of syntax
errors are:
a. Unclosed quotes
b. Missing or Extra parentheses
c. Unclosed braces
d. Missing semicolon
Example:

<?php
echo "C#";
echo "PHP"
echo "C";
?>
TAGS IN PHP:
There are four different pairs of opening and closing tags which can be used in
php. Here is the list of tags.

1. Default syntax Or Universal Tags: The default syntax starts with


"<? php" and ends with "?>".
Example:
<?php
echo "Default Syntax";
?>

2. Short open Tags: The short tags starts with "<?" and ends with "?>". Short style
tags are only available when they are enabled in php.ini configuration file on
servers.
Example:
<?
echo "PHP example with short-tags";
?>
3. HTML Script Tags: HTML script tags look like this :
<script language="php">
echo "This is HTML script tags.";
</script>
4. ASP Style Tags: The ASP style tags start with "<%" and ends with
"%>". ASP style tags are only available when they are enabled in
php.ini configuration file on servers.
Example:
<%
echo 'This is ASP like style';
%>
OUTPUT FUNCTIONS IN PHP:

echo statement

• In PHP ‘echo’ statement is a language construct and not a function, so it can be used
without parenthesis.
• But we are allowed to use parenthesis with echo statement when we are using more
than one argument with it.
• The end of echo statement is identified by the semi-colon (‘;’). We can use ‘echo’ to
output strings or variables.
• Displaying Strings: The keyword echo followed by the string to be displayed within
quotes.

<?php
echo "Hello,This is a display string example!";
?>
Output: Hello,This is a display string example!
Displaying Strings as multiple arguments:
We can pass multiple string arguments to the echo statement instead
of single string argument, separating them by comma (‘,’) operator.

For example, if we have two strings say “Hello” and “World” then
we can pass them as (“Hello”, ”World”).

<?php
echo "Multiple ","argument ","string!";
?>
Output: Multiple argument string!
print statement
• The PHP print statement is similar to the echo statement and
can be used alternative to echo at many times.
• It is also language construct and so we may not use
parenthesis:print or print ().

The main difference between the print and echo statement is


thatprint statement can have only one argument at a time and
thus can print a single string.
Displaying Variables:
Displaying variables with print statement is also same as that of
echo statement.

<?php
$text = "Hello, World!";
$num1 = 10;
$num2 = 20;
print $text."\n";
print $num1."+".$num2."=";
print $num1 + $num2;
?>
Output: Hello, World!
10+20=30
Comparison between Echo and Print in PHP:
var_dump
Using this function, we can display the value of a variable along
with data type.

Ex:
<?php
$x=100;
$y=”scott”;
var_dump($x);
var_dump($y);
?>
Output: int 100
string(5) scott
printf() :Using this function, we can print variables with
the help of format specifiers.

Example:
<?php
$x=100;
$y=”scott”;
printf(“%d”,$x);
printf(“%s”,$y);
?>
Output: 100 scott
print_r(): Using this function, we can display all elements of
array and properties of object.
Example:
<?php
$x=array(10,20,30);
print_r($x);
?>
Output:
Array
(
[0] 10
[1] 20
[2] 30
)
VARIABLES:
The variable is an identifier that holds data or another variable
and whose value can be changed at the execution time of the script.

Syntax: $variablename=value;

• 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 can't 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 ($str and $STR both are two
different)
Example:
<?php
$str="Hello world!";
$a=5;
$b=10.5;
echo "String is: $str <br/>";
echo "Integer is: $x <br/>";
echo "Float is: $y <br/>";
?>
VARIABLE SCOPES
The scope of a variable is defined as its extent in the program
within which it can be accessed, i.e. the scope of a variable is
the portion of the program within which it is visible or can be
accessed. Depending on the scopes, PHP has three variable
scopes:
Local variables: The variables declared within a function are
called local variables to that function and has its scope only in that
particular function. Example:
<?php
$num = 60;
function local_var()
{
$num = 50;
echo "local num = $num \n";
}
local_var();
echo "Variable num outside local_var() is $num \n";
?>
Output: local num = 50
Variable num outside local_var() is 60
Global variables: The variables declared outside a function are
called global variables. These variables can be accessed directly
outside a function. To get access within a function we need to use
the “global” keyword before the variable to refer to the global
variable.
Example:
<?php
$num = 20;
function global_var()
{
global $num;
echo "Variable num inside function : $num \n";
}
Output: Variable num inside function : 20
global_var(); Variable num outside function : 20
echo "Variable num outside function : $num \n";
?>
Static variable: It is the characteristic of PHP to delete the variable, once
it completes its execution and the memory is freed. But sometimes we need
to store the variables even after the Completion of the function execution.
Example:<?php
function static_var()
{
static $num = 5;
$sum = 2;
$sum++; Output: 6 3
73
$num++;
echo $num "\n";
echo $sum "\n";
}
static_var();
static_var();
?>
CONSTANTS:
Constants are name or identifier that can't be changed during
the execution of the script. In php constants are define in two
ways;
1. Using define() function
2. Using const keyword
In php declare constants follow same rule variable
declaration. Constant start with letter or underscore only.
Create a PHP Constant
Create a constant in PHP by using the define() function.

Syntax: define((name, value, case-insensitive)


Name: Specifies the name of the constant
Value: Specifies the value of the constant
Case-insensitive: Specifies whether the constant name should be
case-insensitive. Default is false

Example:
<?php
define("MSG","Hello world!"); //using case-sensitive
echo MSG;
?>
Output: Hello world!
Example:
<?php
define("MSG","Hello world!"); //using
case-insensitive
echo msg; //error
?>
Output: Hello world!
constant
Define constant using cons keyword in PHP
The const keyword defines constants at compile time. It is a
language construct, not a function. It is a bit faster than
define(). It is always case-sensitive.

Example:
<?php
const MSG="Hello world!";
echo MSG;
?>
Data types
PHP data types are used to hold different types of data or values. PHP
supports the following data types: String, Integer, Float, Boolean,
Array, Object, NULL, and Resource.

Integer:
Integers hold only whole numbers including positive and negative
numbers, i.e., numbers without fractional part or decimal point.
• They can be decimal (base 10), octal (base 8) or hexadecimal
(base16).
• The default base is decimal (base 10).
• The octal integers can be declared with leading 0 and the
hexadecimal can be declared with leading 0x.
• The range of integers must lie between -2^31 to 2^31.
Example:
<?php
// decimal base integers
$deci1 = 50;
$deci2 = 654;
$sum = $deci1 + $deci2;
echo $sum;
?>
Output: 704
Float(or)double:
• It can hold numbers containing fractional or decimal part
including positive and negative numbers.
• By default, the variables add a minimum number of decimal
places.
Example:
<?php
$val1 = 50.85;
$val2 = 654.26;
$sum = $val1 + $val2;
echo $sum;
?>
Output: 705.11
String:
• It can hold letters or any alphabets, even numbers are
included.
• These are written within double quotes during declaration.
• The strings can also be written within single quotes but it
will be treated differently while printing variables.
Example:
<?php
$name = "Krishna";
echo "The name of the Geek is $name \n";
echo 'The name of the geek is $name';
?>
Output: The name of the Geek is Krishna
The name of the geek is $name
NULL:
• These are special types of variables that can hold only one value
i.e., NULL.
• We follow the convention of writing it in capital form, but its
case sensitive.
Example:
<?php
$nm = NULL;
echo $nm; // This will give no output
?>
Boolean:
• Hold only two values, either TRUE or FALSE.
• Successful events will return true and unsuccessful events return
false.
• NULL type values are also treated as false in Boolean.
• If a string is empty then it is also considered as false in boolean
• data type.
Example:
<?php
if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>
Output: This condition is TRUE
This condition is not TRUE
What are PHP Keywords?

PHP keywords are predefined, reserved words in PHP that are used to perform
specific functions. These keywords are reserved by PHP and cannot be used as
variable names, function names, or class names. PHP keywords are case-
insensitive, meaning that they can be written in either upper or lower case
letters.
What is an Exception?
An exception is an unexcepted outcome of a program, which can
be handled by the program itself. Basically, an exception disrupts
the normal flow of the program. But it is different from an error
because an exception can be handled, whereas an error cannot be
handled by the program itself.

Exception handling is required when an exception interrupts the


normal execution of the program or application.
try -
The try block contains the code that may have an exception or where an
exception can arise. When an exception occurs inside the try block during
runtime of code, it is caught and resolved in catch block. The try block must
be followed by catch or finally block. A try block can be followed by
minimum one and maximum any number of catch blocks.
catch -
The catch block contains the code that executes when a specified exception is
thrown. It is always used with a try block, not alone. When an exception
occurs, PHP finds the matching catch block.
throw -
It is a keyword used to throw an exception. It also helps to list all the
exceptions that a function throws but does not handle itself.
Remember that each throw must have at least one "catch".
finally -
The finally block contains a code, which is used for clean-up activity in PHP.
Basically, it executes the essential code of the program.
<?php
class DivideByZeroException extends Exception { }
class DivideByNegativeNoException extends Exception { }
function checkdivisor($dividend, $divisor){
// Throw exception if divisor is zero
try {
if ($divisor == 0) {
throw new DivideByZeroException;
}
else if ($divisor < 0) {
throw new DivideByNegativeNoException;
}
else {
$result = $dividend / $divisor;
echo "Result of division = $result </br>";
}
}
catch (DivideByZeroException $dze) {
echo "Divide by Zero Exception! </br>";
}
catch (DivideByNegativeNoException $dnne) {
echo "Divide by Negative Number Exception
</br>";
}
catch (Exception $ex) {
echo "Unknown Exception";
}
}
checkdivisor(18, 3);
checkdivisor(34, -6);
checkdivisor(27, 0);
?>

Output:
Result of division = 6
Divide by Zero Exception!
Divide by Negative Number Exception!
PHP Operators: Operators are used to perform operations
on variables and values. PHP divides the operators in the
following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
PHP Arithmetic Operators: The arithmetic operators are used to perform common
arithmetical operations, such as addition, subtraction, multiplication etc. Here's a
complete list of PHP's arithmetic operators:
Operator Description Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y.
* Multiplication $x * $y Product of $x and $y.
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
<?php
$x = 10;
$y = 4;
echo($x + $y); // 0utputs: 14
echo($x - $y); // 0utputs: 6
echo($x * $y); // 0utputs: 40
echo($x / $y); // 0utputs: 2.5
echo($x % $y); // 0utputs: 2
?>
PHP Assignment Operators: The assignment operators are used to
assign values to variables.Operator Description Example Is The Same As
= Assign $x = $y $x = $y
+= Add and assign $x += $y $x = $x + $y
-= Subtract and assign $x -= $y $x = $x - $y
*= Multiply and assign $x *= $y $x = $x * $y
/= Divide and assign quotient $x /= $y $x = $x / $y
%= Divide and assign modulus $x %= $y $x = $x % $y
<?php
$x = 10;
echo $x; // Outputs: 10
$x = 20;
$x += 30;
echo $x; // Outputs: 50
$x = 50;
$x -= 20;
echo $x; // Outputs: 30
$x = 5;
$x *= 25;
echo $x; // Outputs: 125
$x = 50;
$x /= 10;
echo $x; // Outputs: 5
$x = 100;
$x %= 15;
echo $x; // Outputs: 10
?>
PHP Comparison Operators: The comparison operators are used to
compare two values in a Boolean fashion.
Operator Name Example Result
== Equal $x == $y True if $x is equal to $y
=== Identical $x === $y True if $x is equal to $y, and
they are of the same type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
!== Not identical $x !== $y True if $x is not equal to $y, orthey are not of
the same type
< Less than $x < $y True if $x is less than $y
> Greater than $x > $y True if $x is greater than $y
>= Greater thanor equal to
$x >= $y True if $x is greater than or equal to $y
<= Less than or equal to
$x <= $y True if $x is less than or equal to $y
<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true
var_dump($x < $y); // Outputs: boolean true
var_dump($x > $y); // Outputs: boolean false
var_dump($x <= $y); // Outputs: boolean true
var_dump($x >= $y); // Outputs: boolean false
?>
PHP Incrementing and Decrementing Operators
The increment/decrement operators are used to increment/decrement
a variable's value.
++$x Pre-increment Increments $x by one, then returns $x
$x++ Postincrement Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x– Postdecrement Returns $x, then decrements $x by one
<?php
$x = 10;
echo ++$x; // Outputs: 11
echo $x; // Outputs: 11
$x = 10;
echo $x++; // Outputs: 10
echo $x; // Outputs: 11
$x = 10;
echo --$x; // Outputs: 9
echo $x; // Outputs: 9
$x = 10;
echo $x--; // Outputs: 10
echo $x; // Outputs: 9
?>
PHP Logical Operators
The logical operators are typically used to combine conditional
statements.
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $$x or $y is true
! Not !$x True if $x is not true
<?php
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0))){
echo "$year is a leap year.";
}
else
{
echo "$year is not a leap year.";
}
?>
PHP String Operators
There are two operators which are specifically designed for strings.

. Concatenation

$str1 . $str2 Concatenation of $str1 and $str2

.= Concatenation assignment

$str1 .= $str2 Appends the $str2 to the $str1

<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
$x .= $y;
echo $x; // Outputs: Hello World!
?>
PHP Array Operators
The array operators are used to compare arrays:
+ Union $x + $y Union of $x and $y
== Equality $x == $y True if $x and $y have the
same key/value pairs
=== Identity $x === $y True if $x and $y have the
same key/value pairs in the
same order and of the same types
!= Inequality $x != $y True if $x is not equal to $y
<> Inequality $x <> $y True if $x is not equal to $y
!== Non-identity $x !== $y True if $x is not identical to $y
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
var_dump($x == $y); // Outputs: boolean false
var_dump($x === $y); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x <> $y); // Outputs: boolean true
var_dump($x !== $y); // Outputs: boolean true
?>
Ternary operator:
<?php
$a = 10;
$b = 20;
/* If condition is true then assign a to result otheriwse b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otheriwse b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result<br/>";
?>

You might also like