PHP
Introduction of PHP:
PHP Stands for Hypertext Pre-processor is a widely used open source server side scripting language.
Originally created by Danish-Canadian programmer Rasmus Lerdorf in 1994, PHP has since evolved into one of the most popular languages for web development.
PHP is designed to be embedded in html and can be used to generate dynamic web pages, handle form data, manage sessions, and interact with databases. It can also be used to build web application, content management systems (cms), e-commerce platforms, and many other types of web-based software
LAMP Development Framework
Uses Of PHP:
Why we use PHP?
Versions of PHP:
PHP Installation:
Installing PHP via XAMPP is a convenient option if you're setting up a local development environment on Windows, macOS, or Linux. XAMPP bundles Apache, MySQL, PHP, and Perl into an easy-to-install package. Here's how you can install PHP using XAMPP:
Go to the Apache Friends website (https://www.apachefriends.org/index.html) and download the appropriate XAMPP installer for your operating system.
Start XAMPP:
After installation, start the XAMPP control panel. On Windows, this is usually done by double-clicking the XAMPP desktop icon or launching it from the Start menu. On macOS and Linux, you can start XAMPP from the Terminal.
Start Apache and MySQL:
In the XAMPP control panel, start the Apache and MySQL services by clicking the "Start" buttons next to them. This will start the web server (Apache) and the database server (MySQL).
Access PHPMyAdmin (Optional):
XAMPP includes PHPMyAdmin, a web-based tool for managing MySQL databases. You can access PHPMyAdmin by opening your web browser and navigating to http://localhost/phpmyadmin.
Test PHP:
To test PHP, create a new PHP file in the XAMPP htdocs directory (this is usually located in the XAMPP installation directory).( C:\xampp\htdocs)
Open a text editor and create a new file named Basic.php.
Comment Line:
In PHP, comments are used to add explanatory notes within the code that are not executed as part of the program. They are primarily for the benefit of developers to understand the code. PHP supports two types of comments:
Single Line Comment:
These comments begin with two forward slashes (//) and continue until the end of the line. They are used for short comments on a single line.
Multi Line Comment:
These comments begin with /* and end with */. They can span multiple lines and are often used for longer explanations or to comment out blocks of code temporarily.
Variables:
In PHP, variables are used to store data values. They begin with the dollar sign ($) followed by the variable name.
Example:
In PHP, variables are loosely typed, meaning you don't need to explicitly declare the data type of a variable when you create it. PHP infers the data type based on the value assigned to it. For example:
Variables can store various types of data, such as strings, integers, floats, arrays, objects, and more. Here are some examples:
PHP also supports variable interpolation within double-quoted strings, meaning you can directly embed variables within a string. For example:
You can also concatenate variables and strings using the dot (.) operator:
Remember, PHP variable names are case-sensitive, meaning $name, $Name, and $NAME are treated as different variables.
Var_dump():
In PHP, var_dump() is a function used for debugging purposes to display structured information (type and value) about one or more variables. It's particularly useful during development to inspect the contents of variables and to understand their data types and values.
Example:
Output:
Data Types:
Variables can store data of different types, and different data types can do different things. Here are some of the fundamental data types in PHP:
Integer data type represents whole numbers without any decimal points.
2. String:
String data type represents a sequence of characters enclosed within single quotes (' ') or double quotes (" ").
3. Float:
Float data type represents numbers with a decimal point or numbers in exponential form.
4. Boolean:
Boolean data type represents a logical value, which can be either true or false.
5. Array:
An array stores multiple values in one single variable.
6. Object:
Object data type represents an instance of a class.
7. Null:
The special NULL value represents a variable with no value assigned to it.
8. Resource:
Resource data type is a special type that holds a reference to an external resource (like a database connection).
Type Conversion:
In PHP, type conversion allows you to convert a value from one data type to another. PHP provides several functions and methods to perform type conversion.
OPERATORS:
PHP operator is a symbol i.e operators are used to perform operations on variables or values.
For example:
$num=10+20;
PHP divides the operators in the following groups:
1. Arithmetic operators:
In PHP, arithmetic operators are used to perform mathematical operations on variables and values. Here are the basic arithmetic operators in PHP
1. Addition (+): Adds two operands.
2. Subtraction (-): Subtracts the right operand from the left operand.
3. Multiplication (*): Multiplies two operands.
4. Division (/): Divides the left operand by the right operand.
5. Modulus (%): Returns the remainder of the division of the left operand by the right operand.
6. Exponentiation (**): Raises the left operand to the power of the right operand.
2. Assignment operators:
In PHP, assignment operators are used to assign values to variables. They combine the operation of assigning a value to a variable with another operation, such as addition or subtraction. Here are the assignment operators in PHP
Assignment (=): Assigns the value of the right operand to the left operand.
1. Addition assignment (+=): Adds the value of the right operand to the left operand and assigns the result to the left operand.
2. Subtraction assignment (-=): Subtracts the value of the right operand from the left operand and assigns the result to the left operand.
3. Multiplication assignment (*=): Multiplies the value of the left operand by the value of the right operand and assigns the result to the left operand.
4. Division assignment (/=): Divides the value of the left operand by the value of the right operand and assigns the result to the left operand.
5. Modulus assignment (%=): Computes the modulus of the left operand with the value of the right operand and assigns the result to the left operand.
6. Concatenation assignment (.=): Concatenates the value of the right operand to the value of the left operand and assigns the result to the left operand.
7. Exponentiation assignment (=):** Raises the value of the left operand to the power of the right operand and assigns the result to the left operand.
3. Comparison operators:
In PHP, comparison operators are used to compare two values and determine their relationship. These operators return a Boolean value (true or false) based on the comparison result. Here are the comparison operators in PHP
Equal (==): Checks if the values of two operands are equal
4. Increment and Decrement operators:
In PHP, the increment and decrement operators are used to increase or decrease the value of a variable by one. Here's how they work:
Here's a simple program demonstrating the usage of these operators:
4. Logical operators:
In PHP, logical operators are used to combine conditional statements. There are three main logical operators: AND (&&), OR (||), and NOT (!). Here are some examples of how they can be used:
2. OR (||) Operator: The || operator returns true if at least one of the operands is true.
3. NOT (!) Operator: The ! operator negates the value of its operand.
5. String operators
In PHP, string operators are used to manipulate strings, concatenate them, and perform other operations. Here are the main string operators in PHP
Concatenation Operator (.): The dot (`.`) operator is used to concatenate two strings together.
Concatenation Assignment Operator (.=): This operator is a combination of concatenation and assignment. It appends the right operand to the left operand and assigns the result to the left operand.
Here's a simple program demonstrating the usage of these operators:
6. Array operators
In PHP, array operators are used to perform operations on arrays. There are two main array operators: union (+) and equality (== and ===). Here's how they work:
Union Operator (+): The union operator (+) returns the union of two arrays. It returns an array containing all the unique elements from both arrays.
Equality Operators (== and ===): The equality operators (== and ===) are used to compare the equality of two arrays. The == operator checks if the arrays have the same key/value pairs, while the === operator also checks if they are of the same type.
7. Conditional assignment operators
In PHP allow you to assign a value to a variable based on a condition. These operators are shorthand for common conditional assignment scenarios. There are two main conditional assignment operators in PHP: the ternary operator (`?:`) and the null coalescing operator (`??`). Let me explain each of them with examples:
The ternary operator is a concise way to write an if-else statement in PHP.
Syntax: `$variable = (condition) ? value_if_true : value_if_false;`
In this example, if the condition $age >= 18 is true, the value "You are an adult." will be assigned to $message; otherwise, "You are a minor." will be assigned.
The null coalescing operator is used to assign a default value to a variable if the variable is null.
Syntax: `$variable = $value ?? $default_value;`
In this example, if the 'user' parameter is present in the GET request, its value will be assigned to `$userName;` otherwise, the default value 'Guest' will be assigned.
CONTROL STATEMENTS
PHP provides several control statements to manage the flow of execution in your code. Here's an overview of some common control statements in PHP:
1. if...else Statement:
It allows you to execute code conditionally based on the result of a Boolean expression.
2. switch Statement:
It is used to perform different actions based on different conditions.
3. while Loop:
It executes a block of code as long as the specified condition is true.
4. do...while Loop:
Similar to the while loop, but it always executes the block of code at least once, even if the condition is false.
5. for Loop:
It executes a block of code a specified number of times.
6. foreach Loop:
It is used to iterate over arrays.
7. break Statement:
It terminates the execution of a loop or switch statement.
8. continue Statement:
It skips the rest of the current loop iteration and continues with the next iteration.
PHP Arrays
Arrays are fundamental data structures in PHP, allowing you to store multiple values in a single variable. PHP supports various types of arrays, including indexed arrays, associative arrays, and multidimensional arrays.
Here's an overview of each type:
Indexed Arrays:
Indexed arrays use numeric keys to access elements. Keys start from 0 and increase sequentially.
Associative Arrays:
Associative arrays use named keys to access elements. Keys can be strings or integers.
Mixed Arrays:
Arrays can also contain a mix of indexed and associative elements.
Multidimensional Arrays:
Arrays can hold other arrays as elements, creating multidimensional arrays.
Array Functions:
PHP provides a wide range of functions to manipulate arrays, including `count()`, `array_push()`, `array_pop()`, `array_shift()`, `array_unshift()`, `array_slice()`, `array_merge()`, `array_reverse()`, `array_key_exists()`, `in_array()`, etc.
Arrays are fundamental to PHP programming and are extensively used for storing, manipulating, and iterating over collections of data. They offer flexibility and convenience in handling complex data structures.
Constant Arrays:
In PHP, you can define arrays as constants using the `define() function or the `const` keyword.
FUNCTIONS
PHP functions are blocks of reusable code that perform a specific task. They allow you to modularize your code, making it easier to manage, debug, and maintain.
Here's a brief overview of PHP functions:
Functions in PHP are defined using the function keyword followed by the function name and parentheses containing optional parameters. The syntax looks like this:
Once defined, you can call a function by simply using its name followed by parentheses. If the function accepts parameters, you pass them inside the parentheses.
For example:
Functions can accept zero or more parameters. Parameters are variables that are passed to the function and are used within the function's body. Parameters can have default values, making them optional.
For example:
Functions can return values using the `return` statement. This allows the function to pass data back to the code that called it.
For example:
Variables defined within a function are local to that function by default, meaning they cannot be accessed outside the function. However, you can use the `global` keyword to access global variables from within a function.
PHP comes with a large number of built-in functions that perform common tasks, such as manipulating strings, working with arrays, handling dates, etc. For example, `strlen()`, `explode()`, `date()`, etc.
PHP supports anonymous functions, also known as closures. These are functions without a specified name, which can be assigned to variables or passed as arguments to other functions.
SUPERGLOBALS
This is a PHP superglobal variable that is itself an associative array containing references to all variables which are currently defined in the global scope of the script. It allows you to access global variables from anywhere in your PHP script.
This superglobal array contains information about the server and the execution environment. It includes information such as server paths, headers, script locations, etc. It's useful for obtaining information about the current request.
Contains variables passed to the current script via the URL parameters (i.e., in the query string). It's commonly used to retrieve data sent to the script through HTTP GET requests.
Contains variables passed to the current script via HTTP POST method when a form is submitted with method="post". It's commonly used to retrieve form data submitted by users.
Contains information about uploaded files through HTTP POST method. When a file is uploaded via a form with enctype="multipart/form-data", this array contains information such as file name, type, size, etc.
Contains variables passed to the current script via HTTP cookies. It's commonly used to store and retrieve session identifiers or other small pieces of data on the client side.
Contains session variables available to the current script. Session variables are stored on the server and can be accessed across multiple pages during a user's session. It's commonly used to store user-specific data.
A merge of $_GET, $_POST, and $_COOKIE arrays. It can be used to collect data sent through both GET and POST requests. However, using it is not recommended for security reasons, as it can make your script vulnerable to attacks like CSRF (Cross-Site Request Forgery).
Contains environment variables available to the script. These are often set by the web server or system and can provide information about the server environment.
FILE HANDLING
PHP provides various functions and methods for handling files, such as reading from and writing to files, manipulating file metadata, and more. Here's a basic overview of file handling in PHP:
Opening and Closing Files
You can open a file using the fopen() function and close it using fclose() when you're done.
Reading from Files
You can read from a file using functions like `fgets()`, `fread()`, or `file_get_contents()`.
Writing to Files
You can write to a file using functions like `fwrite()` or `file_put_contents()`.
Appending to Files
You can append to a file using the "a" mode in `fopen()` or `file_put_contents()`.
Checking File Existence
You can check if a file exists using `file_exists()`.
File Metadata
You can get information about a file using functions like `filesize()`, `filemtime()` (modification time), `filetype()`, etc.
Deleting Files
You can delete a file using `unlink()`.
Handling Errors
Always check for errors when performing file operations, especially when opening files.
OBJECT ORIENTED PROGRAMMING
Object-oriented programming (OOP) in PHP allows you to organize your code into classes and objects, providing a more modular and structured approach to programming. Here's a basic overview of OOP concepts in PHP:
Classes and Objects
2. Object Instantiation: Create an instance of a class using the new keyword.
Properties
2. Getter and Setter Methods: Encapsulate property access with getter and setter methods.
Methods
Constructor and Destructor
Inheritance
Interfaces and Abstract Classes
2. Abstract Classes: Define abstract classes using the abstract keyword, which cannot be instantiated directly but can contain abstract methods.
Static Members
Static Properties and Methods: Declare properties and methods as static to make them accessible without an instance of the class.
Namespaces
Namespace Declaration: Organize classes into namespaces to avoid naming conflicts.