TL;DR
This guide shows how attackers can bypass file upload restrictions on a PHP server and what you can do to prevent it.
Understanding the Problem
PHP applications often allow users to upload files. Poorly implemented security checks can let attackers upload malicious files (like web shells) disguised as legitimate ones, leading to cyber security breaches.
Common Bypass Techniques & Prevention
- Filename Manipulation
- Technique: Attackers change the filename extension. For example, uploading
evil.phpasevil.php.jpgorevil.jpg.php. Some servers only check the last few characters of the filename. - Prevention: Never rely on client-side validation (JavaScript). Use server-side checks to verify the file extension against a strict whitelist of allowed extensions. Also, remove any extra extensions. For example:
- Content-Type Manipulation
- Technique: Attackers change the
Content-Typeheader in the HTTP request. For example, sending a PHP script withContent-Type: image/jpeg. - Prevention: Don’t rely on the
Content-Typeheader sent by the client. Use functions likemime_content_type()to detect the file type based on its content, *after* you have already validated the extension. - Null Byte Injection (Older PHP versions)
- Technique: Attackers insert a null byte (%00) into the filename. For example,
evil.php%00.jpg. This can trick some older PHP versions into ignoring everything after the null byte. This is less common now due to updated PHP versions and configurations. - Prevention: Use modern PHP versions (8.x recommended). Sanitize filenames by removing null bytes:
- Double Extension Bypass
- Technique: Uploading a file with multiple extensions, hoping the server only checks for one. For example,
evil.php.jpg.png. - Prevention: Use more robust extension checking logic that handles multiple dots and ensures only allowed extensions are present.
- Polyglot Files
- Technique: Creating a file that is valid in multiple formats. For example, a PHP script that also happens to be a valid JPEG image.
- Prevention: This is the hardest to prevent. Thoroughly validate the file content using dedicated libraries for each allowed type. Consider using a more secure upload library or service.
Additional Security Measures
- Random Filenames: Rename uploaded files to random, unique names. This prevents attackers from predicting the filename and accessing it directly.
- Store Files Outside Web Root: Store uploaded files in a directory that is not accessible directly through the web server. Use scripts to serve the files securely.
- Permissions: Set strict file permissions on the upload directory to prevent execution of uploaded scripts.
- File Size Limits: Limit the maximum allowed file size to prevent denial-of-service attacks and large malicious uploads.
- Regular Scanning: Regularly scan the upload directory for suspicious files using an antivirus or malware scanner.

