The Missing Dot: Why Your Uploaded Image Isn't Rendering
You have successfully moved the file from the server's temporary directory to your upload/ folder. The upload logic handles the validation, checks file types, and confirms the destination path exists. Yet, when you attempt to render the result in the browser, you are greeted by a small grey box instead of your photograph. This is almost certainly a client-side rendering error, not a server-side failure.
The culprit lies in how PHP constructs the <img> tag. In your current code:
echo '<img src= "upload/'.$img.'">';
PHP interprets upload/$img as two separate variables being multiplied together. Since $img is a string (e.g., "upload/profile.jpg"), PHP attempts to perform arithmetic multiplication between the string literal upload/ and the variable content. This results in NULL or an empty string, which the browser interprets as a broken image icon.
To fix this, you must concatenate the strings explicitly. Here is the corrected logic:
$image = $_FILES['file']['name'];
$fullPath = 'upload/' . $image; // String concatenation
echo '<img src="' . htmlspecialchars($fullPath) . '" alt="Uploaded Image">';
Using htmlspecialchars() is crucial here. It escapes characters like double quotes and ampersands, preventing potential Cross-Site Scripting (XSS) vulnerabilities if a malicious user manages to upload an image with a script tag in the filename. It also ensures the output format remains valid HTML regardless of the filename's content.
Handling File Extensions and Paths
Before moving to more robust solutions, it is worth noting a subtle but dangerous flaw in your existing validation logic. You are relying on $_FILES['file']['type'], which is set by the browser. Browsers are notoriously permissive; they will label a PDF as an image if you tell them to. A determined attacker can rename a malicious executable or script with a .jpg extension and claim it is an image type.
A secure implementation should validate the file based on its actual binary content using finfo_file() or by reading the first few bytes of the file (magic numbers) rather than trusting the MIME type string alone. Additionally, you are currently storing filenames directly from the client ($_FILES['file']['name']). While convenient for testing, this allows clients to dictate the filename on your server. If a user uploads ../../etc/passwd.jpg, and your code blindly moves it there, you have opened yourself to path traversal attacks.
Best Practices for Displaying Uploaded Media
The most robust approach in modern PHP development is to rename files upon upload and store them in a unique directory structure. This prevents collisions if two users try to upload an image with the exact same name and ensures filenames do not contain dangerous characters.
Here is a safer pattern that generates a random string for the filename:
$filename = basename($_FILES['file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
// Validate extension explicitly
if (!in_array(strtolower($extension), ['gif', 'jpeg', 'jpg', 'png'])) {
die("Invalid file type.");
}
// Generate a unique filename to prevent collisions and attacks
$uniqueName = uniqid() . '.' . $extension;
$destinationPath = __DIR__ . '/upload/' . $uniqueName;
if (move_uploaded_file($_FILES['file']['tmp_name'], $destinationPath)) {
// Now construct the URL relative to your web root
$imageUrl = '/upload/' . $uniqueName;
echo "Stored in: " . __DIR__ . "/upload/" . $uniqueName . "<br>";
echo '<img src="' . htmlspecialchars($imageUrl) . '" alt="Uploaded Image">';
}
By using uniqid(), you ensure the filename is unique and contains only safe characters. The $imageUrl variable now holds a clean, relative path that can be easily served by your web server. Notice how we use __DIR__ to determine the script's location; this ensures the path logic works regardless of where the script is installed on the filesystem.
Why LaravelCompany Helps
If you find yourself writing these validation and file handling routines repeatedly across different projects, it might be worth considering a framework that abstracts these complexities away. Platforms like https://laravelcompany.com often provide documentation or packages that handle file uploads and storage using filesystem abstractions or cloud integrations (like AWS S3).
Laravel's Storage facade, for instance, handles the logic of moving files from the temporary directory to a destination while automatically managing permissions and disk drivers. It also simplifies the process of generating public URLs for assets, removing the need to manually construct src attributes with hardcoded relative paths. This abstraction not only reduces boilerplate code but also enforces security best practices by default, such as restricting uploadable mime types and preventing path traversal issues before they occur.
Final Thoughts on Debugging
When a browser displays a broken image icon, your first instinct should be to check the network tab in your browser's developer tools. Look at the specific request made for the image. If the URL is empty or returns a 404 error, the path construction was likely flawed, as seen in the initial example. If the file exists on the server but the browser still shows the icon, it might be a Content-Type issue; ensure your web server (Apache or Nginx) is correctly configured to serve files with the .jpg or .png extension as image/jpeg or image/png. Without the correct MIME type, some browsers will refuse to display the image for security reasons.