Overview
Upload validation with size limits, Fileinfo MIME detection and random filenames.
What this script does
This starter demonstrates the core implementation pattern. Adapt database fields, configuration and error handling to your application.
Source code
<?php
declare(strict_types=1);
function storeUpload(array $file,string $privateDir): string {
$allowed=['image/jpeg'=>'jpg','image/png'=>'png','application/pdf'=>'pdf'];
if (($file['error']??UPLOAD_ERR_NO_FILE)!==UPLOAD_ERR_OK || ($file['size']??0)<1 || $file['size']>5*1024*1024) {
throw new RuntimeException('Upload error or size limit exceeded.');
}
$tmp=(string)$file['tmp_name'];
if (!is_uploaded_file($tmp)) throw new RuntimeException('Invalid upload source.');
$mime=(new finfo(FILEINFO_MIME_TYPE))->file($tmp);
if (!isset($allowed[$mime])) throw new RuntimeException('File type not allowed.');
if (!is_dir($privateDir) && !mkdir($privateDir,0700,true)) throw new RuntimeException('Storage unavailable.');
$name=bin2hex(random_bytes(16)).'.'.$allowed[$mime];
if (!move_uploaded_file($tmp,rtrim($privateDir,'/').'/'.$name)) throw new RuntimeException('Cannot store file.');
return $name;
}
Download starter source: Download Secure PHP File Upload Starter source
Installation and customization
- Review the code and required PHP extensions.
- Configure database and storage settings outside the public web root where applicable.
- Add authorization, rate limiting and logging for public-facing endpoints.
- Test valid, invalid and boundary inputs before deployment.
> This is a learning starter, not a complete production application. Apply the security and deployment requirements of your project.