惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
G
Google Developers Blog
aimingoo的专栏
aimingoo的专栏
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
小众软件
小众软件
Stack Overflow Blog
Stack Overflow Blog
美团技术团队
博客园_首页
T
Tailwind CSS Blog
博客园 - 三生石上(FineUI控件)
B
Blog
D
DataBreaches.Net
腾讯CDC
C
Check Point Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
U
Unit 42
月光博客
月光博客
V
V2EX
Vercel News
Vercel News
T
The Blog of Author Tim Ferriss
The Cloudflare Blog
博客园 - 叶小钗
Y
Y Combinator Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Develop a Pure PHP Face Recognition Application
Arshid · 2026-04-28 · via DEV Community

Face recognition isn’t just for Python or complex AI stacks anymore. You can now implement it in PHP to create efficient web-based solutions for attendance, security, and user authentication, even integrating seamlessly with Laravel or WordPress.

This guide walks you through using Dlib models in PHP to perform face detection, identify facial landmarks, and generate face embeddings.

Install the php-dlib Extension

Download the correct file from: https://github.com/mailmug/php-dlib/releases

Find php.ini, then add the extension path.

Example:

extension="/path/to/dlib.dll"

Enter fullscreen mode Exit fullscreen mode

More details: https://github.com/mailmug/php-dlib/

Create a data directory, then download the required files and extract their contents into that folder.

http://dlib.net/files/mmod_human_face_detector.dat.bz2,
http://dlib.net/files/shape_predictor_5_face_landmarks.dat.bz2, http://dlib.net/files/dlib_face_recognition_resnet_model_v1.dat.bz2

$detectionModel = "data/mmod_human_face_detector.dat";
$landmarkModel = "data/shape_predictor_5_face_landmarks.dat";
$recognitionModel = "data/dlib_face_recognition_resnet_model_v1.dat";

Enter fullscreen mode Exit fullscreen mode

Model Roles:

  • Face Detector → Finds faces in images
  • Landmark Detector → Identifies eyes, nose, and mouth positions
  • Recognition Model → Generates 128D face embeddings

PHP Face Recognition Code Explained

1. Initialize Models

$fd = new CnnFaceDetection($detectionModel);
$fld = new FaceLandmarkDetection($landmarkModel);
$fr = new FaceRecognition($recognitionModel);

Enter fullscreen mode Exit fullscreen mode

These objects load your AI models into PHP for processing images.

2. Define Known People Dataset

$people = [
  "Arshid" => "Photo-1.jpeg", //correct file path
  "Jhon"   => "Photo-2.png",
];

Enter fullscreen mode Exit fullscreen mode

This acts as your training dataset of known faces.

3. Face Detection + Processing Loop

foreach ($people as $name => $img) {
  echo "Processing: $name\n";
  $faces = $fd->detect($img);
  if (count($faces) == 0) {
     echo "No face found in $img\n";
     continue;
   }
   $face = $faces[0];

Enter fullscreen mode Exit fullscreen mode

✔ Detects faces in the image
✔ Skips images without faces
✔ Selects the first detected face

4. Facial Landmark Detection

$landmarks = $fld->detect($img, $face);

Enter fullscreen mode Exit fullscreen mode

This step improves accuracy by locating:

  • Eyes
  • Nose
  • Mouth
  • Jawline This is crucial for alignment before recognition. ### 5. Generate Face Embedding
$descriptor = $fr->computeDescriptor($img, $landmarks);

Enter fullscreen mode Exit fullscreen mode

This generates a 128-dimensional face embedding a unique numerical signature representing a person’s face. It forms the foundation of modern face recognition systems.

6. Store Face Database

// 4. store
    $database[$name] = $descriptor;

    echo "Saved: $name\n";
}

// save to file
file_put_contents("faces.db", serialize($database)); // save as file. You can store to db also

echo "Database created\n";

Enter fullscreen mode Exit fullscreen mode

Complete Enroll Code (Train to Machine)

<?php


$detectionModel  =   "data/mmod_human_face_detector.dat";
$landmarkModel   =   "data/shape_predictor_5_face_landmarks.dat";
$recognitionModel = "data/dlib_face_recognition_resnet_model_v1.dat";

$fd = new CnnFaceDetection($detectionModel);
$fld = new FaceLandmarkDetection($landmarkModel);
$fr = new FaceRecognition($recognitionModel);


$people = [
  "Arshid" => "Photo-1.jpeg",
  "Jhon"   => "Photo-2.jpg",
];

$database = [];

foreach ($people as $name => $img) {

    echo "Processing: $name\n";

    // 1. detect face first
    $faces = $fd->detect($img);

    if (count($faces) == 0) {
        echo "No face found in $img\n";
        continue;
    }

    // take first face
    $face = $faces[0];

    // 2. landmark detection (✔ needs image + face box)
    $landmarks = $fld->detect($img, $face);

    // 3. face encoding
    $descriptor = $fr->computeDescriptor($img, $landmarks);

    // 4. store
    $database[$name] = $descriptor;

    echo "Saved: $name\n";
}

// save to file
file_put_contents("faces.db", serialize($database));

echo "Database created\n";

Enter fullscreen mode Exit fullscreen mode

Understanding Face Matching: The Next Step

Later, you can compare faces using:

  • Euclidean distance
  • Cosine similarity
  • To find the closest match from faces.db.

File: recognize.php code

<?php


$detectionModel  =   "data/mmod_human_face_detector.dat";
$landmarkModel   =   "data/shape_predictor_5_face_landmarks.dat";
$recognitionModel = "data/dlib_face_recognition_resnet_model_v1.dat";

$fd = new CnnFaceDetection($detectionModel);
$fld = new FaceLandmarkDetection($landmarkModel);
$fr = new FaceRecognition($recognitionModel);

$database = unserialize(file_get_contents("faces.db"));

$image = "test.jpeg"; 

$faces = $fd->detect($image);

foreach ($faces as $face) {

    $landmarks = $fld->detect($image, $face);
    $descriptor = $fr->computeDescriptor($image, $landmarks);

    $bestName = "Unknown";
    $bestDist = 999;

    foreach ($database as $name => $dbDescriptor) {

        $dist = 0;

        for ($i = 0; $i < 128; $i++) {
            $diff = $descriptor[$i] - $dbDescriptor[$i];
            $dist += $diff * $diff;
        }

        $dist = sqrt($dist);

        if ($dist < $bestDist) {
            $bestDist = $dist;
            $bestName = $name;
        }
    }

    // threshold (important)
    if ($bestDist < 0.6) {
        echo "MATCH: $bestName (distance $bestDist)\n";
    } else {
        echo "Unknown face\n";
    }
}

Enter fullscreen mode Exit fullscreen mode

Download source code: https://ciphercoin.com/wp-content/uploads/2026/04/photo-rec.zip