如何使用PHP实现E-pos热敏打印机自动打印订单收据(无需点击打印按钮)
Hey there! Let’s break down how to auto-print and batch print order receipts with an E-pos thermal printer using PHP. I’ve tackled similar scenarios for retail and food service systems before, so here’s what works in real-world setups:
PHP is a backend language, so it can’t directly control client-side printers out of the box. We’ll split this into two common use cases: auto-printing for web-based order confirmations (no click needed from staff) and batch printing from a backend system.
1. No-Click Auto-Print (Web Client Scenario)
This is for when a customer submits an order, and you want the receipt to print automatically on a connected thermal printer (e.g., at a restaurant counter). The trick is using PHP to generate the receipt content, then JavaScript to trigger the browser’s print function without user input.
Step-by-Step Implementation
First, create a PHP page that generates a receipt formatted for your thermal printer (most use 80mm width, so we’ll style accordingly):
<?php // Fetch order data from your database (example data here) $order = [ 'order_id' => 'ORD-2024-0042', 'customer' => 'Jane Smith', 'items' => [ ['name' => 'Matcha Latte', 'qty' => 1, 'price' => 6.49], ['name' => 'Vegan Muffin', 'qty' => 2, 'price' => 3.99] ], 'total' => 14.47, 'date' => date('Y-m-d H:i:s') ]; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Auto-Print Receipt</title> <style> /* 80mm thermal paper friendly styles */ body { width: 200px; font-family: monospace; margin: 0 auto; padding: 10px; font-size: 12px; } .center { text-align: center; } .bold { font-weight: bold; } .divider { border-top: 1px dashed #000; margin: 5px 0; } </style> <script> // Auto-trigger print when page loads window.addEventListener('load', function() { window.print(); // Optional: Close the tab after printing (works in most browsers) setTimeout(() => window.close(), 1500); }); </script> </head> <body> <div class="center bold">GREEN BREW CAFE</div> <div class="center">456 Oak Ave, Downtown</div> <div class="center">Phone: 987-654-3210</div> <div class="divider"></div> <div>Order ID: <?php echo $order['order_id']; ?></div> <div>Date: <?php echo $order['date']; ?></div> <div>Customer: <?php echo $order['customer']; ?></div> <div class="divider"></div> <div>Items:</div> <?php foreach($order['items'] as $item): ?> <div><?php echo $item['qty']; ?>x <?php echo $item['name']; ?> - $<?php echo number_format($item['price'], 2); ?></div> <?php endforeach; ?> <div class="divider"></div> <div class="bold">Total: $<?php echo number_format($order['total'], 2); ?></div> <div class="center bold">Thanks for visiting!</div> </body> </html>
How to Use This
- Redirect users (or staff) to this page right after an order is confirmed.
- Note: Modern browsers block unprompted auto-print first time around. Ask staff to click "Allow" when the print permission pop-up appears—after that, the browser will let auto-print run for your site.
2. Batch Print Order Receipts (Backend/Server Scenario)
For bulk printing (e.g., end-of-day reconciliation, printing 10+ orders at once), you’ll want to print directly from the server (or a dedicated print workstation) instead of relying on a browser. Here are two reliable methods:
Method 1: Use System Commands (Simple, No Libraries)
If your server/workstation has the thermal printer installed locally, you can generate a plain-text receipt and call the OS’s print command via PHP.
<?php // Fetch batch of orders from database $orders = [ ['order_id' => 'ORD-2024-0039', 'customer' => 'Bob Brown', ...], ['order_id' => 'ORD-2024-0040', 'customer' => 'Alice Lee', ...] ]; // Loop through each order to print foreach($orders as $order) { // Generate plain-text receipt (works best for thermal printers) $receipt = "GREEN BREW CAFE\n"; $receipt .= "456 Oak Ave, Downtown\n"; $receipt .= "Phone: 987-654-3210\n"; $receipt .= "------------------------\n"; $receipt .= "Order ID: {$order['order_id']}\n"; $receipt .= "Date: {$order['date']}\n"; $receipt .= "Customer: {$order['customer']}\n"; $receipt .= "------------------------\n"; foreach($order['items'] as $item) { $receipt .= "{$item['qty']}x {$item['name']} - $" . number_format($item['price'], 2) . "\n"; } $receipt .= "------------------------\n"; $receipt .= "Total: $" . number_format($order['total'], 2) . "\n"; $receipt .= "Thanks!\n\n"; // Add blank lines between orders // Save to a temporary file $tempFile = tempnam(sys_get_temp_dir(), 'receipt_'); file_put_contents($tempFile, $receipt); // Trigger system print command (Windows example) $printerName = "E-pos Thermal Printer"; // Use your printer's exact name exec("print /D:\"{$printerName}\" {$tempFile}"); // Clean up temp file unlink($tempFile); } ?>
- Linux/Mac: Replace the
execline withexec("lp -d \"{$printerName}\" {$tempFile}"). - Permissions: Ensure PHP has permission to execute system commands (adjust
php.inior server settings if needed).
Method 2: Use a Thermal Printer Library (Advanced Control)
For more precise control (bold text, alignment, barcode support), use the mike42/escpos-php library, which supports ESC/POS commands (standard for most E-pos printers).
First install the library via Composer:
composer require mike42/escpos-php
Then batch print with full control:
<?php require 'vendor/autoload.php'; use Mike42\Escpos\PrintConnectors\WindowsPrintConnector; use Mike42\Escpos\Printer; // Connect to your printer $printerName = "E-pos Thermal Printer"; $connector = new WindowsPrintConnector($printerName); $printer = new Printer($connector); // Fetch batch orders $orders = [/* Your order data here */]; foreach($orders as $order) { try { // Header (centered, bold) $printer->setJustification(Printer::JUSTIFY_CENTER); $printer->selectPrintMode(Printer::MODE_BOLD); $printer->text("GREEN BREW CAFE\n"); $printer->selectPrintMode(); // Reset to normal $printer->text("456 Oak Ave, Downtown\n"); $printer->text("Phone: 987-654-3210\n"); $printer->feed(); // Order details (left-aligned) $printer->setJustification(Printer::JUSTIFY_LEFT); $printer->text("Order ID: {$order['order_id']}\n"); $printer->text("Date: {$order['date']}\n"); $printer->text("Customer: {$order['customer']}\n"); $printer->feed(); // Items $printer->text("Items:\n"); foreach($order['items'] as $item) { $printer->text("{$item['qty']}x {$item['name']} - $" . number_format($item['price'], 2) . "\n"); } $printer->feed(); // Total (right-aligned) $printer->setJustification(Printer::JUSTIFY_RIGHT); $printer->selectPrintMode(Printer::MODE_BOLD); $printer->text("Total: $" . number_format($order['total'], 2) . "\n"); $printer->selectPrintMode(); $printer->feed(); // Footer (centered) $printer->setJustification(Printer::JUSTIFY_CENTER); $printer->text("Thanks for visiting!\n"); $printer->feed(3); // Add 3 blank lines between receipts } catch (Exception $e) { echo "Failed to print order {$order['order_id']}: " . $e->getMessage() . "\n"; } } // Close the printer connection $printer->close(); ?>
Key Notes to Avoid Headaches
- Browser Permissions: For auto-print, users must allow print access to your site first—this is a browser security rule you can’t bypass.
- Printer Compatibility: Ensure your thermal printer supports ESC/POS if using the library (most budget E-pos printers do).
- Batch Performance: For large batches, run the script as a background cron job instead of via a web request to avoid timeouts.
内容的提问来源于stack exchange,提问作者Priyanka nahar

