Jump to content

Prefix image file with user id before image upload


son

Recommended Posts

I need a bit of help with this image upload function. The function is:

			foreach ($images as $imgID => $img_name)			{  				if (!isset($_FILES[$imgID]['name']) OR empty($_FILES[$imgID]['name']) OR $_FILES[$imgID]['error'] == 4)   				{  					if ($imgID == 'img1')					{    				$errors[$imgID] = $img_name;					}    			$$imgID = FALSE; 				}   				else   				{    				if ($_FILES[$imgID]['error'] != 0)    				{      				$errors[$imgID] = upload_error($_FILES[$imgID]['error']);      				$$imgID = false;    				}    				else    				{      				$ext = explode('.',$_FILES[$imgID]['name']);      				$ext = $ext[count($ext)-1];      					if (!in_array(strtolower($ext), $allowed))      					{        				$errors[$imgID] = 'Please use only the following formats: jpg, gif, png';        				$$imgID = FALSE;      					}      					else      					{        				$img_num = trim(str_replace('Image', '', $img_name));         				$$imgID = "{$img_num}.{$ext}";        				$$imgID = strtolower($$imgID);      					}    				}  				}			}

I move the image files after the data is inserted into database via:

if ($insertResult = mysqli_query ($dbc, $insertQuery))						{						foreach ($images as $imgID => $img_name)						{							if (!move_uploaded_file($_FILES[$imgID]['tmp_name'], "../ banner/main/{$_FILES[$imgID]['name']}"))         		 			$errors[$imgID] = 'The image could not be moved.';        					else        					{          					resize_image("../banner/main/{$_FILES[$imgID]['name']}", "../ banner/main/{$_FILES[$imgID]['name']}", BANNER_SIZE_W, BANNER_SIZE_H);         		 			resize_image("../banner/main/{$_FILES[$imgID]['name']}", "../ banner/thumb/{$_FILES[$imgID]['name']}", THUMB_SIZE_W, THUMB_SIZE_H);        					}						}

This is generally working, but now I have to use a user id and start the image name as '1_nameOfFile.jpg' for example. The user id is stored in $userID.I have tried several options, but somehow it only inserts the file name correctly into database, but does not name and/or move the file correctly. How would it be best for me to amend my function and/or statements to move/resize the files?Son

Link to comment
Share on other sites

In the move_uploaded_file() method and all following usages of the file, just concatenate the ID with the file name:../ banner/main/ID_{$_FILES[$imgID]['name']}

Link to comment
Share on other sites

You just needs to update fifth line of your new code with below,if (!move_uploaded_file($_FILES[$imgID]['tmp_name'], "../ banner/main/$userID.$_FILES[$imgID]['name']"))
Thanks. You brought me now onto the right track:-)Son
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...