Hi All, I have an image upload that works for my requirements -

But what I am unable to figure out is how to rename the image to the datatime stamp and to keep the file extension
.jpg / .png / .gif / .jpeg etc

I have a variable $datetime
$datetime = date('l jS F Y h:i:s');

here is the code that I am trying to work with -

Any help with be much appreciated -

////////////////////////////////////////////////////////////////////////////////////////////////////////////
				$img1 = $_FILES['jan_image']['name'];
				//Add a security check, to make sure only allowed files are uploaded
				$ext=explode('.',$img1);//explode the image name into an array to get the extension
				$allowed_exts=array('jpg','jpeg','png','bmp','gif');// allowed extensions
				if(in_array(strtolower($ext[1]), $allowed_exts)){//file type is allowed!
					//destination
					$dest="members/$securecode/$sname/images/igal/".$img1;
					//temp image name
					$val= move_uploaded_file($_FILES['jan_image']['tmp_name'], $dest);
				
					chmod($dest, 0644);//make sure you have permissions for the file
					if($val)
					{ //update database and rename
					//rename image to datetime stamp
					rename($dest, 'members/'.$securecode.'/'.$sname.'/images/igal/jan.jpg');
					//set $dest to the new file name so the database entry is correct
					$dest="members/".$securecode."/".$sname."/images/igal/jan.jpg";
						
					mysql_query("update tbl set igimg1='$dest' where id=$lastid");
					}
					}

Dani AI

Generated

Short answer: do not use a human-readable date string (like date('l jS F Y h:i:s')) as a filename — it contains spaces and colons and can break things. was right to suggest a timestamp, but add a few safety and uniqueness steps, avoid rename() and never trust the uploaded extension/MIME blindly.

A robust pattern

  1. check $_FILES['jan_image']['error'] and is_uploaded_file(); 2) verify the MIME with finfo_file() or getimagesize(); 3) extract a lowercase extension (use pathinfo() PATHINFO_EXTENSION) and validate it against an allow-list; 4) build a safe filename using a compact timestamp plus a random suffix (to prevent same-second collisions); 5) ensure the target directory exists and is writable; 6) call move_uploaded_file() directly to that new name; 7) set safe permissions and store the (relative) filename in the DB using a prepared statement. Avoid storing full server paths if portability is desired.

Example (concise, modern-PHP sketch):

$err = $_FILES['jan_image']['error'] ?? UPLOAD_ERR_NO_FILE;
if ($err === UPLOAD_ERR_OK && is_uploaded_file($_FILES['jan_image']['tmp_name'])) {
    $ext = strtolower(pathinfo($_FILES['jan_image']['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg','jpeg','png','gif','bmp'];
    $mime = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $_FILES['jan_image']['tmp_name']);
    if (in_array($ext, $allowed) && strpos($mime, 'image/') === 0) {
        $safeDir = "members/{$securecode}/{$sname}/images/igal";
        if (!is_dir($safeDir)) mkdir($safeDir, 0755, true);
        $filename = date('YmdHis') . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
        $dest = "$safeDir/$filename";
        if (move_uploaded_file($_FILES['jan_image']['tmp_name'], $dest)) {
            chmod($dest, 0644);
            $stmt = $pdo->prepare('UPDATE tbl SET igimg1 = ? WHERE id = ?');
            $stmt->execute([$filename, $lastid]);
        }
    }
}

Notes and cautions: convert random_bytes() fallback to uniqid() on older PHP installs; sanitize $securecode/$sname (no ../); limit file size; confirm extension matches MIME; disable script execution in the upload folder (e.g., .htaccess) and stop using deprecated mysql_* calls — use PDO or mysqli with prepared statements. This addresses the rename/extension concern and gives a collision-resistant filename suitable for long-term storage.

Recommended Answers

All 3 Replies

Member Avatar for Member #120589
$now = time(); //this gives a unix timestamp (integer)
//OR $now = date('YmdHis') //gives a more readable timestamp, e.g. 20120211121545 (2012-02-11 12:15:45)

$dest="members/$securecode/$sname/images/igal/{$image_name}_{$now}.{image_extension};

This way you don't need to rename.

Obviously you need to exctract the filename and the extension from the uploaded file. You can do this with pathinfo().

$fdata = pathinfo($_FILES['jan_image']['name']);
$imagename = $fdata['filename'];
$image_extension = $fdata['extension'];

Using explode is a little dangerous as a period (.) may be included in the filename (it shouldn't be, but it pays to obviate this eventuality).
Of course you could use other string functions to get the true extension, but why bother with all that nonsense?

So for example:

if uploaded file was: mynewpicture.jpg

the stored file will be mynewpicture_20120211121545.jpg (depending on the $now format used)

Hi thanks for a quick reply -

How can i integrate your solution into my image upload ?

Member Avatar for Member #120589

Want me to upload it for you too?!

$img1 = $_FILES['jan_image']['name'];

$fdata = pathinfo($_FILES['jan_image']['name']);
$image_name = $fdata['filename'];
$image_extension = $fdata['extension'];

$now = date('YmdHis');

$allowed_exts=array('jpg','jpeg','png','bmp','gif');
if(in_array(strtolower($image_extension), $allowed_exts)){
   $dest="members/$securecode/$sname/images/igal/{$image_name}_{$now}.{image_extension};
   $val= move_uploaded_file($_FILES['jan_image']['tmp_name'], $dest);
   chmod($dest, 0644);//make sure you have permissions for the file
   if($val){
      mysql_query("update tbl set igimg1='$dest' where id=$lastid");
   }
}					}

Why are you updating the last id??
Why not just make an insert with the code above along with the rest of your fields?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.