Basic Syntax
Syntax
<?php
// Single line comment
# Another comment
/* Multi-line
comment */
echo "Hello, World!";
?>
Variables
Variable
$a = 1;
$b = "Hello";
$c = true;
$d = null;
$e = [1, 2, 3];
$f = ["name" => "John", "age" => 25];
Data Types
Type
$a = 1; // Integer
$b = 2.5; // Float
$c = 'A'; // String
$d = true; // Boolean
$e = [1,2,3]; // Array
$f = null; // Null
Strings
String
$s = "Hello";
$s2 = 'World';
$len = strlen($s);
$upper = strtoupper($s);
$name = "Alice";
$msg = "Hi, $name!";
Numbers
Number
$a = 5;
$b = 2.5;
$sum = $a + $b;
$pow = pow($a, 2);
$parsed = intval("42");
Arrays
Array
$arr = [1, 2, 3];
$assoc = ["a" => 1, "b" => 2];
$multi = [[1,2], [3,4]];
echo $arr[0];
echo $assoc["a"];
Array Functions
Array Fn
$arr = [1, 2, 3];
array_push($arr, 4);
$len = count($arr);
$sum = array_sum($arr);
$keys = array_keys($arr);
$vals = array_values($arr);
Control Flow
Control
if ($a > 0) {
echo "Positive";
} elseif ($a == 0) {
echo "Zero";
} else {
echo "Negative";
}
for ($i = 0; $i < 5; $i++) {
echo $i;
}
while ($a > 0) {
$a--;
}
switch ($a) {
case 1:
echo "One";
break;
default:
break;
}
Functions
Function
function add($a, $b) {
return $a + $b;
}
function greet($name = "World") {
echo "Hello, $name!";
}
Superglobals
Superglobal
$_GET["q"];
$_POST["name"];
$_SESSION["user"];
$_COOKIE["id"];
$_SERVER["REQUEST_URI"];
$_FILES["file"];
Forms
Form
<form method="post" action="">
<input type="text" name="name" />
<input type="submit" value="Send" />
</form>
$name = $_POST["name"] ?? "";
String Functions
String Fn
$s = "Hello World";
$len = strlen($s);
$pos = strpos($s, "W");
$rep = str_replace("World", "PHP", $s);
$parts = explode(" ", $s);
Date & Time
Date
$now = date("Y-m-d H:i:s");
$ts = time();
$dt = new DateTime();
echo $dt->format("Y-m-d");
File I/O
File
$txt = file_get_contents("file.txt");
file_put_contents("file.txt", "Hello");
$lines = file("file.txt");
Include/Require
Include
include "file.php";
require "file.php";
include_once "file.php";
require_once "file.php";
Sessions
Session
session_start();
$_SESSION["user"] = "Alice";
$user = $_SESSION["user"] ?? null;
Cookies
Cookie
setcookie("user", "Alice", time()+3600);
$user = $_COOKIE["user"] ?? null;
Error Handling
Error
try {
throw new Exception("Error!");
} catch (Exception $e) {
echo $e->getMessage();
} finally {
echo "Done";
}
Classes
Class
class User {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
}
$user = new User("John", 25);
echo $user->getName();
Objects
Object
class User {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
}
$user = new User("John", 25);
echo $user->getName();
Inheritance
Inheritance
class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Dog extends Animal {
private $breed;
public function __construct($name, $breed) {
parent::__construct($name);
$this->breed = $breed;
}
public function getBreed() {
return $this->breed;
}
}
$dog = new Dog("Buddy", "Golden Retriever");
echo $dog->getName(); // Outputs: Buddy
echo $dog->getBreed(); // Outputs: Golden Retriever
Interfaces
Interface
interface Animal {
public function makeSound();
}
class Dog implements Animal {
public function makeSound() {
echo "Woof!";
}
}
$dog = new Dog();
$dog->makeSound(); // Outputs: Woof!
Traits
Trait
trait Greet {
public function sayHello() {
echo "Hello from trait!";
}
}
class User {
use Greet;
}
$user = new User();
$user->sayHello(); // Outputs: Hello from trait!
Namespaces
Namespace
namespace App;
class User {
public function getName() {
return "User from namespace";
}
}
$user = new User();
echo $user->getName(); // Outputs: User from namespace
PDO
PDO
$dsn = "mysql:host=localhost;dbname=test";
$username = "root";
$password = "";
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([1]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($user);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
MySQLi
MySQLi
$mysqli = new mysqli("localhost", "root", "", "test");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
exit();
}
$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", 1);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
print_r($user);
$stmt->close();
$mysqli->close();
JSON
JSON
$data = ['name' => 'John', 'age' => 25];
$json = json_encode($data);
echo $json; // Outputs: {"name":"John","age":25}
$decoded = json_decode($json);
print_r($decoded); // Outputs: Array ( [name] => John [age] => 25 )
Filters
Filter
$name = "John Doe";
$filtered_name = filter_var($name, FILTER_SANITIZE_STRING);
echo $filtered_name; // Outputs: John Doe
$email = "test@example.com";
$email_filtered = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $email_filtered; // Outputs: test@example.com
$url = "http://example.com?q=test";
$url_filtered = filter_var($url, FILTER_SANITIZE_URL);
echo $url_filtered; // Outputs: http://example.com?q=test
Validation
Validation
$email = "test@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address!";
} else {
echo "Invalid email address.";
}
$age = "25";
if (filter_var($age, FILTER_VALIDATE_INT, ["options" => ["min_range" => 0, "max_range" => 100]])) {
echo "Valid age!";
} else {
echo "Invalid age.";
}
Useful Built-ins
Built-in
print_r($_SERVER); // Prints all server variables
$dir = ".";
$files = array_diff(scandir($dir), array('.', '..'));
$files = array_values($files);
print_r($files);
$path = "test.txt";
if (file_exists($path)) {
echo "File exists.";
} else {
echo "File does not exist.";
}
$size = filesize("test.txt");
echo "File size: " . $size . " bytes";
$modified = filemtime("test.txt");
echo "Last modified: " . date("Y-m-d H:i:s", $modified);
$content = file_get_contents("test.txt");
echo $content;
$content = "Hello, World!";
file_put_contents("test.txt", $content);
$lines = file("test.txt");
print_r($lines);
$content = "Hello\nWorld\n";
$lines = explode("\n", $content);
print_r($lines);
$content = "Hello, World!";
$encoded = base64_encode($content);
echo $encoded;
$decoded = base64_decode($encoded);
echo $decoded;
$hash = password_hash("password123", PASSWORD_DEFAULT);
echo $hash;
if (password_verify("password123", $hash)) {
echo "Password is correct.";
} else {
echo "Password is incorrect.";
}
$random_bytes = random_bytes(10);
echo bin2hex($random_bytes);
$random_int = random_int(1, 100);
echo $random_int;