PHP (Hypertext Preprocessor) is a widely used open-source server-side scripting language designed for web development. It can be embedded into HTML and is used to create dynamic web pages. PHP code is executed on the server, and the result is sent to the client's browser as plain HTML.
PHP is a widely used server-side scripting language known for its simplicity, flexibility, and broad range of features. Some of its main features are:
Variables in PHP are defined using the '$' symbol followed by the variable name. Variable names are case-sensitive and must start with a letter or underscore.
$variableName = "value";
In PHP, there are several types of variables based on the data they can hold:
In PHP, both echo and print are used to output data to the browser:
Feature | echo | |
---|---|---|
Language Type | Language construct | Function |
Parentheses | Not required | Required |
Output | Can output multiple expressions | Can output only one expression at a time |
Return Value | No return value | Returns 1 |
Performance | Slightly faster | Slightly slower than echo |
To connect to a MySQL database using PHP, you can use the mysqli
extension or the PDO
(PHP Data Objects) extension. Here's how you can establish a connection using both methods:
// Database connection parameters
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Close connection
$conn->close();
Cookies are small files stored on the client’s computer that contain data specific to a user or website. To set a cookie in PHP, use the 'setcookie()' function:
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
This sets a cookie named "name" with the value "value" that expires in 30 days.
Sessions are used to store user data across multiple pages. To start a session, use the 'session_start()' function at the beginning of your script:
session_start();
$_SESSION["user"] = "John Doe";
This initializes a session and stores the username in the session.
In PHP, there are some ways to include files:
In PHP, errors can be handled using various methods and techniques. Some common approaches to error handling:
try {
// Code that may throw an exception
} catch (Exception $e) {
echo "Caught exception: " . $e->getMessage();
}
PHP supports three types of arrays:
You can iterate over an array using 'foreach', 'for', or 'while' loops. 'foreach' is commonly used:
foreach ($array as $key => $value) {
echo "$key: $value";
}
A class in PHP is a blueprint for creating objects. It defines properties and methods that the objects created from the class will have. Here’s an example:
class MyClass {
public $property;
function __construct($property) {
$this->property = $property;
}
public function myMethod() {
return "Hello, " . $this->property;
}
}
You create an object using the 'new' keyword followed by the class name:
$myObject = new MyClass("World");
echo $myObject->myMethod(); // Outputs: Hello, World
Inheritance is a feature in OOP where a class can inherit properties and methods from another class. The class that inherits is called the child class, and the class being inherited from is called the parent class. Use the 'extends' keyword:
class ParentClass {
public function parentMethod() {
echo "This is a parent method.";
}
}
class ChildClass extends ParentClass {
public function childMethod() {
echo "This is a child method.";
}
}
$child = new ChildClass();
$child->parentMethod(); // Outputs: This is a parent method.
Interfaces define the methods a class must implement without providing the method implementation. They are declared using the 'interface' keyword:
interface MyInterface {
public function myMethod();
}
class MyClass implements MyInterface {
public function myMethod() {
echo "Method implemented.";
}
}
Traits are a mechanism for code reuse in single inheritance languages like PHP. Traits can include methods and properties, and classes can use multiple traits. They are declared using the 'trait' keyword:
trait MyTrait {
public function myTraitMethod() {
echo "This is a trait method.";
}
}
class MyClass {
use MyTrait;
}
$object = new MyClass();
$object->myTraitMethod(); // Outputs: This is a trait method.
A constructor is a special method automatically called when an object is created. It is defined using '__construct()'. A destructor is called when an object is destroyed and is defined using '__destruct()'.
class MyClass {
public function __construct() {
echo "Constructor called.";
}
public function __destruct() {
echo "Destructor called.";
}
}
$object = new MyClass(); // Outputs: Constructor called.
Form data is handled using the '$_GET' and '$_POST' superglobals, depending on the method used in the form.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo "Name: " . $name;
}
Use the 'filter_var()' function with the 'FILTER_VALIDATE_EMAIL' filter to validate email addresses:
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
SQL injection is a code injection technique that exploits vulnerabilities in an application's software by injecting malicious SQL statements. To prevent it, use prepared statements and parameterized queries with the 'mysqli' or 'PDO' extensions.
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
Cross-Site Scripting (XSS) is a security vulnerability that allows attackers to inject malicious scripts into web pages viewed by others. To prevent XSS, sanitize user input and output using 'htmlspecialchars()' or similar functions.
$output = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
Magic methods are special methods in PHP that start with double underscores ('__'). They are called automatically in certain situations. Examples include '__construct()', '__destruct()', '__call()', '__get()', '__set()', '__toString()', and '__clone()'.
In PHP, both include and require are used to include and evaluate the content of a file in the current script. The difference is:
Feature | include | require |
---|---|---|
Behavior | Includes and evaluates a file | Includes and evaluates a file |
Error Handling | Generates a warning if file not found | Generates a fatal error if file not found |
Script Continuation | Continues script execution | Halts script execution |
Use Case | Used for optional components or files | Used for essential components or files |
PHP's 'mail()' function can be used to send emails. It requires the recipient's email address, subject, message, and additional headers.
$to = "[email protected]";
$subject = "Test Email";
$message = "This is a test email.";
$headers = "From: [email protected]";
mail($to, $subject, $message, $headers);
'$_SERVER' is a superglobal array that contains information about headers, paths, and script locations. It provides various server and execution environment information.
echo $_SERVER['PHP_SELF']; // Outputs the filename of the currently executing script
To start a session in PHP, use the 'session_start()' function. This function should be called at the beginning of the script before any output.
session_start();
$_SESSION['username'] = 'JohnDoe';
The difference between '==' and '===' in PHP are:
Feature | '==' (Equal Operator) | '===' (Identical Operator) |
---|---|---|
Comparison | Compares values, ignores data types | Compares values and data types |
Returns | True if values are equal after type coercion | True if values and data types are identical |
Type Conversion | Performs type conversion | Does not perform type conversion |
Example | $var == 10 returns true if $var is 10, regardless of its data type | $var === 10 returns true only if $var is integer and equal to 10 |
$a = "5";
$b = 5;
var_dump($a == $b); // true
var_dump($a === $b); // false
Namespaces in PHP provide a way to group related classes, interfaces, functions, and constants. They help avoid name conflicts and can be defined using the 'namespace' keyword.
namespace MyNamespace;
class MyClass {
// Class code
}
$object = new \MyNamespace\MyClass();
Handling file uploads in PHP involves setting up an HTML form with 'enctype="multipart/form-data"' to allow file uploads. On the server side, you use '$_FILES' superglobal to access the uploaded file's information. You validate the file, including its size, type, and existence, and then move it to the desired location using 'move_uploaded_file()' function.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
A constant is a name or an identifier for a simple value that cannot be changed during script execution. Define a constant using the 'define()' function.
define("MY_CONSTANT", "Some value");
echo MY_CONSTANT; // Outputs: Some value
The 'isset()' function checks if a variable is set and is not NULL. It returns 'true' if the variable exists and has a value other than NULL.
$var = "Hello";
if (isset($var)) {
echo "Variable is set.";
}
Create a cookie in PHP, you can use the setcookie() function. This function allows you to set various parameters for the cookie, such as its name, value, expiration time, path, domain, and whether it should be sent over HTTPS only.
setcookie("username", "Baibhav", time() + (86400 * 30), "/");
The difference between 'empty()' and 'isset()' in PHP are:
Feature | empty() | isset() |
---|---|---|
Checks for | Empty values (null, false, 0, empty string) | Whether a variable is set and not null |
Returns | True if variable is considered "empty" | True if variable is set and not null |
Example | empty($var) returns true for null, false, 0, '' (empty string) | isset($var) returns true if $var exists and is not null |
Useful for | Checking if a variable is empty | Checking if a variable is set and initialized |
$var = "";
var_dump(isset($var)); // true
var_dump(empty($var)); // true
To connect to a PostgreSQL database, use the 'pg_connect()' function.
$conn = pg_connect("host=localhost dbname=mydb user=myuser password=mypass");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
The 'explode()' function splits a string by a specified delimiter and returns an array of strings.
$string = "Hello,World,PHP";
$array = explode(",", $string);
print_r($array); // Outputs: Array ( [0] => Hello [1] => World [2] => PHP )
The 'implode()' function joins array elements into a single string using a specified delimiter.
$array = ["Hello", "World", "PHP"];
$string = implode(" ", $array);
echo $string; // Outputs: Hello World PHP
Use the 'header()' function to send a raw HTTP header, which can be used for redirection.
header("Location: http://www.example.com/");
exit();
The difference between str_replace() and preg_replace() in PHP are:
Feature | str_replace() | preg_replace() |
---|---|---|
Replacement | Simple string replacement | Pattern-based replacement using regex |
Search Method | Literal (exact match) | Regular expression pattern matching |
Flexibility | Limited | High |
Performance | Faster | Slower |
Use Cases | Simple string replacements | Advanced string manipulations with regex |
$string = "Hello World";
echo str_replace("World", "PHP", $string); // Outputs: Hello PHP
$string = "Hello World";
echo preg_replace("/World/", "PHP", $string); // Outputs: Hello PHP
Use 'json_encode()' to convert PHP data to JSON format and 'json_decode()' to convert JSON data to PHP format.
$array = ["name" => "John", "age" => 30];
$json = json_encode($array);
echo $json; // Outputs: {"name":"John","age":30}
$json = '{"name":"John","age":30}';
$array = json_decode($json, true);
print_r($array); // Outputs: Array ( [name] => John [age] => 30 )
Composer is a dependency management tool for PHP. It allows you to manage and install libraries and packages for your PHP projects. Use 'composer.json' to specify dependencies and run 'composer install' to install them.
The 'unlink()'
function in PHP is used to delete a file from the filesystem. It takes a filename as input and permanently removes the file from the system. It's commonly used for tasks like removing temporary files or cleaning up unwanted files.
if (unlink("test.txt")) {
echo "File deleted.";
} else {
echo "File deletion failed.";
}
Use 'include_once' or 'require_once' to include a file only once. This prevents multiple inclusions and potential redeclaration errors.
include_once "file.php";
require_once "file.php";
Prepared statements are used to execute the same SQL statement repeatedly with high efficiency and protection against SQL injection. They are supported by 'mysqli' and 'PDO'.
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
To fetch data from a MySQL database using PDO in PHP, you can follow these steps:
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
$stmt = $pdo->query("SELECT * FROM users");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
'session_start()' initializes a session or resumes the current one. It must be called at the beginning of the script before any output.
session_start();
$_SESSION['username'] = 'Baibhav';
List of different ways to read a file in PHP:
// fread
$file = fopen("test.txt", "r");
$content = fread($file, filesize("test.txt"));
fclose($file);
// file_get_contents
$content = file_get_contents("test.txt");
// fgets
$file = fopen("test.txt", "r");
while ($line = fgets($file)) {
echo $line;
}
fclose($file);
'__autoload()' in PHP was used to automatically load classes when they were accessed but not yet defined. However, it's deprecated. Use 'spl_autoload_register()' instead, which allows for more flexibility and control over class loading.
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});
To create a custom error handler in PHP:
function customError($errno, $errstr) {
echo "Error: [$errno] $errstr";
}
set_error_handler("customError");
To compress and decompress data in PHP, you can use the gzcompress() and gzuncompress() functions. These functions are part of the zlib compression library, which is included in PHP by default.
gzcompress()
function. This function takes a string as input and returns the compressed data in binary format.$data = "This is a test string.";
$compressedData = gzcompress($data);
echo "Compressed Data: " . $compressedData;
$compressedData = gzcompress("This is a test string.");
$uncompressedData = gzuncompress($compressedData);
echo "Uncompressed Data: " . $uncompressedData;
Compress and Decompress: Here’s a complete example demonstrating both compression and decompression:
<?php
// Original data
$data = "This is a test string.";
// Compress the data
$compressedData = gzcompress($data);
echo "Compressed Data: " . $compressedData . "\n";
// Decompress the data
$uncompressedData = gzuncompress($compressedData);
echo "Uncompressed Data: " . $uncompressedData;
?>