Paradox in File Uploading

I’m using two functions for uploading images to the server, one of which creates the folders if needed and checks the file for validity. It also checks whether the image already exists but the actual processing is being done in another function which, if needed, converts to a suitable format.

The problem is apparently to do not only with case but with the file extension being changed to match the uploaded file, which gets uploaded into up to three different places at once. One is the original file, another is the reduced and (if needed) converted image and the third is a thumbnail. I’ve tried making it all check for lower case but so far have been unable. For example, if the original is TestImage.bmp, it’s converted to testimage.png so it never matches the file being uploaded and gets overwritten! Any thoughts of where I should be looking? This has me a bit perplexed!

This is the segment of imageUpload() that checks the files but, contrary to its name, it doesn’t actually upload them.

Note that $targetFile is already set to lower case using strtolower($targetFile) and the images are uploading with lower case names.

if (!is_dir($SubPath)) :
	// CHECK IF THE UPLOAD DIRECTORY EXISTS
	// THE DIRECTORY SHOULD HAVE BEEN CREATED ABOVE
	$Error = "the image directory does not exist.";
	$uploadValid = 0;
elseif (file_exists($targetFile)) :
	// CHECK IF FILE ALREADY EXISTS
	$Error = "it already exists.";
	$uploadValid = 0;
elseif ($_FILES['UploadFile']['size'] == 0) :
	// CHECK THAT THE FILE CONTAINS DATA
	$Error = "it contains no data.";
	$uploadValid = 0;
elseif ($_FILES["UploadFile"]["size"] > $_MaxSize) :
	// CHECK IF FILE IS WITHIN MAXIMUM SIZE
	$Error = "it is too large.";
	$uploadValid = 0;
elseif (!in_array($imageFileType, $AllowedFormats)) :
	// ALLOW ONLY SPECIFIC FILE FORMATS
	$_AllowedFormats = preg_replace("/,([^,]+)$/", " & $1", $_AllowedFormats);
	$Error = "only $_AllowedFormats files are allowed.";
	$uploadValid = 0;
endif;

Instead, this function does the appropriate resizing, format conversion and uploading:

function imageResize($TargetDir, $ImageFormat, $MaxWidth, $MaxHeight) {

	$TargetFile = pathinfo($_FILES['UploadFile']['name'], PATHINFO_FILENAME);
	$TargetFile = strtolower($TargetFile);
	$imagick = new Imagick($_FILES['UploadFile']['tmp_name']);

	$imagick->setImageColorspace(imagick::COLORSPACE_SRGB);
	$imagick->setImageFormat($ImageFormat);
	$imagick->resizeImage($MaxWidth, $MaxHeight, Imagick::FILTER_LANCZOS, 1);
	$imagick->setFilename($TargetFile);

	$TargetFile = "$TargetDir{$TargetFile}.$ImageFormat";
	$imagick->writeImage($TargetFile);

	return $TargetFile;
}

The simplest way of guaranteeing that uploaded files are uniquely named, so that they cannot overwrite other uploaded files, is to generate the full filename yourself.

After you have determined that the file was successfully upload, without error, and have validated the uploaded file information, insert a row into a database table with all the who, what, when, where, and why information about the file. This will record the original filename part of the uploaded file name. If this filename must be unique across all uploaded files, you would define the column holding the filename as a unique index, then test for a unique index error (number) in the insert query exception error handling to let the user know that the filename already exists. If the query doesn’t produce an error, you would get the last insert id (autoincrement primary index) from this query and use it as part of the full filename that you use when saving the file in the file system.

I have three recommendations for the posted code -

  1. Use an array to hold user/validation errors, with the array index being the form field name or similar. This will let you validate all independent inputs separately. This will let you test at any point if there is or is not an error for any particular form field and will let you output the error messages adjacent to the fields they correspond with.
  2. With either the existing $Error string variable or an array holding user/validation errors, you don’t need a separate $uploadValid variable. You can simply test if the string variable or array is empty() or is (not) !empty() at any point.
  3. You should supply all input data to a function as call-time parameter(s). By hard-coding $_FILES[‘UploadFile’] … inside the function code, these functions are not general purpose, reusable. If you need to upload multiple files or an array of files, you would need to rewrite this code.

Thank you and it will indeed need to be rewritten to be able to handle multiple images. For now, though, one at a time is fine and, as I’m the only one using it, I tried to keep it simple. As for the file naming, it is on purpose that the names are unchanged. Each section of the site holds its images in a separate folder. For example, Classified Ads have images in /images/classifieds/5 (5 being the ad entry’s database ID) with thumbnails and originals in folders under that so each ad has its own folder that keeps it all separate. There are occasions where I actually want to overwrite the images on purpose but I have not yet gone through that part to see what it takes for a confirmation. This is all from a set or suite of working sites that I am rebuilding from the ground up, redoing what was already working due to the age of the code and its compatibility with modern PHP.

I had considered an array for the errors but, as they show in a JavaScript alert popup, it seemed that for now, using a single variable was sufficient.

I like using the Intervention library as it makes uploading images easy in my opinion.

Here’s an upload script that I use:

// Include the configuration file and autoload file from the composer.
require_once __DIR__ . '/../../config/starlite_config.php';
require_once "../vendor/autoload.php";

use Intervention\Image\ImageManagerStatic as Image;
use clearwebconcepts\ErrorHandler;
use clearwebconcepts\Database;
use clearwebconcepts\LoginRepository as Login;

$required_security_level = ['sysop'];

$host = $_SERVER['HTTP_HOST'];
$base_path = ($host === 'localhost:8888') ? '/innsoltech' : '';
$errorHandler = new ErrorHandler();
// Register the exception handler method
set_exception_handler([$errorHandler, 'handleException']);

$database = new Database();
$pdo = $database->createPDO();


$login = new Login($pdo);
// Restrict access to administrators (sysop only)
$login->enforce_security_level(['admin', 'sysop']);
$message = "";

// Directory paths for saving images
$imageDir = 'uploads/images/';
$thumbDir = 'uploads/thumbnails/';

// Ensure directories exist
if (!is_dir($imageDir)) {
    mkdir($imageDir, 0755, true);
}
if (!is_dir($thumbDir)) {
    mkdir($thumbDir, 0755, true);
}

// Set minimum dimensions for uploaded and resized images.
$minWidth = 2048;
$minHeight = 1365;

// Process form submissions for adding new slideshow entries.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
    $user_id = $_POST['user_id'] ?? null;
    $heading = $_POST['heading'] ?? null;
    $content = $_POST['content'] ?? null;

    if ($_FILES['image']['error'] == 0) {
        $imageFile = $_FILES['image'];

        // Generate unique filenames
        $imageFileName = uniqid() . "_" . basename($imageFile['name']);
        $thumbFileName = 'thumb_' . $imageFileName;

        // Full paths for saving images
        $imagePath = $imageDir . $imageFileName;
        $thumbPath = $thumbDir . $thumbFileName;

        try {
            // Load the image using Intervention
            $image = Image::make($imageFile['tmp_name'])
                ->resize($minWidth, $minHeight, function ($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                })
                ->encode(null, 100); // Keeps quality and profile
            $image->save($imagePath, 100); // Specify quality again to ensure no unnecessary compression

            // Create and save the thumbnail
            $image->resize(300, 200)
                ->save($thumbPath);

            // Save paths relative to the public directory
            $thumbPathRelative = 'uploads/thumbnails/' . $thumbFileName;
            $imagePathRelative = 'uploads/images/' . $imageFileName;

            // Insert data into the database
            $stmt = $pdo->prepare('
                INSERT INTO slideshow (user_id, thumb_path, image_path, heading, content, date_added)
                VALUES (:user_id, :thumb_path, :image_path, :heading, :content, NOW())
            ');

            $stmt->execute([
                ':user_id' => $user_id,
                ':thumb_path' => $thumbPathRelative,
                ':image_path' => $imagePathRelative,
                ':heading' => $heading,
                ':content' => $content,
            ]);

            //$message = "New slideshow entry added successfully!";
            header('Location: ' . $base_path . '/slideshow/gallery.php');
            exit();
        } catch (Exception $e) {
            $message = "Error: " . $e->getMessage();
        }
    } else {
        $message = "Error uploading the file.";
    }
}

What exactly does the $targetFile variable in the 1st code contain? Does it include the path to where the files are being stored? Is it the actual uploaded file name (testimage.bmp) or is is the target/converted file name (testimage.png)?

Im which order are your functions running?

Since imageResize contains the mentioned strtolower as well as returning the final filename, I would expect this to run first and passing the name back to the checking function.

If ny assumption is correct, the file has been written already before the checks are happening ( by $imagick->writeImage($TargetFile) )

If the order however is different, it may go wrong outside the shared code.

Did you output the names at different positions within your script to confirm that the value is always as expected?

just do an echo or var_dump at the respective line and place a die() right after it for quick and dirty testing.

$TargetFile contains just the file name of the original file but I think the problem is that the file gets a new extension and, as this process is run for each folder containing the original, the resized and thumbnail need to be copied to, the message is getting overwritten because by they no longer match.

If it doesn’t contain the path to where the file is at, file_exists($targetFile) will never match any file, let alone a file with a different extension.

If you are not actually saving the file using the original extension, for your .bmp example, and are only saving the converted file, with a .png extension, you would need to test if ‘filename.png’ exists. Alternately, you can get just the filename portion and use glob(“filename.*”) to find all variations of the filename.

The original file is being save too in addition to the resized versions. The extension is changed only if not already jpg or png but even those get overwritten.

Can you then please share the full script which is receiving the posted file?

Everything else would be “finger in the wind” guessing…

Did you try including the debug output?

Okay, here it is but I hope the formatting isn’t too messed up in the process. One endif; seemed to want to keep getting lost.

The basic test HTML form.

<h3>Test FIle Upload</h3>

<form method="POST" name="images" id="images" action="<?=$submitFormAction;?>" enctype="multipart/form-data">
	<input type="file" name="UploadFile" id="UploadFile" multiple> <input name="FileUpload" type="submit" value="Upload File(s)">
	<input type="hidden" name="OldImage" value="">
	<input type="hidden" name="ImageUpload" value="1" id="ImageUpload">
</form>

Setup array in the form script. The message(Alert() function called at the end simply generates any message in a JavaScript popup.

if (isset($_FILES['UploadFile']) && isset($_FILES)) :

	// UseSub IS FOR SUBFOLDER NAME SUCH AS THE ID OR SPECIFIC NAME
	// THIS FOLDER, IF ANY, IS UNDER THE SITE-WIDE $ImagePath FOLDER
	// UseDB TO BE COMMA-SEPARATED LIST THAT INCLUDES TABLE NAME AND FIELDS
	// PDF UPLOADING IS NOT YET ENABLED
	$ImageSetup =	[
					'BasePath'		=> $ImagePath,
					'PDFPath'		=> $PDFPath,
					'UseSub'			=> '',
					'SaveOriginal'		=> 'original',
					'SaveThumbnail'	=> 'thumbnail',
					'PDFFolder'		=> '',
					'AllowedFormats'	=> 'jpg, jpeg, png, gif, bmp, tif, tiff, heic, pdf',
					'KeepFormat'		=> 'jpg, jpeg, png, pdf',
					'DefaultFormat'	=> 'png',
					'UseDB'			=> '',
					'MaxWidth'		=> 640,
					'MaxHeight'		=> 0,
					'ThumbWidth'		=> 150,
					'ThumbHeight'	=> 0,
					'MaxSize'		=> 150000000
					];

	$Message = imageUpload($ImageSetup); 
	messageAlert($Message);
endif;

The function itself but in spite its name, it uploads only the original files, not the resized copies.

function imageUpload($Values) {
	// CREATE UNDERSCORED VARIABLES FROM $Values ARRAY
	foreach ($Values as $row => $val) :
		if (is_string($row)) :
			${'_'.$row} = $val;
		endif;
	endforeach;

	// BEGIN CREATE FOLDERS
		// CREATE BASE IMAGE SUBFOLDER IF NEEDED
		if (isset($_UseSub) && $_UseSub !== "") :
			$SubPath = "{$_BasePath}$_UseSub". DIRECTORY_SEPARATOR;
			// ADD SUBFOLDER FOR ENTRY IMAGES WHICH MAY BE NAME OR DATABASE ENTRY ID
			if (!file_exists($SubPath)) :
				mkdir($SubPath, 0775, true);
			endif;
		else :
			$SubPath = $_BasePath;
		endif;

		// CREATE THUMBNAIL FOLDER IF NEEDED
		if (isset($_SaveThumbnail) && $_SaveThumbnail !== "") :
			$ThumbPath = "{$SubPath}$_SaveThumbnail". DIRECTORY_SEPARATOR;
			// ADD THUMBNAIL PATH (CREATE IF NECESSARY) AND RESIZE IMAGE
			if (!file_exists($ThumbPath)) :
				mkdir($ThumbPath, 0775, true);
			endif;
		else :
			$ThumbPath = "";
		endif;

		// CREATE FOLDER FOR SAVING ORIGINAL FILE
		if (isset($_SaveOriginal) && $_SaveOriginal !== "") :
			$OriginalPath = "{$SubPath}$_SaveOriginal". DIRECTORY_SEPARATOR;
			// ADD ORIGINAL PATH (CREATE IF NECESSARY) BUT DO NOT RESIZE IMAGE
			if (!file_exists($OriginalPath)) :
				mkdir($OriginalPath, 0775, true);
			endif;
		else :
			$OriginalPath = "";
		endif;

		// CREATE FOLDER FOR SAVING PDF FILES
		// NOTE TO SELF: PDFs ARE NOT CURRENTLY BEING UPLOADED
		if (isset($_PDFPath) && isset($_PDFFolder) && $_PDFPath !== "" && $_PDFFolder !== "") :
			$PDFPath = "{$_PDFPath}$_PDFFolder". DIRECTORY_SEPARATOR;
			// ADD ORIGINAL PATH (CREATE IF NECESSARY) BUT DO NOT NOT AN IMAGE SO DO NOT RESIZE 
			if (!file_exists($PDFPath)) :
				mkdir($PDFPath, 0775, true);
			endif;
		else :
			$PDFPath = "";
		endif;
	// END CREATE FOLDERS

	// BEGIN CREATE SOME VARIABLES
		// GET VALUE OF $_AllowedFormats AND MAKE INTO AN ARRAY
		$AllowedFormats = array_map("trim", explode(',', $_AllowedFormats));

		// INITIALIZE VARIABLE, ASSUME VALID BEFORE CHECKING
		$uploadValid = 1;
		$Error = "of an undetermined problem";

		// CREATE VARIABLE FOR FILE NAME
		$targetFile = $_FILES["UploadFile"]["name"];
		$targetFile = strtolower($targetFile);

		// CREATE VARIABLE FOR FILE TYPE
		// DO NOT CHANGE FORMAT OF JPG OR PDF FILES
		$imageFileType = pathinfo($targetFile, PATHINFO_EXTENSION);
		$imageFileType = strtolower($imageFileType);

		$KeepFormat = array_map("trim", explode(',', $_KeepFormat));
		$_DefaultFormat = (in_array($imageFileType, $KeepFormat)) ? $imageFileType : $_DefaultFormat;
	// END CREATE SOME VARIABLES

	// BEGIN CHECK VALIDITY OF SUBMITTED FILE
		// CHECK IF THE UPLOAD FILE IS AN ACTUAL IMAGE
		if (isset($_POST["submit"])) :
			$check = getimagesize($_FILES["UploadFile"]["tmp_name"]);
			if ($check !== FALSE) :
				$Message = "The file is a " . $check["mime"] . " image.";
				$uploadValid = 1;
			else :
				$Error = "it is not an image.";
				$uploadValid = 0;
			endif;
		endif;
// NOTE TO SELF: FIX CASE ISSUE
		if (!is_dir($SubPath)) :
		// CHECK IF THE UPLOAD DIRECTORY EXISTS
		// IT SHOULD HAVE BEEN CREATED ABOVE
			$Error = "the image directory does not exist.";
			$uploadValid = 0;
		elseif (strtolower(file_exists($targetFile))) :

		// CHECK IF FILE ALREADY EXISTS
			$Error = "it already exists.";
			$uploadValid = 0;
		elseif ($_FILES['UploadFile']['size'] == 0) :
		// CHECK THAT THE FILE CONTAINS DATA
			$Error = "it contains no data.";
			$uploadValid = 0;
		elseif ($_FILES["UploadFile"]["size"] > $_MaxSize) :
		// CHECK IF FILE IS WITHIN MAXIMUM SIZE
			$Error = "it is too large.";
			$uploadValid = 0;
		elseif (!in_array($imageFileType, $AllowedFormats)) :
		// ALLOW ONLY SPECIFIC FILE FORMATS
			$_AllowedFormats = preg_replace("/,([^,]+)$/", " & $1", $_AllowedFormats);
			$Error = "only $_AllowedFormats files are allowed.";
			$uploadValid = 0;
		endif;
	// END CHECK VALIDITY OF SUBMITTED FILE

	// BEGIN FINAL CHECK, FILE PROCESSING AND UPLOADING
		// CHECK IF $uploadValid IS TRUE AND IF IT IS, UPLOAD THE FILE
		if ($uploadValid == 0) :
			$Message = "Sorry, the file was not processed because $Error";
		else :		
			$Message = "The file has been processed.";

			// PROCESS AND SAVE IMAGES TO FOLDERS SPECIFIED IN $Values
			if (isset($SubPath) && $SubPath !== "") :
				$FileName = basename(imageResize($SubPath, $_DefaultFormat, $_MaxWidth, $_MaxHeight));
				$Size = ($_MaxWidth > 0) ? "$_MaxWidth wide" : "$_MaxHeight high";
				$Message .= " A new reduced size image $FileName of $Size was uploaded. ";
			endif;

			// PROCESS AND SAVE THE THUMBNAIL
			if (isset($ThumbPath) && $ThumbPath !== "") :
				$FileName = imageResize($ThumbPath, $_DefaultFormat, $_ThumbWidth, $_ThumbHeight);
				$Size = ($_ThumbWidth > 0) ? "$_ThumbWidth wide" : "$_ThumbHeight high";
				$Message .= " A new thumbnail image of $Size was created.";
			endif;
			
			// SAVE THE ORIGINAL IMAGE
			// MOVED TO THE LAST DUE TO move_uploaded_file() DELETED TEMP FILE
			if (isset($OriginalPath) && $OriginalPath !== "") :
				$ImageInfo		= $_FILES["UploadFile"]["tmp_name"];
				move_uploaded_file($_FILES["UploadFile"]["tmp_name"],$OriginalPath.$_FILES["UploadFile"]["name"]);
				$Message .= " A copy of the original image ". $_FILES["UploadFile"]["name"] ." was uploaded. ";
			endif;

			//return "The file ". htmlspecialchars(basename($_FILES['UploadFile']['name'])). " has been uploaded and $NewImage created.";
		endif;

		return $Message;
	// END FILE PROCESSING AND UPLOADING
}

The imageResize() function does the actual uploading except for the original copies which are done in the function above.

// USE IMAGEMAGICK TO RESIZE IMAGE
function imageResize($TargetDir, $ImageFormat, $MaxWidth, $MaxHeight) {

	$TargetFile = pathinfo($_FILES['UploadFile']['name'], PATHINFO_FILENAME);
	$TargetFile = strtolower($TargetFile);
	$imagick = new Imagick($_FILES['UploadFile']['tmp_name']);

	$imagick->setImageColorspace(imagick::COLORSPACE_SRGB);
	$imagick->setImageFormat($ImageFormat);
	$imagick->resizeImage($MaxWidth, $MaxHeight, Imagick::FILTER_LANCZOS, 1);
	$imagick->setFilename($TargetFile);

	$TargetFile = "$TargetDir{$TargetFile}.$ImageFormat";
	$imagick->writeImage($TargetFile);

	return $TargetFile;
}

You already have the cause -

As to the posted code - after you have tested that there is data in $_FILES, you must test that the upload was successful (the error element, $_FILES[…][‘error’], will be a zero) before referencing any of the uploaded file information, and $_FILES is always set, even if it is empty. There’s no point in using isset().

You are correct and I noticed that too after posting. It was working fine until I moved the code info a function and added ImageMagick to its own function so apparently something was removed that should not have been! The code needs to cleaning and there are probably still some variables containing the same values as others but in the meantime, here is a working version.

That more or less done, now I need to add the facility to log the entries into the database but, as back-end database programming is what I do best, I’m sure I can handle that! The main difficulty will be in making it compatible throughout my various sites, each with their own specific needs but I can probably manage that too.

The original file which is not being changed at all seems to be uploading without is exif data so I’ll need to check that the test files actually containing it!

Oh, I almost forgot. I renamed the function too to make more sense for what it does and I added support for the PDF file format in case it’s needed.

function imageProcess($Values) {
	// CREATE UNDERSCORED VARIABLES FROM $Values ARRAY
	foreach ($Values as $row => $val) :
		if (is_string($row)) :
			${'_'.$row} = $val;
		endif;
	endforeach;

	// BEGIN CREATE FOLDERS
		// CREATE BASE IMAGE SUBFOLDER IF NEEDED
		if (isset($_UseSub) && $_UseSub !== "") :
			$SubPath = "{$_BasePath}$_UseSub". DIRECTORY_SEPARATOR;
			// ADD SUBFOLDER FOR ENTRY IMAGES WHICH MAY BE NAME OR DATABASE ENTRY ID
			if (!file_exists($SubPath)) :
				mkdir($SubPath, 0775, true);
			endif;
		else :
			$SubPath = $_BasePath;
		endif;

		// CREATE THUMBNAIL FOLDER IF NEEDED
		if (isset($_SaveThumbnail) && $_SaveThumbnail !== "") :
			$ThumbPath = "{$SubPath}$_SaveThumbnail". DIRECTORY_SEPARATOR;
			// ADD THUMBNAIL PATH (CREATE IF NECESSARY) AND RESIZE IMAGE
			if (!file_exists($ThumbPath)) :
				mkdir($ThumbPath, 0775, true);
			endif;
		else :
			$ThumbPath = "";
		endif;

		// CREATE FOLDER FOR SAVING ORIGINAL FILE
		// TO MAINT TEMP FILE, THIS MUST BE BELOW THE TWO OTHER PROCESSES
		if (isset($_SaveOriginal) && $_SaveOriginal !== "") :
			$OriginalPath = "{$SubPath}$_SaveOriginal". DIRECTORY_SEPARATOR;
			// ADD ORIGINAL PATH (CREATE IF NECESSARY) BUT DO NOT RESIZE IMAGE
			if (!file_exists($OriginalPath)) :
				mkdir($OriginalPath, 0775, true);
			endif;
		else :
			$OriginalPath = "";
		endif;

		// CREATE FOLDER FOR SAVING PDF FILES
		if (isset($_PDFPath) && $_PDFPath !== "") :
			$PDFPath = "{$_PDFPath}$_PDFFolder". DIRECTORY_SEPARATOR;
			// ADD ORIGINAL PATH (CREATE IF NECESSARY) BUT NOT AN IMAGE SO DO NOT RESIZE 
			if (!file_exists($PDFPath)) :
				mkdir($PDFPath, 0775, true);
			endif;
		else :
			$PDFPath = "";
		endif;
	// END CREATE FOLDERS

	// BEGIN CREATE SOME VARIABLES
		// GET VALUE OF $_AllowedFormats AND MAKE INTO AN ARRAY
		$AllowedFormats = array_map("trim", explode(',', $_AllowedFormats));

		// INITIALIZE VARIABLE, ASSUME VALID BEFORE CHECKING
		$uploadValid = 1;
		$Error = "The upload was initialized. ";

		// CREATE VARIABLE FOR FILE NAME
		// NOTE TO SELF: CAN THIS BE USED THROUGHOUT?
		$targetFile = str_replace(' ','_',$_FILES["UploadFile"]["name"]);
		$targetFile = strtolower($targetFile);

		// CREATE VARIABLE FOR FILE TYPE
		$imageFileType = pathinfo($targetFile, PATHINFO_EXTENSION);
		$imageFileType = strtolower($imageFileType);
		$imageFileType = ($imageFileType === "jpeg") ? "jpg" : $imageFileType;

		// DO NOT CHANGE FORMAT OF JPG OR PDF FILES
		$KeepFormat = array_map("trim", explode(',', $_KeepFormat));
		$_DefaultFormat = (in_array($imageFileType, $KeepFormat)) ? $imageFileType : $_DefaultFormat;
		
		// CREATE VARIABLE FOR DUPLICATE CHECKING OF NEW FILE NAME
		$BaseFile = $SubPath.pathinfo($targetFile, PATHINFO_FILENAME).".$_DefaultFormat";
	// END CREATE SOME VARIABLES

	// BEGIN CHECK VALIDITY OF SUBMITTED FILE
		// CHECK IF THE UPLOAD FILE IS AN ACTUAL IMAGE
		if (isset($_POST["submit"])) :
			$check = getimagesize($_FILES["UploadFile"]["tmp_name"]);
			if ($check !== FALSE) :
				$Message = "The file is a " . $check["mime"] . " image.";
				$uploadValid = 1;
			else :
				$Error = "it is not an image.";
				$uploadValid = 0;
			endif;
		endif;

		if (!is_dir($SubPath)) :
		// CHECK IF THE UPLOAD DIRECTORY EXISTS
		// IT SHOULD HAVE BEEN CREATED ABOVE
			$Error = "the image directory does not exist.";
			$uploadValid = 0;
		elseif (file_exists($BaseFile)) :
		// CHECK IF FILE ALREADY EXISTS
			$Error = "it already exists."; 
			$uploadValid = 0;
		elseif ($_FILES['UploadFile']['size'] == 0) :
		// CHECK THAT THE FILE CONTAINS DATA
			$Error = "it contains no data.";
			$uploadValid = 0;
		elseif ($_FILES["UploadFile"]["size"] > $_MaxSize) :
		// CHECK IF FILE IS WITHIN MAXIMUM SIZE
			$Error = "it is too large.";
			$uploadValid = 0;
		elseif (!in_array($imageFileType, $AllowedFormats)) :
		// ALLOW ONLY SPECIFIC FILE FORMATS
			$_AllowedFormats = preg_replace("/,([^,]+)$/", " & $1", $_AllowedFormats);
			$Error = "only $_AllowedFormats files are allowed.";
			$uploadValid = 0;
		endif;
	// END CHECK VALIDITY OF SUBMITTED FILE

	// BEGIN FINAL CHECK, FILE PROCESSING AND UPLOADING
		// CHECK IF $uploadValid IS TRUE AND IF IT IS, UPLOAD THE FILE
		if ($uploadValid == 0) :
			$Message = "Sorry, the file was not processed because $Error";
		else :		
			$Message = "The file has been processed.";

			// PROCESS AND SAVE IMAGES TO FOLDERS SPECIFIED IN $Values
			if (isset($SubPath) && $SubPath !== "" && $imageFileType !== "pdf") :
				$FileName = basename(imageResize($SubPath, $_DefaultFormat, $_MaxWidth, $_MaxHeight));
				$Size = ($_MaxWidth > 0) ? "$_MaxWidth wide" : "$_MaxHeight high";
				$Message .= " A new reduced size image $FileName of $Size was uploaded. ";
			endif;

			// PROCESS AND SAVE THE THUMBNAIL
			if (isset($ThumbPath) && $ThumbPath !== "" && $imageFileType !== "pdf") :
				$FileName = imageResize($ThumbPath, $_DefaultFormat, $_ThumbWidth, $_ThumbHeight);
				$Size = ($_ThumbWidth > 0) ? "$_ThumbWidth wide" : "$_ThumbHeight high";
				$Message .= " A new thumbnail image of $Size was created.";
			endif;

			// SAVE THE ORIGINAL IMAGE
			// MOVED TO THE LAST DUE TO move_uploaded_file() DELETED TEMP FILE
			if (isset($OriginalPath) && $OriginalPath !== "" && $imageFileType !== "pdf") :
				$ImageInfo	= $_FILES["UploadFile"]["tmp_name"];
				move_uploaded_file($_FILES["UploadFile"]["tmp_name"],$OriginalPath.$_FILES["UploadFile"]["name"]);
				$Message .= " A copy of the original image ". $_FILES["UploadFile"]["name"] ." was uploaded. ";
			endif;

			// SAVE PDF FILES
			if (isset($PDFPath) && $PDFPath !== "" && $imageFileType === "pdf") :
				$ImageInfo	= $_FILES["UploadFile"]["tmp_name"];
				move_uploaded_file($_FILES["UploadFile"]["tmp_name"],$PDFPath.$_FILES["UploadFile"]["name"]);
				$Message .= " A copy of the PDF ". $_FILES["UploadFile"]["name"] ." was uploaded. ";
			endif;
		endif;

		return $Message;
	// END FILE PROCESSING AND UPLOADING
}

if (strtolower(file_exists($targetFile)))

may have always evaluated to false (empty string) because of the wrong order.

You are applying a strtolower to the boolean result of file_exists

furthermore your whole repetitive strtolower will fail, if any of your pathnames contains an uppercase letter, because you are creating the folders without strtolower but check later within file_exists (which must include the path and is run through strtolower as a whole)

the repetitive use of strtolower is not needed, after you already had applied it on the targetFile in the first place.

So is it working now with your latest changes?

Yes, thank you and I had already noticed and fixed it and removed the leftover strtolower() too. As I indicated, it still needed cleaning up so I’ve been doing that too now that I’ve worked out how to get what’s needed for the file name comparison and which one I wanted to compare. As uploading the original file and/or a thumbnail is optional depending on which of my sites it’s for, I am comparing the main file being uploaded which is not optional. It is also now set to strip out the EXIF data from any files going to the public site.

Sponsor our Newsletter | Privacy Policy | Terms of Service