Jump to content

[SOLVED] File Upload: Checking type/extension, then renaming, but keeping extension


Recommended Posts

 

Hi,

 

I'm working on a file upload form. I want to let people upload only jpgs or gifs. I need my form to check that it is jpg or gif, then rename it, but keep the existing extension. Does anyone know how I can do this? This is my code so far: (I tried getting the extension with strrchr but it isn't working)

 

if (move_uploaded_file($_FILES['visitor_image']['tmp_name'], "add_image_folder/{$_FILES['visitor_image']['name']}")) {
echo '<p>File name: ' . $_FILES['visitor_image']['name'] . '</p>';
echo '<p>File type: ' . $_FILES['visitor_image']['type'] . '</p>';
$extension = substr(strrchr($_FILES['visitor_image']['name'],"."));
echo '<p>File extension: ' . $extension . '</p>';

$visitor_image_old_name = "add_image_folder/{$_FILES['visitor_image']['name']}";
$visitor_image_new_name = 'add_image_folder/' . $user_id . '.jpg';
rename ($visitor_image_old_name, $visitor_image_new_name); 

echo "<p>Your image has been uploaded</p>";
echo "<p><img src=\"$visitor_image_new_name\" width=\"150\"></p>";

}

$extension = end(preg_split("/\./", $filename));

 

The preg_split() function return an array with split values separated by "." (dot), with end() get the last element of this array, which in our case it's the extension :).

 

if($extension == "jpg" OR $extension == "gif"){

//Your code

}

Wouldn't that let you just let upload files with jpg or gif extentions but you may not be sure it is a real jpg.

 

I had already taken part on a subject like this before and looking all around I did find the following link to the php function "getimagesize"

 

http://ca3.php.net/manual/en/function.getimagesize.php

 

Granted, the name implies it returns the image's size but it returns the type, dimesions and mime type of the image you're handling...

 

Either way, I guess this might be a safer function for you...

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.