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

WT UNIT 2

Uploaded by

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

WT UNIT 2

Uploaded by

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

UNIT II

PHP
Introduction to PHP: How PHP Works , The php.ini File, Basic PHP Syntax, PHP variables,
statements, operators, decision making, loops, arrays, strings, forms, get and post methods,
functions.
Introduction to cookies, storage of cookies at client side, Using information of cookies.
Creating single or multiple server side sessions. Timeout in sessions, Event management in
PHP.
Introduction to content management systems based on PHP.

1. How PHP Works

PHP is a server-side scripting language. The client (web browser) sends a request to
the server for a PHP page. The server processes the PHP script, executes the code, and
sends the resulting output (usually HTML) back to the client. This makes PHP a
powerful tool for dynamic and interactive web pages.

Process:

1. The user requests a PHP page via the browser.


2. The web server interprets the PHP code using the PHP engine.
3. The server returns the processed HTML content to the client.
4. The client displays the content without access to the PHP code.

Example:

<?php// This code runs on the serverecho "This is executed server-side and only the
output is visible to the client.";?>

2. The php.ini File

php.iniis the main configuration file for PHP, where server behavior can be
customized. It dictates how PHP scripts execute and handles various settings related
to performance, security, and error handling.

Common Settings:

 display_errors = On: Shows errors to help in debugging (recommended to turn off in


production).
 max_execution_time = 30: Limits script execution to 30 seconds to avoid infinite loops.
 memory_limit = 128M: Sets the maximum amount of memory a script can use.

Security Note: Improper settings can expose sensitive information or make the server
vulnerable.

Example of Configuration:
; php.inidisplay_errors = Offmax_execution_time = 60upload_max_filesize = 5M

3. Basic PHP Syntax

PHP scripts are enclosed within <?php ... ?> tags. PHP can be embedded in HTML,
making it easy to create dynamic web pages.

Rules:

 PHP code ends with a semicolon (;).


 PHP files typically have the .php extension.

Example:

<!DOCTYPE html>

<html>

<body>

<h1>Welcome Page</h1>

<?php

echo "This content is generated by PHP!";

?>

</body>

</html>

4. PHP Variables

Variables in PHP are used to store data and start with a $ symbol. PHP is a loosely
typed language, so variable types are determined by their values.

Types of Variables:

 String: A sequence of characters ($name = "John";)


 Integer: Whole numbers ($age = 30;)
 Float: Numbers with decimal points ($price = 10.99;)
 Boolean: True or false values ($isActive = true;)
 Array: Stores multiple values ($colors = array("Red", "Green", "Blue");)

Example:

<?php$name = "Alice";$age = 28;echo "Name: $name, Age: $age"; // Outputs: Name:


Alice, Age: 28?>
5. Statements and Operators

PHP supports various operators for different operations:

Types of Operators:

 Arithmetic Operators: Perform mathematical operations.

o + (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus)

 Assignment Operators: Assign values to variables.

o =, +=, -=, *=, /=

 Comparison Operators: Compare values and return boolean results.

o == (Equal), != (Not equal), >, <, >=, <=

 Logical Operators: Combine conditional statements.

o && (AND), || (OR), ! (NOT)

Example:

<?php$x = 10;$y = 5;echo $x + $y; // Outputs: 15

$isAdult = ($x > $y) && ($y < 10); // True?>

6. Decision Making

PHP supports decision-making structures that help control the flow of code based on
conditions.

Types:

 if Statement: Checks a condition and runs code if true.


 else Statement: Runs code if the if condition is false.
 elseif Statement: Checks another condition if the previous if was false.
 switch Statement: Selects one of many code blocks to execute based on a variable's
value.

Example:

<?php$day = "Monday";if ($day == "Monday") {

echo "Start of the week!";

} elseif ($day == "Friday") {


echo "End of the workweek!";

} else {

echo "Midweek day!";

}?>

7. Loops

Loops in PHP allow you to execute the same block of code multiple times.

Types:

 for Loop: Used when the number of iterations is known.


 while Loop: Continues as long as the condition is true.
 do...while Loop: Executes at least once before checking the condition.
 foreach Loop: Specifically for iterating over arrays.

Example:

<?phpfor ($i = 0; $i < 3; $i++) {

echo "Iteration $i<br>";

$colors = array("Red", "Green", "Blue");foreach ($colors as $color) {

echo "$color<br>";

}?>

8. Arrays

Arrays store multiple values in a single variable and come in different forms.

Types:

 Indexed Arrays: Use numeric keys ($fruits = ["Apple", "Banana", "Cherry"];)


 Associative Arrays: Use named keys ($ages = ["John" => 30, "Alice" => 28];)
 Multidimensional Arrays: Arrays containing other arrays.

Example:

<?php$students = array(

"John" => array("Math" => 90, "Science" => 85),

"Alice" => array("Math" => 95, "Science" => 80)


);echo $students["John"]["Math"]; // Outputs: 90?>

9. Strings

Strings in PHP are sequences of characters enclosed within single or double quotes.
PHP provides various string functions:

String Functions:

 strlen(): Returns the length of a string.


 str_replace(): Replaces all occurrences of a substring with another substring.
 substr(): Extracts a part of a string.

Example:

<?php$text = "Hello World!";echo strlen($text); // Outputs: 12echo


str_replace("World", "PHP", $text); // Outputs: Hello PHP!?>

10. Forms and GET/POST Methods

Forms collect user input and send data to the server using GET or POST.

GET:

 Appends data to the URL.


 Used for data retrieval with visible query strings.

POST:

 Sends data within the request body.


 Used for submitting sensitive or large amounts of data.

Example Form (HTML):

<form method="post" action="process.php">

<input type="text" name="username" placeholder="Enter your name">

<input type="submit" value="Submit"></form>

Example PHP Script:

<?phpif ($_SERVER["REQUEST_METHOD"] == "POST") {

$username = $_POST['username'];

echo "Hello, $username!";

}?>
11. Functions

Functions encapsulate reusable code blocks. PHP has built-in functions and allows
user-defined functions.

Example of a User-Defined Function:

<?phpfunction greetUser($name) {

return "Hello, $name!";

}echo greetUser("John"); // Outputs: Hello, John!?>

12. Cookies

Cookies store data on the client side to maintain user information across sessions.

Setting a Cookie:

<?phpsetcookie("username", "JohnDoe", time() + (86400 * 30), "/"); // Expires in 30


days?>

Reading a Cookie:

<?phpif (isset($_COOKIE["username"])) {

echo "Username: " . $_COOKIE["username"];

}?>

13. Sessions

Sessions store data on the server and are more secure than cookies as they are not
stored on the client.

Starting a Session:

<?phpsession_start();$_SESSION["user"] = "JohnDoe";?>

Accessing a Session:

<?phpsession_start();echo "Logged in as " . $_SESSION["user"];?>

Session Timeout: You can manage session timeouts by setting the


session.gc_maxlifetime directive in php.ini or manually checking for session inactivity.

14. Event Management in PHP


Event management handles user-triggered or system events like button clicks or form
submissions.

Example Handling Form Submission:

<?phpif ($_SERVER['REQUEST_METHOD'] === 'POST') {

// Process form data

echo "Form has been submitted!";

}?>

15. Content Management Systems (CMS) Based on PHP

PHP-based CMS platforms like WordPress, Joomla, and Drupal simplify content
creation and website management without extensive coding knowledge.

Benefits:

 User-friendly interfaces.
 Extensibility through plugins and themes.
 Community support and documentation.

Popular PHP-Based CMS:

 WordPress: Most popular, versatile, extensive plugin library.


 Joomla: More complex, offers advanced user management.
 Drupal: Highly flexible, suitable for large, complex websites.

You might also like