Employee Attendance Controller Documentation
File: /controllers/employeeAttendance.php
Purpose: Handles real-time employee attendance tracking with biometric integration and photo capture
Last Updated: December 20, 2024
Total Functions: 4+
Lines of Code: ~417
---
๐ Overview
The Employee Attendance Controller is a real-time attendance tracking system that provides biometric-enabled employee check-in/check-out functionality. It handles:
- โข Real-time attendance recording via webcam photo capture
- โข Biometric integration (fingerprint and RFID)
- โข Daily attendance history management
- โข Image processing with timestamp watermarking
- โข Cross-origin API support for external devices
- โข Automated daily attendance initialization
- โข Employee attendance reporting with filtering
- โข JSON API responses for mobile/external systems
Primary Functions
- โ Real-time attendance capture with photo verification
- โ Biometric authentication (fingerprint/RFID)
- โ Daily attendance history tracking
- โ Image watermarking with timestamps
- โ Cross-origin API compatibility
- โ Automated daily attendance setup
- โ Attendance report generation
- โ Transaction-safe operations
- โ Employee group status tracking
- โ Branch-based filtering
Related Controllers
- โข employeeAttendanceSystems.php - Attendance system configuration
- โข EmployeeAttendanceExcelController.php - Excel import/export
- โข employeePersonalajex.php - Employee personal operations
- โข employeeController.php - Employee management
---
๐๏ธ Database Tables
Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **employeeattendance** | Individual attendance logs | employeeattendanceid, empid, theImage, sysdate, fingerid, rfid, accessType, syncToServer | |
| **employeeclosedayhistory** | Daily attendance summaries | id, employeeid, day, attendanceTime, departureTime, isAbsent, absentHasPermission, status | |
| **employee** | Employee master data | employeeId, empCode, employeeName, employeesubgroupid, employeegroupid, branchid |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **employeesubgroup** | Employee sub-group organization | employeesubgroupid, name, employeegroupid | |
| **employeegroup** | Employee group organization | employeegroupid, name | |
| **employeeclosedaygroupstatus** | Group closure tracking | day, employeegroupid, status | |
| **employeeclosedaysubgroupstatus** | Sub-group closure tracking | day, employeesubgroupid, status | |
| **employeeclosedaystatus** | Daily closure status | day, status |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **youtubelink** | Tutorial links | youtubelinkid, title, url | |
| **user** | System users | userid, username |
๐ Key Functions
1. Default Action / add() - Real-Time Attendance Recording
Location: Line 134
Purpose: Record employee attendance via webcam with photo capture and timestamp watermarking
Function Signature:
// Triggered when: do=add or empty $do
$empid = (int) filter_input(INPUT_GET, 'empid');
$testdate = $_GET['testdate']; // Optional test mode
Process Flow:
1. Initialize daily attendance records if first of day
2. Capture and process webcam image
3. Add timestamp watermark to image
4. Record attendance log in database
5. Update daily attendance history
6. Return JSON response with success/failure
Key Features:
- โข Photo Verification: Saves webcam capture with timestamp
- โข Image Processing: Adds date/time watermark using GD library
- โข Transaction Safety: Rollback on any failure
- โข Cross-Origin Support: CORS headers for API access
- โข Daily Initialization: Auto-creates daily attendance records
Image Processing Code:
$filename = time() . '.jpg';
$filepath = '../upload/employeeAttendance/';
move_uploaded_file($_FILES['webcam']['tmp_name'], $filepath . $filename);
$img = imagecreatefromjpeg($filepath . $filename);
$white = imagecolorallocate($img, 255, 0, 255);
$txt = $sysdate;
$font = "arial.ttf";
imagettftext($img, 24, 0, 5, 24, $white, $font, $txt);
imagejpeg($img, $filepath . $filename, 100);
imagedestroy($img);
---
2. saveaccesslog() - Biometric Attendance Recording
Location: Line 267
Purpose: Process bulk attendance logs from biometric devices (fingerprint/RFID)
Function Signature:
// Triggered when: do=saveaccesslog
$accessLogArr = json_decode($_POST['data_arr']);
Process Flow:
1. Parse JSON array of attendance logs
2. For each log:
- Identify employee by fingerprint ID or RFID
- Process base64 image if provided
- Add timestamp watermark to image
- Record attendance in database
- Update daily history
3. Return comma-separated list of processed IDs
Biometric Integration:
if ($log->accessType == 0) { // Fingerprint
$empid = (int) $employeeEX->getEmpIdWithFingerId($log->fingerid);
} else { // RFID
$empid = (int) $employeeEX->getEmpIdWithRFID($log->rfid);
}
Image Processing for Base64:
$success = file_put_contents($filepath . $filename, base64_decode($log->theImage_base64));
$img = imagecreatefrompng($filepath . $filename);
// Add watermark and save
imagepng($img, $filepath . $filename, 0);
---
3. attendanceReport() - Attendance Report Generation
Location: Line 372
Purpose: Generate filtered attendance reports with employee and date filtering
Function Signature:
// Triggered when: do=attendanceReport
$empid = (int) filter_input(INPUT_POST, 'empid');
$from = filter_input(INPUT_POST, 'from');
$to = filter_input(INPUT_POST, 'to');
Process Flow:
1. Load all employees for dropdown (branch filtered)
2. Build query string with filters:
- Employee ID filter
- Date range filter
- Branch filter if applicable
3. Query attendance records
4. Load YouTube tutorial links
5. Display via Smarty template
Query Building:
if ($_SESSION['branchId'] > 0)
$queryString .= ' AND branchid = ' . $_SESSION['branchId'];
if ($empid > 0) {
$queryString .= " and empid = $empid ";
}
if ($from != '') {
$queryString .= " and date(employeeattendance.sysdate) >= '" . $from . "' ";
}
if ($to != '') {
$queryString .= " and date(employeeattendance.sysdate) <= '" . $to . "' ";
}
---
4. Daily Attendance Initialization - Automated Setup
Location: Lines 143-145, 288-290
Purpose: Automatically create daily attendance records for all active employees
Function Logic:
if ((int) $employeeCloseDayHistoryEX->dayAttendanceCount($day) == 0) {
$employeeCloseDayHistoryEX->beginDayAttendance($day, $sysdate, 1);
}
Features:
- โข Runs on first attendance of each day
- โข Creates records for all active employees
- โข Prevents duplicate daily records
- โข Initializes attendance/departure times to "00:00:00"
---
๐ Workflows
Workflow 1: Real-Time Attendance Capture
---
Workflow 2: Biometric Device Integration
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (empty) or `do=add` | Default action | Real-time attendance capture | |
| `do=saveaccesslog` | `saveaccesslog()` | Biometric device data sync | |
| `do=attendanceReport` | `attendanceReport()` | Generate attendance reports |
Real-Time Attendance (do=add):
- โข
empid- Employee ID (integer) - โข
webcam- Uploaded image file ($_FILES) - โข
testdate- Optional: Override system date for testing
Biometric Sync (do=saveaccesslog):
- โข
data_arr- JSON array of attendance logs (POST)
Attendance Report (do=attendanceReport):
- โข
empid- Employee ID filter (optional, 0 = all) - โข
from- Start date filter (optional) - โข
to- End date filter (optional)
---
๐งฎ Calculation Methods
Attendance Time Logic
// Determine if this is arrival or departure
if ($employeeCloseDayHistory->attendanceTime == "00:00:00") {
$employeeCloseDayHistory->attendanceTime = $time; // First check-in
} else {
$employeeCloseDayHistory->departureTime = $time; // Check-out
}
Image Filename Generation
$filename = time() . '.jpg'; // Unique timestamp-based filename
$filepath = '../upload/employeeAttendance/';
Biometric Employee Lookup
// Fingerprint lookup
$empid = (int) $employeeEX->getEmpIdWithFingerId($log->fingerid);
// RFID lookup
$empid = (int) $employeeEX->getEmpIdWithRFID($log->rfid);
---
๐ Security & Permissions
API Security
- โข CORS Headers: Allows cross-origin requests for mobile/device integration
- โข Input Filtering: Uses
filter_input()for parameter validation - โข Transaction Safety: Database rollback on any failure
File Upload Security
- โข Restricted Extensions: Only .jpg images allowed for webcam
- โข Unique Filenames: Timestamp-based to prevent collisions
- โข Directory Isolation: Files stored in dedicated upload folder
Authentication
- โข Session Required: User must be logged in for attendance reports
- โข Branch Filtering: Attendance data filtered by user's branch access
---
๐ Performance Considerations
Image Processing Optimization
1. File Size: Images compressed with quality=100 for JPEG, 0 for PNG
2. Memory Management: imagedestroy() called to free memory
3. File Cleanup: No automatic cleanup of old attendance images
Database Optimization
1. Batch Operations: saveaccesslog() processes multiple records in single transaction
2. Efficient Queries: Direct employee lookups by fingerprint/RFID
3. Index Requirements:
- employeeattendance(empid, sysdate)
- employeeclosedayhistory(employeeid, day)
- employee(employeeId, conditions)
Known Performance Issues
- โข Daily Initialization: First attendance of day creates records for ALL employees
- โข Image Storage: No automatic cleanup of attendance photos
- โข No Pagination: Attendance reports load all matching records
---
๐ Common Issues & Troubleshooting
1. Image Upload Failures
Issue: Webcam upload fails or images not processed
Causes:
- โข Missing upload directory permissions
- โข PHP upload_max_filesize too small
- โข GD library not installed
Debug:
// Check upload errors
if ($_FILES['webcam']['error'] != UPLOAD_ERR_OK) {
echo "Upload error: " . $_FILES['webcam']['error'];
}
// Verify GD library
if (!extension_loaded('gd')) {
echo "GD library not installed";
}
2. Biometric Device Not Syncing
Issue: saveaccesslog returns -1 or no success IDs
Causes:
- โข Invalid JSON in
data_arr - โข Employee not found by fingerprint/RFID
- โข Database transaction failure
Debug:
$accessLogArr = json_decode($_POST['data_arr']);
if (json_last_error() != JSON_ERROR_NONE) {
echo "JSON decode error: " . json_last_error_msg();
}
3. Daily Records Not Initialized
Issue: Attendance recording fails because no daily record exists
Cause: beginDayAttendance() function failed
Fix:
-- Manual daily record creation
INSERT INTO employeeclosedayhistory (employeeid, day, attendanceTime, departureTime, isAbsent, del)
SELECT employeeId, CURDATE(), '00:00:00', '00:00:00', 1, 0
FROM employee
WHERE conditions = 0;
4. CORS Issues with External Devices
Issue: Browser blocks cross-origin requests
Fix: Verify headers are set correctly:
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
---
๐งช Testing Scenarios
Test Case 1: Manual Attendance Recording
1. Access: ?do=add&empid=1
2. Upload webcam image via form
3. Verify image saved with timestamp watermark
4. Check database record created
5. Confirm JSON response indicates success
6. Test second attendance (departure) for same employee/day
Test Case 2: Biometric Device Integration
1. Prepare JSON payload with attendance logs
2. POST to ?do=saveaccesslog
3. Verify employee identification by fingerprint/RFID
4. Check image processing from base64
5. Confirm batch processing of multiple logs
6. Validate returned success ID list
Test Case 3: Daily Initialization
1. Ensure no daily records exist for test date
2. Record first attendance of day
3. Verify all employee daily records created
4. Check attendance/departure times set to "00:00:00"
5. Confirm specific employee record updated correctly
Test Case 4: Attendance Report
1. Create test attendance data for multiple employees/dates
2. Access report with no filters
3. Test employee-specific filtering
4. Test date range filtering
5. Verify branch filtering applies correctly
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข employeeAttendanceSystems.md - Attendance system configuration
- โข EmployeeAttendanceExcelController.md - Excel integration
- โข employeeController.md - Employee management
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When major changes occur