$ variable = 10 ;
define ("CONSTANT_VALUE " , 5 );
$ integer = 42 ;
$ float = 3.14 ;
$ string = "Hello, PHP! " ;
$ boolean = true ;
$ array = array (1 , 2 , 3 );
$ object = new stdClass ();
$ null = null ;
$ fruits = ["Apple " , "Banana " , "Orange " ];
array_push ($ fruits , "Mango " );
$ person = ["name " => "John " , "age " => 25 ];
$ person ["city " ] = "New York
if ($ age >= 18 ) {
echo "You are an adult. " ;
} else {
echo "You are a minor. " ;
}
for ($ i = 0 ; $ i < 5 ; $ i ++) {
echo $ i ;
}
$ count = 0 ;
while ($ count < 5 ) {
echo $ count ;
$ count ++;
}
function greet ($ name ) {
return "Hello, $ name! " ;
}
include "header.php " ;
require "config.php " ;
$ file = fopen ("data.txt " , "r " );
$ content = fread ($ file , filesize ("data.txt " ));
fclose ($ file );
try {
// Code that may throw an exception
} catch (Exception $ e ) {
echo "An error occurred: " . $ e ->getMessage ();
}
setcookie ("username " , "John " , time () + 3600 , "/ " );
$ username = $ _COOKIE ["username " ];
session_start ();
$ _SESSION ["user_id " ] = 123 ;
if ($ _SERVER ["REQUEST_METHOD " ] == "POST " ) {
$ username = $ _POST ["username " ];
$ password = $ _POST ["password " ];
}
MySQL Database Connection
$ servername = "localhost " ;
$ username = "root " ;
$ password = "password " ;
$ database = "mydb " ;
$ conn = new mysqli ($ servername , $ username , $ password , $ database );
$ sql = "SELECT * FROM users WHERE username=' $ username' " ;
$ result = $ conn ->query ($ sql );
while ($ row = $ result ->fetch_assoc ()) {
echo "Name: " . $ row ["name " ];
}
Inserting data into MySQL
$ sql = "INSERT INTO users (username, password) VALUES (' $ username', ' $ password') " ;
$ conn ->query ($ sql );
$ sql = "UPDATE users SET email=' $ email' WHERE id= $ user_id " ;
$ conn ->query ($ sql );
$ sql = "DELETE FROM users WHERE id= $ user_id " ;
$ conn ->query ($ sql );
Object-oriented programming
class Person {
public $ name ;
public $ age ;
public function greet () {
echo "Hello, my name is $ this ->name . " ;
}
}
class Student extends Person {
public $ studentID ;
}
Composer (Dependency Manager)
// Install a package
composer require vendor/package
// Autoload packages
require 'vendor/autoload.php ' ;
$ pattern = "/[0-9]{4}-[0-9]{2}-[0-9]{2}/ " ;
$ validDate = preg_match ($ pattern , "2023-09-04 " );
$ to = "recipient@example.com " ;
$ subject = "Hello " ;
$ message = "This is a test email. " ;
$ headers = "From: sender@example.com " ;
mail ($ to , $ subject , $ message , $ headers );
// Handle GET request
if ($ _SERVER ["REQUEST_METHOD " ] == "GET " ) {
$ data = ["message " => "GET request received " ];
echo json_encode ($ data );
}
if ($ _FILES ["file " ]["error " ] == 0 ) {
move_uploaded_file ($ _FILES ["file " ]["tmp_name " ], "uploads/ " . $ _FILES ["file " ]["name " ]);
}
$ data = '{"name": "John", "age": 30} ' ;
$ decodedData = json_decode ($ data );
$ currentDate = date ("Y-m-d H:i:s " );
// Include a template file
include "template.php " ;
$ file = fopen ("data.txt " , "w " );
fwrite ($ file , "Hello, PHP! " );
fclose ($ file );
Sessions and User Authentication
session_start ();
if (!isset ($ _SESSION ["user_id " ])) {
// Redirect to login page
}
header ("Location: https://example.com " );
Content-Type Headers
header ("Content-Type: application/json " );
Creating and Using Classes
class Car {
private $ make ;
private $ model ;
public function __construct ($ make , $ model ) {
$ this ->make = $ make ;
$ this ->model = $ model ;
}
public function getInfo () {
return "Make: $ this ->make , Model: $ this ->model " ;
}
}
if (file_exists ("oldfile.txt " )) {
unlink ("oldfile.txt " );
}
$ xml = simplexml_load_string ("<book><title>PHP Basics</title></book> " );
$ title = $ xml ->title ;
Namespaces in Autoloading
// Autoloading classes within a namespace
spl_autoload_register (function ($ className ) {
$ className = str_replace ("\\" , DIRECTORY_SEPARATOR , $ className );
require_once __DIR__ . "/ {$ className }.php " ;
});
Exception handling and custom exception classes
class MyCustomException extends Exception {}
try {
// Some code that may throw an exception
throw new MyCustomException ("This is a custom exception. " );
} catch (MyCustomException $ e ) {
echo "Caught exception: " . $ e ->getMessage ();
}
Dependency injection in classes
class Database {
public function __construct ($ hostname , $ username , $ password , $ database ) {
// Database connection setup
}
}
$ database = new Database ("localhost " , "username " , "password " , "mydb " );
Namespaces for code organization
namespace MyNamespace ;
class MyClass {
// Class code here
}
PDO (PHP Data objects) for database access
try {
$ pdo = new PDO ("mysql:host=localhost;dbname=mydb " , "username " , "password " );
$ pdo ->setAttribute (PDO ::ATTR_ERRMODE , PDO ::ERRMODE_EXCEPTION );
} catch (PDOException $ e ) {
echo "Connection failed: " . $ e ->getMessage ();
}
Dependency injection in functions
function calculateTotal ($ price , $ taxRate ) {
return $ price * (1 + $ taxRate );
}
$ total = calculateTotal (100 , 0.1 );
Namespaces for third-party libraries
use Vendor \Library \Class ;
$ instance = new Class ();
require 'vendor/autoload.php ' ;
class Singleton {
private static $ instance ;
private function __construct () {}
public static function getInstance () {
if (self ::$ instance === null ) {
self ::$ instance = new Singleton ();
}
return self ::$ instance ;
}
}
$ file = 'example.txt ' ;
header ('Content-Description: File Transfer ' );
header ('Content-Type: application/octet-stream ' );
header ('Content-Disposition: attachment; filename=" ' .basename ($ file ).'" ' );
readfile ($ file );