logoalt Hacker News

calvinmorrison01/21/20251 replyview on HN

<?php

// Hardcoded token for authentication $authToken = 'your-secure-token-here';

// Set the printer name (adjust to your printer's name) $printerName = 'YourPrinterName';

// Allow only POST requests if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['error' => 'Method not allowed. Use POST.']); exit; }

// Check for token in the request if (empty($_POST['token']) || $_POST['token'] !== $authToken) { http_response_code(401); echo json_encode(['error' => 'Unauthorized: Invalid token.']); exit; }

// Check if a file was uploaded if (empty($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) { http_response_code(400); echo json_encode(['error' => 'No file uploaded or file upload error.']); exit; }

// Get the uploaded file path $uploadedFile = $_FILES['file']['tmp_name']; $fileName = basename($_FILES['file']['name']);

// Use lp command to print the file $command = escapeshellcmd("lp -d " . escapeshellarg($printerName) . " " . escapeshellarg($uploadedFile)); exec($command, $output, $status);

// Check the status of the command if ($status === 0) { http_response_code(200); echo json_encode(['success' => "File '$fileName' sent to printer '$printerName'."]); } else { http_response_code(500); echo json_encode(['error' => 'Failed to print the file.']); }


Replies

corytheboyd01/21/2025

I don’t think you can just send any document to a thermal printer and have it come out usable… there’s definitely value in software that can _convert_ arbitrary data to whatever format/dimensions/etc the thermal printer needs. Like the post mentions automatic dithering of images. Stuff like that. The HTTP glue is not the hard part.