0% found this document useful (0 votes)
7 views8 pages

UNIT1 PHP

This document provides an introduction to PHP, covering its definition, key features, and history. It explains how to embed PHP code in HTML, send data to web browsers using GET and POST methods, and discusses variables, constants, expressions, conditional statements, looping statements, data types, operators, and keywords in PHP. The document serves as a comprehensive guide for beginners to understand the fundamentals of PHP programming.

Uploaded by

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

UNIT1 PHP

This document provides an introduction to PHP, covering its definition, key features, and history. It explains how to embed PHP code in HTML, send data to web browsers using GET and POST methods, and discusses variables, constants, expressions, conditional statements, looping statements, data types, operators, and keywords in PHP. The document serves as a comprehensive guide for beginners to understand the fundamentals of PHP programming.

Uploaded by

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

Unit1:Introduction to PHP:

What is PHP?
PHP stands for Hypertext Preprocessor (though it originally meant Personal Home Page). PHP was primarily
created by Rasmus Lerdorf, a Danish-Canadian programmer It's a widely-used open-source scripting language
specifically designed for web development. This means it's free to use and relatively easy to learn compared
to other programming languages

Key features of PHP:


1.Server-side scripting: PHP code runs on the web server before the content is sent to the user's browser.
This allows for creating dynamic web pages that can adapt based on user input or data from a database.
2.Embeds in HTML: PHP code can be inserted directly into HTML files using special tags. This makes it easy to
combine the logic and structure of your web pages.
3.Database interaction: PHP can connect to and work with databases like MySQL to store and retrieve
information. This is essential for building features like user accounts, shopping carts, and content
management systems.
4.Form handling: PHP can process data submitted through HTML forms, allowing users to interact with your
web application.
5.Wide range of functionalities: PHP can handle various tasks like file handling, sending emails, user
authentication, and more.
6.Relatively easy to learn: With a C-like syntax, PHP has a gentle learning curve for beginners.
7.Open-source and free: There's no cost to use PHP, making it an accessible option for personal and
commercial projects.
8.Object-oriented programming: PHP supports object-oriented features for better code organization and
reusability

History of PHP
PHP's journey began in the early 1990s with Rasmus Lerdorf, a Danish-Canadian programmer. Here's a
glimpse into its evolution:
1993-1994: Lerdorf creates a set of Common Gateway Interface (CGI) scripts in C to manage his personal
website.
1995: Lerdorf expands these scripts to include functionalities like tracking visitors and guestbooks. He
releases it as "Personal Home Page Tools" (PHP Tools).
1995: A major rewrite happens, and it's christened "Personal Home Page/Forms Interpreter" (PHP/FI). This
version boasts a more advanced scripting interface.
1997: With growing popularity, a team effort led by Zeev Suraski and Andi Gutmans rewrites the PHP/FI
parser, forming the base for PHP Version 3. This version is considered much closer to the PHP we know
today.
1998: Work begins on a complete overhaul of PHP's core by Andi Gutmans and Zeev Suraski.
2004: PHP 5 is released after extensive development. It introduces significant improvements in performance,
object-oriented programming features, and error handling.
Present: PHP continues to evolve with new features and versions being released regularly. The focus remains
on enhancing performance, security, and integration with modern frameworks.

Embedding PHP code in web pages


1. Using PHP Tags:
PHP code is embedded within HTML files using PHP tags (<?php ...?>). These tags tell the web server to
execute the enclosed PHP code before sending the HTML content to the browser.
Example:
<html>
<body>
<h1>Hello, World!</h1>
<?php
$message = "This is a message from PHP!";
echo "<p>$message</p>";
?>
</body>
</html>
2. Mixing PHP and HTML: You can freely mix PHP code with HTML code within a single file. This allows for
dynamic content generation based on PHP logic.
3. Including PHP Files: Similar to HTML's include directive, PHP provides include and require statements to
include the content of another PHP file. This helps organize larger projects and promotes code reusability.

Sending data to the web browser in PHP


In PHP, you can send data from your server-side script to the web browser using two primary methods:
1.GET Method: GET method is suitable for sending small amounts of non-sensitive data, such as search
parameters, sorting criteria, or pagination controls
Example:
index.php (form)
<form action="process.php" method="get">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<button type="submit">Submit</button>
</form>

process.php (server-side script)


if (isset($_GET['name'])) {
$name = $_GET['name'];
echo "Hello, $name!";
}
2.POST Method:
POST is ideal for sending larger amounts of data or any data that needs to be kept confidential. It's
commonly used for submitting form data, uploading files, and processing user actions that might modify
server-side data.
Example:
index.php (form)
<form action="process.php" method="post">
<label for="message">Message:</label>
<textarea name="message" id="message"></textarea>
<button type="submit">Submit</button>
</form>

process.php (server-side script)


if (isset($_POST['message'])) {
$message = $_POST['message'];
// Process the message (e.g., store it in a database)
}
Comments
Temporarily disable code sections by enclosing them in comments. This is useful for testing purposes or
when debugging specific parts of your script.
Types of Comments in PHP:
Single-line comments: Use two forward slashes (//) followed by your comment text. Everything after // on
that line is ignored.
// This is a single-line comment
Multi-line comments: Use a starting delimiter (/) and an ending delimiter (/) to enclose your comment text.
This allows comments to span multiple lines.
/*
This is a multi-line comment
It can span multiple lines
*/

Variable in php
Variables in PHP are like containers that hold information you can use throughout code. They allow to store and
manipulate data of various types.
Declaring Variables:
Use a dollar sign ($) followed by the variable name.
Variable names can contain letters, numbers, and underscores, but must start with a letter or underscore.
PHP is case-sensitive, so $name and $NAME are considered different variables.
Example:
$firstName = "John";
$age = 30;
$isStudent = true;

Constants in PHP
Constants in PHP are essentially fixed values that, unlike variables, cannot be changed after they are defined during
script execution. They provide a way to represent values that should remain consistent throughout code.
Constants are created using either the define() function or the const keyword (introduced in PHP 5.3).

Syntax:define(name, value, case_insensitive):


Example:
define("PI", 3.14159); // Using define()
const MAX_USERS = 100; // Using const keyword

Expressions
Expressions in PHP are the fundamental building blocks of your code. They are any combination of values, variables,
operators, and function calls that can be evaluated to produce a single value

Conditional statements
Conditional statements in PHP are fundamental constructs that allow your code to make decisions and execute different
blocks of code based on specific conditions. They are essential for creating dynamic and interactive programs.

1. if statement:
Checks a single condition.
If the condition is true, the code block within the if statement executes.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
}

2. if-else statement:
Checks a single condition.
If the condition is true, the code block within the if statement executes.
If the condition is false, the code block within the else statement executes (optional).
Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}

Example:
$grade = "B";
if ($grade == "A") {
echo "Excellent work!";
} else {
echo "Keep practicing!";
}

3. if-elseif-else statement:
Checks multiple conditions one by one.
If the first condition is true, its corresponding code block executes, and the rest are skipped.
If the first condition is false, it checks the second elseif condition (optional), and so on.
If none of the conditions are true, the optional else block executes.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} elseif (condition2) {
// Code to execute if condition1 is false and condition2 is true
} else {
// Code to execute if all conditions are false
}
Example:
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} else {
echo "Grade: C";
}

4. switch statement:
Evaluates an expression against a list of values.
If a match is found, the corresponding code block executes.
It's useful for handling multiple conditions that check for the same variable against different values.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
default:
// Code to execute if no match is found (optional)
}
Example:
$day = "Monday";
switch ($day) {
case "Saturday":
case "Sunday":
echo "It's the weekend!";
break;
default:
echo "It's a weekday.";
}

Looping statements
PHP provides several looping statements to execute a block of code repeatedly. Here's a breakdown of the common
ones:

1.for Loop:
Ideal when you know the exact number of iterations beforehand.
Syntax:
for ($initialization; $condition; $increment/decrement) {
// Code to be executed
}
Exampe:
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}

2.while Loop:
Executes the code block as long as a specified condition is true.
Syntax:
while ($condition) {
// Code to be executed
}

Exampe:
$input = "";
while ($input !== 'q') {
$input = readline("Enter 'q' to quit: ");
if ($input !== 'q') {
echo "You entered: $input\n";
}
}
3. do-while Loop:
Similar to while loop, but the code block executes at least once even if the condition is initially false.
Syntax:
do {
// Code to be executed
} while ($condition);
Exampe:
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);

4.foreach Loop:
Specifically designed to iterate over arrays or similar data structures.
Syntax :
foreach ($array as $value) {
echo $value . " ";
}
Exampe:
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
echo "$x <br>";
}

PHP Data Types


Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
1. String
2. Integer
3. Float
4. Boolean
5. Array
1.String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example
$x = "Hello world!";
$y = 'Hello world!';
var_dump($x);
echo "<br>";
var_dump($y);

2.Integer
An integer data type is a non-decimal number
Rules for integers:
An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation
Example
$x = 5985;
var_dump($x);
3.Float
A float (floating point number) is a number with a decimal point or a number in exponential form.
Example
$x = 10.365;
var_dump($x);

4.Boolean
A Boolean represents two possible states: TRUE or FALSE.
Example
$x = true;
var_dump($x);

5. Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type and value:
Example
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);

The "? Operator"


The "? Operator" in PHP, also known as the nullish coalescing operator, is a relatively new addition (introduced in PHP
7.0) that provides a concise way to handle null values. It offers a shortcut for checking if a variable is null and assigning a
default value if it is.
Syntax:
$result = $variable ?? $default_value;
$variable: The expression to be evaluated.
??: The nullish coalescing operator.
$default_value: The value to be assigned if $variable is null.

How it Works:
The expression ($variable) is evaluated.
If the expression evaluates to null, the ?? operator assigns the $default_value to the result ($result).
If the expression evaluates to a non-null value (including 0, false, an empty string, or any other value), that value is
directly assigned to the result ($result).
Example:
$name = null;
$greeting = "Hello, " . ($name ?? "Guest") ."!";
echo $greeting; // Output: Hello, Guest!

Keywords
In PHP, keywords are special words that have a predefined meaning and function within the programming language.
These keywords cannot be used for other purposes like variable names or function names. They are the building blocks
that define the structure and functionality of your PHP code.

Purpose: Define statements, control flow, functions, and other core aspects of code.
Examples: if, else, for, while, function, class, echo, print.
Cannot be used as: Variable names, function names, or constants (except for some special cases).
Understanding keywords is essential for writing valid and efficient PHP code
Operators
In PHP, operators are special symbols that perform operations on values (operands) to produce a new result. They are
essential for manipulating data, performing calculations, making comparisons, and controlling the flow of code.

1. Arithmetic Operators:
Perform basic mathematical operations like addition, subtraction, multiplication, division, etc.
Examples: +, -, *, /, % (modulus - remainder after division)
2. Comparison Operators:
Used to compare values and return a boolean (true/false) result.
Examples: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), >= (greater than or
equal to)
3. Logical Operators:
Combine conditions to create more complex logical expressions.
Examples: && (AND - both conditions must be true), || (OR - at least one condition must be true), ! (NOT - inverts the
truth value)
4. Assignment Operators:
Assign values to variables, sometimes combined with other operations.
Examples: = (simple assignment), += (add and assign), -= (subtract and assign), *= (multiply and assign), etc.
5. Increment/Decrement Operators:
Increase or decrease the value of a variable by 1.
Examples: ++ (pre-increment - increment before use), -- (pre-decrement - decrement before use), $x++ (post-increment
- use the value and then increment), $x-- (post-decrement - use the value and then decrement

You might also like