Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Unit 10 Note 06 php basics

The document provides an overview of PHP, a server-side scripting language used for web development, highlighting its key features such as server-side scripting, database interaction, and security. It covers various aspects of PHP programming, including variable types, loops, conditional statements, and variable scopes, along with examples to illustrate their usage. Additionally, it discusses common use cases for PHP, including website development and API creation.

Uploaded by

matheeshabest
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit 10 Note 06 php basics

The document provides an overview of PHP, a server-side scripting language used for web development, highlighting its key features such as server-side scripting, database interaction, and security. It covers various aspects of PHP programming, including variable types, loops, conditional statements, and variable scopes, along with examples to illustrate their usage. Additionally, it discusses common use cases for PHP, including website development and API creation.

Uploaded by

matheeshabest
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit 10 Web development Note 06 php properties AL English Medium Kithsiri jayakody

PHP (Hypertext Preprocessor) is a widely-used, open-source server-side scripting


language primarily designed for web development. It is often embedded within HTML
and is used to create dynamic web pages and interact with databases. PHP scripts are
executed on the server, generating HTML that is sent to the client’s browser. As a result,
PHP is responsible for the backend functionality of websites and web applications.

Key Features of PHP:

1. Server-Side Scripting: PHP runs on the server, meaning it is executed on the


web server before the output is sent to the user's browser. This makes it useful
for processing forms, interacting with databases, and generating dynamic
content.
2. Open-Source: PHP is free to use, and its source code is open for developers
to modify and enhance. It is supported by a large community, which contributes
to continuous improvements and updates.
3. Database Interaction: PHP is commonly used with databases
like MySQL, MariaDB, PostgreSQL, and SQLite to store and retrieve data
dynamically. It makes tasks like handling form submissions, managing user
data, and displaying database-driven content easy.
4. Cross-Platform: PHP is platform-independent. It can run on a variety of
operating systems, including Windows, Linux, and macOS, and can interact
with many web servers, such as Apache, Nginx, and IIS.
5. Embedded in HTML: PHP code can be embedded directly within HTML
code, making it easy to add server-side functionality to web pages. The PHP
code is enclosed within <?php ... ?> tags.
6. Dynamic Content Creation: PHP can generate dynamic web content, such as
displaying personalized content based on user input, showing product
recommendations, or generating reports based on data.
7. Session Management: PHP provides features to manage user sessions,
allowing for features like login/logout functionality and storing user data
between page reloads.
8. Security: PHP includes built-in functions to help developers secure their web
applications, including methods for data encryption, input sanitization, and
protection against attacks such as SQL injection and Cross-Site Scripting
(XSS).
9. Extensive Libraries and Frameworks: PHP offers numerous libraries and
frameworks (like Laravel, Symfony, and CodeIgniter) that streamline
development, making it easier to build complex web applications.
10. Support for Cookies and Sessions: PHP allows web developers to manage
state by working with cookies and sessions, essential for features like shopping
carts and user authentication.
Common Use Cases of PHP:

• Website Development: PHP is used to create dynamic, interactive websites


like e-commerce sites, social networks, content management systems (e.g.,
WordPress, Drupal), and forums.
• Web Applications: PHP is used for building web apps that require server-side
processing, like customer relationship management (CRM) systems or
inventory management systems.
• Form Handling: PHP can process and validate form data, store it in a
database, or send it via email.
• Content Management Systems (CMS): Many popular CMS platforms like
WordPress and Joomla are built using PHP.
• APIs: PHP is often used to develop RESTful APIs for communication
between web services.

Example of PHP in Action:

Simple PHP Script:

<?php echo "Hello, World!" ; // This will display "Hello, World!" in the browser ?>

PHP with HTML:

<!DOCTYPE html>
<html>
<head>
<title>PHP Example</title>
</head>
<body>
<?php $name = "John" ;
echo "<h1>Hello, $name!</h1>" ; // This will display "Hello,
John!" on the page ?>
</body>
</html>

Conclusion:

PHP is a powerful tool for web developers. It can handle a wide range of tasks, from
displaying dynamic content to interacting with databases and managing sessions. Its
ability to integrate with HTML and databases makes it a key player in the development
of modern web applications.
Variables

in PHP, variables can hold data of different types. Here are the basic types of variables
in PHP:

Scalar Types:
• Integer: A whole number, positive or negative, without a decimal point.

$age = 25 ; // Integer
• Float (or Double): A number that can have a decimal point.
php

$price = 19.99 ; // Float


• String: A sequence of characters enclosed in single or double quotes.

$name = "John Doe" ; // String


• Boolean: A value that is either true or false.

$is_active = true ; // Boolean

Compound Types:

• Array: A collection of values stored in a single variable, with each


value having an index.

$colors = array ( "red" , "green" , "blue" ); // Array

Special Types:

• NULL: A special type representing a variable with no value.


$value = NULL ; // NULL

PHP Comments

Comments are used to add notes in the code. They are not executed and are used for
documentation, explanation, or debugging purposes.

• Single-line Comments:
• These are used for short comments that fit on one line.
• You can use // or #.
// This is a single-line comment $x = 5 ; // Assign value to x # This is also a
single-line comment
• Multi-line Comments:
• These are used for longer comments that span multiple lines.
• You use /* to begin and */ to end the comment.

/* This is a multi-line comment spanning multiple lines */ $y = 10 ;

• PHP Documentation Comments (DocBlock):


• These comments are used for generating documentation and typically
include information about functions, parameters, and return values.
They are marked with /** and */.

PHP Variable Scopes

The scope of a variable in PHP determines where it can be accessed. PHP has different
types of variable scopes:

Global Scope:
• A variable declared outside any function has a global scope and is
accessible throughout the entire script (except inside functions, unless
explicitly referenced).
• To access a global variable inside a function, you need to use
the global keyword or use the super global variable $GLOBALS.

$x = 10 ; // Global variable

function show()
{ global $x ; // Accessing the global variable
echo $x ; // Output: 10 }

show ();

Local Scope:
• A variable declared inside a function is said to have a local scope and
can only be accessed within that function.

function test()

{ $y = 5 ; // Local variable
echo $y ; // Output: 5 }
test ();
echo $y ; // Error: Undefined variable

Static Variables:
• A static variable inside a function maintains its value between function
calls. It's useful when you want the function to "remember" its state
across calls without using global variables.
• A static variable is declared with the static keyword.

function counter() {
static $count = 0 ; // Static variable
$count ++; echo $count ; // Output: 1, 2, 3... }

counter (); // Output: 1


counter (); // Output: 2
counter (); // Output: 3
19. Superglobals:
• Superglobal variables are built-in variables that are always accessible,
regardless of scope. They are used to access data from external sources
like forms, cookies, and session variables.
• Common superglobals include:
• $_GET, $_POST, $_REQUEST (for form data)
• $_SESSION (for session variables)
• $_COOKIE (for cookies)
• $_SERVER (for server-related information)
• $_FILES (for file uploads)

Summary of PHP Variable Scopes:

• Global Scope: Variables declared outside functions, accessible throughout the


script (with global or $GLOBALS inside functions).
• Local Scope: Variables declared inside functions, only accessible within the
function.
• Static Variables: Variables inside functions that retain their values between
function calls.
• Superglobals: Predefined global variables that are accessible from anywhere
in the script.
Understanding variable types, comments, and variable scopes is crucial for effective
PHP programming, especially when working with dynamic and interactive websites.

PHP Loops: while, do-while, and for

Loops are used in PHP to execute a block of code multiple times. There are three main
types of loops in PHP:

while Loop
do-while Loop
for Loop

Each loop has its specific use cases depending on how many times you need to repeat
the code and the conditions required.

while Loop

The while loop repeats a block of code as long as the specified condition is true. It
checks the condition before executing the code block.

Syntax:

while (condition) { // Code to be executed }


• Condition is evaluated before entering the loop.
• The loop continues to run as long as the condition is true.

Example:

<?php $count = 1 ;
while ( $count <= 5 )
{ echo "Count is: $count<br>" ;
$count ++; }
?>

Count is : 1 Count is : 2 Count is : 3 Count is : 4 Count is : 5

Explanation:

• The loop will continue as long as $count is less than or equal to 5.


• Each time, it prints the value of $count and then increments it by 1.
do-while Loop

The do-while loop is similar to the while loop, but the difference is that it executes the
code block at least once before checking the condition. The condition is
checked after the code block is executed.

do { // Code to be executed }

while (condition);
• The code inside the do block is executed once before checking the condition.

<?php $count = 1 ;
do {
echo "Count is: $count<br>" ; $count ++; }
while ( $count <= 5 ); ?>

Output:

Count is : 1 Count is : 2 Count is : 3 Count is : 4 Count is : 5

Explanation:

• Even if the condition is false initially, the code will execute once.
• The loop continues as long as $count is less than or equal to 5, printing and
incrementing the value.

3. for Loop

The for loop is used when you know in advance how many times the code should be
executed. It is typically used for iterating over a fixed number of iterations.

Syntax:

for (initialization; condition; increment/decrement) { // Code to be executed }


• Initialization: Sets the initial value of the counter.
• Condition: The loop runs as long as this condition is true.
• Increment/Decrement: Increases or decreases the counter after each iteration.

Example:

<?php for ( $count = 1 ; $count <= 5 ; $count ++) {


echo "Count is: $count<br>" ; } ?>
Output:

Count is : 1 Count is : 2 Count is : 3 Count is : 4 Count is : 5

Explanation:

• The loop starts with $count = 1.


• It runs as long as $count <= 5.
• After each iteration, $count is incremented by 1 ($count++).

Comparison of Loops

• while Loop:
• The condition is checked before executing the loop.
• The loop may not run at all if the condition is false initially.
• do-while Loop:
• The loop is guaranteed to run at least once, as the condition is
checked after the loop execution.
• Ideal when you need the code to run at least once, regardless of the
condition.
• for Loop:
• Best suited for count-controlled loops, where you know the number of
iterations beforehand.
• Combines initialization, condition checking, and increment/decrement
in a single line.

Summary:

• while Loop: Executes as long as the condition is true. The condition is


checked before the code runs.
• do-while Loop: Executes at least once, checking the condition after the code
runs.
• for Loop: Ideal when the number of iterations is known in advance. All loop
control (initialization, condition, and increment/decrement) is handled in one
line.

PHP Conditional Operators and if Conditions

Conditional operators in PHP are used to evaluate expressions and control the flow of
the program based on the evaluation result. The most common control structure is
the if statement, which allows the program to execute certain code only if a specific
condition is true.
PHP if Statement

The if statement checks a condition and, if the condition is true, it executes the block
of code inside it.

Syntax:

if (condition) { // Code to be executed if condition is true }

Example:

<?php $age = 18 ;
if ( $age >= 18 )
{ echo "You are an adult!" ; } ?>

Output:

You are an adult !

Explanation:

• The condition $age >= 18 is true, so the message "You are an adult!" is printed.

if-else Statement

The if-else statement provides an alternative block of code to execute when the
condition is false.

if (condition) { // Code to be executed if condition is true } else { // Code to be


executed if condition is false }

Example:

<?php $age = 16 ;
if ( $age >= 18 )
{
echo "You are an adult!" ; }
else {
echo "You are not an adult!" ; } ?>

Output:

You are not an adult !

Explanation:
• The condition $age >= 18 is false, so the else block executes and prints "You
are not an adult!".

if-elseif-else Ladder

The if-elseif-else structure allows for multiple conditions to be checked in sequence. If


the first condition is false, the program checks the next condition, and so on. If none of
the conditions are true, the else block is executed.

Syntax:

if (condition1) { // Code to be executed if condition1 is true }


elseif (condition2) { // Code to be executed if condition2 is true }
else { // Code to be executed if none of the above conditions are true }

Example:

<?php $age = 25 ;
if ( $age < 18 ) { echo "You are a minor." ; }
elseif ( $age >= 18 && $age <= 65 ) { echo "You are an adult." ; }
else { echo "You are a senior." ; } ?>

Output:

You are an adult.

Explanation:

• The first condition $age < 18 is false, so it moves to the next condition.
• The second condition $age >= 18 && $age <= 65 is true, so the message "You
are an adult." is printed.

PHP Conditional (Ternary) Operator

The ternary operator is a shorthand for the if-else statement. It evaluates a condition
and returns one of two values based on whether the condition is true or false.

Syntax:

(condition) ? true_value : false_value;

Example:

<?php $age = 20 ; echo ( $age >= 18 ) ? "Adult" : "Minor" ; ?>

Output:
Explanation:

• The condition $age >= 18 is true, so the string "Adult" is returned and printed.

PHP Comparison Operators

Comparison operators are used to compare two values or expressions. These operators
return a Boolean value (true or false) based on the comparison.

Common Comparison Operators:

• ==: Equal to
• ===: Identical (equal in value and type)
• !=: Not equal to
• !==: Not identical
• <: Less than
• >: Greater than
• <=: Less than or equal to
• >=: Greater than or equal to

Example:

<?php $x = 10 ; $y = 20 ;
if ( $x == $y ) {
echo "x is equal to y" ; }
else {
echo "x is not equal to y" ; } ?>

x is not equal to y

Explanation:

• The condition $x == $y checks if $x and $y are equal. Since they are not,
the else block is executed.

Logical Operators in PHP

Logical operators are used to combine multiple conditions. The most common logical
operators are:

• &&: AND (returns true if both conditions are true)


• ||: OR (returns true if at least one condition is true)
• !: NOT (inverts the Boolean value)
Example:

<?php $age = 22 ;
$has_permission = true ;
if ( $age >= 18 && $has_permission )
{ echo "Access granted." ; }
else
{ echo "Access denied." ; } ?>

Output:

Access granted.

Explanation:

• The condition $age >= 18 && $has_permission checks if both conditions are
true. Since both are true, the message "Access granted." is printed.

Switch Case (Alternative to if-elseif-else)

The switch statement is an alternative to if-elseif-else when you need to check a single
variable against multiple values. It evaluates an expression and matches it
with case values.

Syntax:

switch (expression) {
case value1: // Code to be executed if expression is equal to value1 break ;
case value2: // Code to be executed if expression is equal to value2 break ;
default : // Code to be executed if no match is found }

Example:

<?php $day = 3 ;
switch ( $day ) {
case 1 : echo "Monday" ; break ;
case 2 : echo "Tuesday" ; break ;
case 3 : echo "Wednesday" ; break ;
default : echo "Invalid day" ; } ?>

Output:

Wednesday

Explanation:
• The switch statement checks the value of $day and matches it with the
corresponding case value. Since $day is 3, it prints "Wednesday".

Summary of PHP Conditional Operators and if Conditions:

• if Statement: Executes code if the condition is true.


• if-else Statement: Executes one block of code if the condition is true,
otherwise executes another block.
• if-elseif-else Ladder: Checks multiple conditions in sequence.
• Ternary Operator: A shorthand for if-else that returns a value based on a
condition.
• Comparison Operators: Used to compare values (e.g., ==, !=, <, >=).
• Logical Operators: Used to combine multiple conditions (e.g., &&, ||, !).
• Switch Statement: An alternative to if-elseif-else when comparing a variable
to multiple values.

These conditional structures allow you to control the flow of your program, making it
respond to different inputs or situations.

You might also like