Code Snippets

A collection of useful code snippets and utilities I find handy. Feel free to copy and use them in your projects.

Compare Two Strings (PHP)

Case-sensitive and case-insensitive string comparison in PHP.

<?php
// Case-sensitive comparison
$str1 = "Hello";
$str2 = "hello";
if (strcmp($str1, $str2) === 0) {
    echo "Strings are equal (case-sensitive).\n";
} else {
    echo "Strings are not equal (case-sensitive).\n";
}

// Case-insensitive comparison
if (strcasecmp($str1, $str2) === 0) {
    echo "Strings are equal (case-insensitive).\n";
} else {
    echo "Strings are not equal (case-insensitive).\n";
}
?>
Debounce Function (JavaScript)

Limits the rate at which a function can fire.

function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func.apply(this, args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

// Example usage:
// const handleResize = debounce(() => {
//   console.log('Window resized');
// }, 250);
// window.addEventListener('resize', handleResize);
Upload File to S3 (Laravel)

Basic example of uploading a file to AWS S3 using Laravel's Storage facade.

<?php

use IlluminateSupportFacadesStorage;
use IlluminateHttpRequest;

public function upload(Request $request) {
    if ($request->hasFile('avatar') && $request->file('avatar')->isValid()) {
        // Store the file in the 'avatars' directory on the 's3' disk
        $path = $request->file('avatar')->store('avatars', 's3');

        // $path will contain the path to the file on S3
        // e.g., "avatars/randomfilename.jpg"

        // Optionally, make the file public
        // Storage::disk('s3')->setVisibility($path, 'public');

        // Get the full URL (if bucket is configured for public access)
        // $url = Storage::disk('s3')->url($path);

        return response()->json(['path' => $path]);
    }

    return response()->json(['error' => 'No valid file uploaded.'], 400);
}
?>
// Ensure your .env file has AWS credentials and S3 bucket configured
// FILESYSTEM_DISK=s3
// AWS_ACCESS_KEY_ID=your_key
// AWS_SECRET_ACCESS_KEY=your_secret
// AWS_DEFAULT_REGION=your_region
// AWS_BUCKET=your_bucket_name
// AWS_URL=your_s3_url (optional, for public URLs)
Validate Vietnamese Phone Number (PHP)

Regex to validate common Vietnamese mobile phone number formats.

<?php
function isValidVietnamesePhoneNumber(string $phoneNumber): bool {
    // Remove spaces and hyphens
    $phoneNumber = str_replace([' ', '-'], '', $phoneNumber);

    // Regex for common formats (e.g., 09..., 03..., 07..., 08..., 05..., +849...)
    $pattern = '/^(0|\+84)(3[2-9]|5[689]|7[06-9]|8[1-689]|9[0-46-9])\d{7}$/';

    return preg_match($pattern, $phoneNumber) === 1;
}

// Example Usage:
$phone1 = "0987654321";
$phone2 = "+84987654321";
$phone3 = "0123456789"; // Invalid prefix

var_dump(isValidVietnamesePhoneNumber($phone1)); // bool(true)
var_dump(isValidVietnamesePhoneNumber($phone2)); // bool(true)
var_dump(isValidVietnamesePhoneNumber($phone3)); // bool(false)
?>
Docker Compose (Laravel + MySQL + Redis)

Basic docker-compose.yml for a Laravel development environment.

version: '3.8'

services:
  # PHP Service (Laravel App)
  app:
    build:
      context: .
      dockerfile: Dockerfile # Assuming you have a Dockerfile for your app
    container_name: laravel_app
    restart: unless-stopped
    working_dir: /var/www/html
    volumes:
      - ./:/var/www/html
    depends_on:
      - db
      - redis
    networks:
      - laravel_network

  # Nginx Service
  nginx:
    image: nginx:alpine
    container_name: laravel_nginx
    restart: unless-stopped
    ports:
      - "8000:80" # Host port 8000 mapped to container port 80
    volumes:
      - ./:/var/www/html
      - ./docker/nginx/conf.d/:/etc/nginx/conf.d/ # Your Nginx config
    depends_on:
      - app
    networks:
      - laravel_network

  # MySQL Database Service
  db:
    image: mysql:8.0
    container_name: laravel_db
    restart: unless-stopped
    environment:
      MYSQL_DATABASE: ${DB_DATABASE:-laravel}
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD:-root}
      MYSQL_PASSWORD: ${DB_PASSWORD:-userpass}
      MYSQL_USER: ${DB_USERNAME:-user}
    volumes:
      - db_data:/var/lib/mysql
    ports:
      - "33061:3306" # Host port 33061 mapped to container port 3306
    networks:
      - laravel_network

  # Redis Service
  redis:
    image: redis:alpine
    container_name: laravel_redis
    restart: unless-stopped
    ports:
      - "63791:6379" # Host port 63791 mapped to container port 6379
    networks:
      - laravel_network

networks:
  laravel_network:
    driver: bridge

volumes:
  db_data:
    driver: local
Simple API Auth Middleware (Laravel)

Basic API token authentication middleware example.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\User; // Assuming you have a User model with an 'api_token' column

class AuthenticateApiToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->bearerToken(); // Get token from Authorization header

        if (!$token) {
            // Or from query parameter or request body as fallback
            $token = $request->input('api_token');
        }

        if (!$token) {
            return response()->json(['message' => 'Authentication token not provided.'], 401);
        }

        $user = User::where('api_token', $token)->first();

        if (!$user) {
            return response()->json(['message' => 'Invalid authentication token.'], 401);
        }

        // Authenticate the user for this request
        auth()->login($user); // Optional: if you want to use auth() helpers

        // Or simply attach user to request for stateless auth
        // $request->setUserResolver(function () use ($user) {
        //     return $user;
        // });


        return $next($request);
    }
}

// Register this middleware in app/Http/Kernel.php (e.g., in $routeMiddleware)
// protected $routeMiddleware = [
//     ...
//     'auth.api_token' => \App\Http\Middleware\AuthenticateApiToken::class,
// ];

// Apply to routes:
// Route::middleware('auth.api_token')->group(function () {
//     Route::get('/api/protected-resource', ...);
// });
?>