The Hidden Trap in filesize() and Uploading Logic
When you encounter the warning Warning: filesize(): stat failed for img.jpg, your immediate instinct might be to assume the file doesn't exist or is corrupted. However, if you have just uploaded a file via an HTML form and are trying to validate it immediately, the issue usually lies in how PHP resolves the path relative to the current execution context versus where the file actually lives.
In the scenario described, the code attempts to retrieve the original filename from $_FILES['profile']['name']. This value is inherently dangerous for direct filesystem operations because it contains the client's chosen name, which could include special characters or be relative to a different directory structure on the server. The snippet provided attempts to sanitize this using iconv('UTF-8', 'ISO-8859-1',$path). While character set conversion is sometimes necessary for legacy systems, it does not solve the fundamental pathing issue and can inadvertently introduce new errors if the target encoding differs from what the filesystem expects.
The core problem with calling filesize($path) immediately after form submission is that $path often represents a temporary location created by PHP's default file upload handling ($_FILES['profile']['tmp_name']), or it points to a non-existent file because the script has already moved or deleted the uploaded content. If you are processing the file in a handler that expects the file to be at a specific absolute path, but $path is just a raw client name (e.g., img.jpg) without the base directory prefix, stat() fails because it cannot find a file named literally img.jpg in your current working directory.
To resolve this, you must distinguish between the original filename and the actual filesystem path. When handling uploads securely, the standard practice is to move the uploaded file from its temporary location ($_FILES['profile']['tmp_name']) to your designated upload directory using move_uploaded_file(). Only after this move should you attempt to verify properties like file size.
Here is a corrected implementation pattern that avoids the stat failed warning:
$uploadDir = dirname(__DIR__) . '/uploads/'; // Define absolute target path
$filename = $_FILES['profile']['name'];
$fileTmpName = $_FILES['profile']['tmp_name'];
$fileSize = $_FILES['profile']['size']; // Use this for initial validation
// Validate file size immediately using the temporary stream metadata
if ($fileSize > 1024 * 600) {
return "File too large";
}
$allowedExtensions = ['jpg', 'jpeg', 'png'];
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!in_array($extension, $allowedExtensions)) {
return "Invalid file type";
}
// Move the file to its final destination
$destinationPath = $uploadDir . basename($filename);
// Verify the move was successful before attempting stat on the new path
if (move_uploaded_file($fileTmpName, $destinationPath)) {
// Now filesize() will work because the file exists at $destinationPath
$finalSize = filesize($destinationPath);
} else {
return "Failed to move uploaded file";
}
There is also a subtle pitfall regarding encoding. The iconv function in your original snippet converts the string from UTF-8 to ISO-8859-1. If your server's filesystem locale is set to something other than Latin-1 (like Windows-1252 or a UTF-8 compatible locale), this conversion might strip out characters or fail silently, resulting in an invalid path that stat() cannot resolve. Always ensure the target directory path is hardcoded as an absolute string rather than relying on relative paths combined with sanitized client names.
Furthermore, relying solely on filesize() after moving a file is redundant if you have already validated $fileSize from the $_FILES array. The $_FILES['profile']['size'] attribute is provided by the web server (usually Apache or Nginx) and reflects the actual number of bytes received in the POST request. Using this value for logic gates like size limits is more efficient than re-reading the filesystem, provided you haven't already moved the file to a location where permissions might restrict access.
If you are building this for a Laravel application, consider utilizing the Uploaders trait or the built-in Storage facade. These tools abstract away the path resolution and temporary file handling, ensuring that operations like size() (which wraps stat()) are performed on valid, absolute paths managed by the framework. For more robust file handling patterns in modern PHP stacks, resources like https://laravelcompany.com offer insights into leveraging these frameworks to avoid manual filesystem pitfalls.