Jump to content

Archived

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

Leao

Excluding non-JPEG images

Recommended Posts

Hi,

I need a PHP script that excludes images sent from a form that aren't JPEGs. I originally tried this PHP script:

[code=php:0]
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']);
$ok=1;

if ($uploaded_type != 'image/jpeg') {
{
echo "Sorry your file needs to be a JPEG image.";
$ok=0;
}

if ($ok==0)
{
echo "Sorry your file was not uploaded";
}

else
{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], 'images/title.jpg'))
{
echo "Your image has been uploaded.";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
[/code]

This script worked perfectly on most computers, but on those that hide file extensions it rejected even valid JPEG images. I tried the getimagesize() method below too as an alternative means of rejecting non JPEG files. It doesn't work either, can you help? Thanks – Leao

[code=php:0]
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']);
$ok=1;

list($ImportWidth,$ImportHeight,$ImageMimeType) = getimagesize($_FILES['uploaded']['tmp_name']) ;

if ($ImportMimeType != 'image/jpeg')
{
echo "Sorry your file needs to be a JPEG image.";
$ok=0;
}

if ($ok==0)
{
echo "Sorry your file was not uploaded";
}

else
{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], 'images/title.jpg'))
{
echo "Your image has been uploaded.";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
[/code]

Share this post


Link to post
Share on other sites
This might help you, http://php.robm.me.uk/ . Scroll down to the "file uploads" section. Here is a snippet of code from that site:
[code]
$validMimes = array(
    'image/png' => '.png',
    'image/x-png' => '.png',
    'image/gif' => '.gif',
    'image/jpeg' => '.jpg',
    'image/pjpeg' => '.jpg'
);

$image = $_FILES['image'];

if(!array_key_exists($image['type'], $validMimes)) {
    die('Sorry, but the file type you tried to upload is invalid; only images are allowed.');
}

// Get the filename minus the file extension:
$filename = substr($image['name'], 0, strrpos($image['name'], '.'));

// Append the appropriate extension
$filename .= $validMimes[$image['type']];

// Do something with the uploaded file
[/code]

Share this post


Link to post
Share on other sites
Thanks, I tried this and... it worked!

[code=php:0]if ($ImportMimeType != 2)
{
echo "Sorry your file needs to be a JPEG image.";
$ok=0;
} [/code]

Share this post


Link to post
Share on other sites

×

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.