Php Cheatsheet

🐘 PHP Basics

<?php
// Output
echo "Hello World!";
print "Hello Again";

// Variables
$name = "Alice";
$age = 25;

// Constants
define("SITE_NAME", "MaxonCodes");

// Data Types
$int = 42;
$float = 3.14;
$string = "Hello";
$bool = true;
$array = [1, 2, 3];
?>

🔀 Control Structures

<?php
// If Else
if ($age >= 18) {
  echo "Adult";
} else {
  echo "Minor";
}

// Switch
switch ($day) {
  case "Mon": echo "Start of week"; break;
  case "Fri": echo "Weekend soon"; break;
  default: echo "Midweek";
}

// Loops
for ($i = 0; $i < 5; $i++) {
  echo $i;
}

$nums = [10,20,30];
foreach ($nums as $n) {
  echo $n;
}
?>

⚡ Functions

<?php
function greet($name) {
  return "Hello $name!";
}

echo greet("Alice");

// Default Args
function add($a, $b = 10) {
  return $a + $b;
}

echo add(5); // 15
?>

🏗️ OOP (Object-Oriented PHP)

<?php
class Car {
  public $brand;

  function __construct($brand) {
    $this->brand = $brand;
  }

  function drive() {
    echo "Driving $this->brand";
  }
}

$car = new Car("Tesla");
$car->drive();
?>

📩 Handling Forms

<form method="post">
  <input type="text" name="username">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $user = $_POST['username'];
  echo "Hello, " . htmlspecialchars($user);
}
?>

💾 MySQL with PDO

<?php
$dsn = "mysql:host=localhost;dbname=testdb";
$user = "root";
$pass = "";

try {
  $pdo = new PDO($dsn, $user, $pass);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  // Insert
  $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
  $stmt->execute(["Alice", "alice@email.com"]);

  // Fetch
  $stmt = $pdo->query("SELECT * FROM users");
  while ($row = $stmt->fetch()) {
    echo $row['name'] . "<br>";
  }
} catch (PDOException $e) {
  echo "DB Error: " . $e->getMessage();
}
?>

🔒 Security Tips

<?php
// Prevent SQL Injection (use prepared statements)
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);

// XSS Protection
echo htmlspecialchars($_POST['input']);

// Password Hashing
$hash = password_hash("mypassword", PASSWORD_BCRYPT);
if (password_verify("mypassword", $hash)) {
  echo "Password match";
}
?>

🚀 Advanced PHP

<?php
// Namespaces
namespace MyApp;

class Utils {
  static function hello() {
    return "Hello World";
  }
}

// Anonymous Functions
$square = function($n) { return $n * $n; };
echo $square(5);

// Type Declarations
function add(int $a, int $b): int {
  return $a + $b;
}

// JSON Handling
$data = ["name" => "Alice", "age" => 25];
$json = json_encode($data);
echo $json;

// Composer Autoload (PSR-4)
// composer.json
{
  "autoload": {
    "psr-4": { "App\\": "src/" }
  }
}
?>

🛠️ Sessions & Cookies

<?php
// Start Session
session_start();

// Set Session
$_SESSION['user'] = "Alice";

// Get Session
echo $_SESSION['user'];

// Destroy Session
session_unset();
session_destroy();

// Cookies
setcookie("username", "Alice", time() + 3600, "/");

// Read Cookie
if(isset($_COOKIE['username'])) {
  echo $_COOKIE['username'];
}
?>

📂 File Handling

<?php
// Write File
$file = fopen("data.txt", "w");
fwrite($file, "Hello World!");
fclose($file);

// Read File
$file = fopen("data.txt", "r");
echo fread($file, filesize("data.txt"));
fclose($file);

// File Upload
if (isset($_FILES['file'])) {
  $target = "uploads/" . basename($_FILES['file']['name']);
  if(move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
    echo "File uploaded!";
  }
}
?>

<form method="POST" enctype="multipart/form-data">
  <input type="file" name="file">
  <button type="submit">Upload</button>
</form>

📧 Sending Email

<?php
$to = "user@example.com";
$subject = "Welcome!";
$message = "Thanks for joining MaxonCodes!";
$headers = "From: admin@maxoncodes.com";

if(mail($to, $subject, $message, $headers)) {
  echo "Email sent!";
} else {
  echo "Email failed!";
}
?>

🌐 APIs (cURL)

<?php
// cURL GET Request
$ch = curl_init("https://jsonplaceholder.typicode.com/posts/1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
echo $data['title'];

// cURL POST Request
$ch = curl_init("https://jsonplaceholder.typicode.com/posts");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
  'title' => 'MaxonCodes',
  'body' => 'Learning PHP APIs',
  'userId' => 1
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

🔄 JSON Handling

<?php
// Encode
$user = ["name" => "Alice", "age" => 25];
$json = json_encode($user);
echo $json;

// Decode
$data = '{"name":"Bob","age":30}';
$obj = json_decode($data);
echo $obj->name; // Bob
?>

⚠️ Error Handling

<?php
// Try-Catch
try {
  $pdo = new PDO("mysql:host=localhost;dbname=wrongdb", "root", "");
} catch (PDOException $e) {
  echo "Error: " . $e->getMessage();
}

// Custom Error Handler
function customError($errno, $errstr) {
  echo "Error [$errno]: $errstr";
}
set_error_handler("customError");

echo $undefinedVar; // triggers custom error
?>

💻 CLI (Command Line PHP)

# Run PHP script from CLI
php script.php

# Read arguments
<?php
echo $argv[1]; // first argument
?>

# Example: php script.php hello
# Output: hello

🛣️ Laravel Routes

// Basic Route
Route::get('/hello', function () {
    return "Hello Laravel!";
});

// Route with Controller
Route::get('/users', [UserController::class, 'index']);

// Route with Params
Route::get('/user/{id}', function ($id) {
    return "User ID: " . $id;
});

// Named Route
Route::get('/profile', [UserController::class, 'profile'])
     ->name('user.profile');

🧑‍💻 Controllers

// Create Controller
php artisan make:controller UserController

// Example Controller
class UserController extends Controller {
    public function index() {
        return User::all();
    }
}

📦 Models & Migrations

// Create Model + Migration
php artisan make:model Post -m

// Migration Example
Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->timestamps();
});

// Eloquent Example
Post::create(['title' => 'Hello', 'content' => 'Laravel!']);
$posts = Post::where('title', 'Hello')->get();

🔑 Authentication

// Laravel Breeze (Simple Auth)
composer require laravel/breeze --dev
php artisan breeze:install

// Socialite (Google, GitHub, Facebook)
composer require laravel/socialite

// Example in Controller
use Laravel\Socialite\Facades\Socialite;

public function redirectToGoogle() {
    return Socialite::driver('google')->redirect();
}

public function handleGoogleCallback() {
    $user = Socialite::driver('google')->user();
    // Save user to DB
}

🌐 API Routes & JSON

// api.php
Route::get('/posts', [PostController::class, 'index']);

// Controller
public function index() {
    return response()->json(Post::all());
}

// API Resource
php artisan make:resource PostResource

// Example Resource
class PostResource extends JsonResource {
    public function toArray($request) {
        return [
            'id' => $this->id,
            'title' => $this->title,
        ];
    }
}

🛡️ Middleware

// Create Middleware
php artisan make:middleware CheckAdmin

// Example
public function handle($request, Closure $next) {
    if(auth()->user()->role !== 'admin') {
        return redirect('/');
    }
    return $next($request);
}

// Register in Kernel.php
protected $routeMiddleware = [
    'admin' => \App\Http\Middleware\CheckAdmin::class,
];

// Use in Routes
Route::get('/admin', fn() => 'Admin Page')->middleware('admin');

📬 Queues & Jobs

// Create Job
php artisan make:job SendEmailJob

// Example Job
class SendEmailJob implements ShouldQueue {
    public function handle() {
        Mail::to("user@example.com")->send(new WelcomeMail());
    }
}

// Dispatch Job
SendEmailJob::dispatch();

💡 Pro Tips

// Debugging
dd($variable); // Dump & Die
dump($variable); // Dump

// Artisan Shortcuts
php artisan tinker  // interactive shell
php artisan migrate:fresh --seed // reset DB

// Caching
php artisan config:cache
php artisan route:cache

// Hashing with Argon2 (your project setup)
use Illuminate\Support\Facades\Hash;
$password = Hash::make('secret', ['memory' => 1024, 'time' => 2, 'threads' => 2]);

إرسال تعليق