Last updated: August 25, 2026.
PDF files store positioned page content rather than ordinary paragraphs. For searchable PDFs, a command-line extractor such as Poppler’s pdftotext is a dependable way to obtain text from PHP. Scanned PDFs require OCR instead.
Run pdftotext safely from PHP
Install Poppler on the server, keep uploaded files outside the public web root, and pass the command as an argument array so a filename is never interpreted by a shell.
<?php
declare(strict_types=1);
function extractPdfText(string $pdfPath): string
{
if (!is_file($pdfPath)) {
throw new InvalidArgumentException('PDF file not found.');
}
$command = ['pdftotext', '-layout', '-enc', 'UTF-8', $pdfPath, '-'];
$pipes = [];
$process = proc_open($command, [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
], $pipes);
if (!is_resource($process)) {
throw new RuntimeException('Could not start pdftotext.');
}
fclose($pipes[0]);
$text = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
if (proc_close($process) !== 0) {
throw new RuntimeException(trim($error) ?: 'PDF extraction failed.');
}
return trim((string) $text);
}Practical checks
- Validate the upload size and MIME type before processing.
- Use a timeout and job queue for large documents.
- Do not expect reading order to be perfect in multi-column layouts.
- Use OCR for image-only pages, then review the output for recognition errors.
- Delete temporary files after processing and restrict access to extracted text.
See the Poppler project for the PDF utilities used by this approach.