Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

I want to overwrite the image in the folder of different extensions (jpg, jpeg, png) in PHP.

Hi, Thanks in advance. I want to upload image in folder named as "uploads". Image type which can be uploaded are jpg, jpeg, and png. Once, i upload it in the folder and now want to overwrite the file, i am able to overwrite the file with same type. But when i try to overwrite the file with different type, i am unable to do that. Instead of overwriting, the new image is uploaded and the old image is not deleted from the folder.

3 Answers

hmmm, if overwriting isn't working for you, perhaps you could use two steps - 1) Delete the file 2) Add the new one?

Jeff Lemay
Jeff Lemay
14,268 Points

You'd have to write something that deletes any files with the same file name. You can delete files using php's unlink() but be aware that this can be a big security risk if you don't have proper validation (i.e. someone could delete other files on your server).

Fundamentally, files with the same name but different extensions are different files and I am aware of no systems that will natively do what you want. To the computer, the difference is the same between .jpg and .png as it is between .jpg and .txt. You would have to write a code to compare names and do the replacement. You could write it so it only looked at certain file extensions. The better choice for a web app is only allow certain file types to be uploaded and manually reduce photos from time to time if you really need to.