TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Change filename on upload (http://www.talkphp.com/general/2857-change-filename-upload.html)

Jmz 05-28-2008 08:54 AM

Change filename on upload
 
Hi,

I've got a form that lets users upload a thumbnail file. It then puts the filename of the image in the database.

The code looks like:

Code:

<?php

        include("../../config/connect.php");
        include("../../config/functions.php");
       
        // Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path. 
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
$_FILES['uploadedfile']['tmp_name']; 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
       
        $galleryname = $_POST['galleryname'];
        $gallerydescription = $_POST['gallerydescription'];
        $gallerykeywords = $_POST['gallerykeywords'];
        $thumbname = basename( $_FILES['uploadedfile']['name']);
       
        if (empty ($galleryname) or empty ($gallerydescription) or empty ($gallerykeywords)) {
                echo "Fill out all fields";
                exit();
        }
       
        $galleryname = mysql_real_escape_string($galleryname);
        $gallerydescription = mysql_real_escape_string($gallerydescription);
        $gallerykeywords = mysql_real_escape_string($gallerykeywords);
       
        $create_gallery = mysql_query("INSERT INTO tbl_gallery (fld_id, fld_galleryname, fld_gallerydesc, fld_keywords, fld_userid, fld_thumbname) values ('', '$galleryname', '$gallerydescription', '$gallerykeywords', '1', '$thumbname')");
       
        if ($create_gallery){
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:spry="http://ns.adobe.com/spry">
<head>
<title>Settings Updated</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/style_notice.css" type="text/css" rel="stylesheet" />
<meta http-equiv="refresh" content="2;url=<?php echo "http://play.jamesowers.co.uk/photo/usercp/create_gallery.php"; ?>"/>
<style type="text/css">
#content {background: #1c284e url(images/logged_out.gif) no-repeat;}
</style>
</head>
<body>
<div id="content">
Gallery Added
</div>

<div id="footer">
<img src="images/logo_login.gif" alt="" class="toplogo"/>
</div>
</body>
<?php
        } else {
                echo "Error";
        }       
       
        } else{
    echo "There was an error uploading the file, please try again!";
}
?>

I would like to be able to either rename the file or at least add a prefix to the filename (both on the image and in the databse). How would I do this?

Also how would I go about resizing the image if it is over 100px x 100px?

ReSpawN 05-28-2008 10:16 AM

If you output the $_FILES with print_r();, you'll see that it is a multidimensional array. Thus, the key names 'name', can simply be changed by setting the value $_FILES['uploadfile']['name'] with a prefix. Automaticly generated by choice, of course.

Jmz 05-28-2008 11:00 AM

Thanks, I've got the image name sorted.

Any ideas on resizing it if it's too big?

Jim 05-28-2008 12:42 PM

You can change the name in the move_uploaded_file(), as a second argument just specify the filename (and path) you desire.

In this script you don't check for safety, you should always check the Mimetype and extention of the file you are uploading.

Here a little function i made a while ago, i recommend you check this function for ideas how to make your script be save. (Oh and i also included a little function that makes tumbnails)

PHP Code:

function uploadFoto($foto$naam) {

    
// Wat voor extenties zijn toegestaan?
    
$extenties = array('jpg''gif''jpeg''png''pjpeg');
   
    
// Wat voor mimetypes zijn toegestaan?
    
$mimetypes = array('image/jpeg''image/png''image/pjpeg''image/gif');
   
    
// Wat is de max size in bytes?
    
$maxsize 2000000// 1.5 / 2 mb
   
    // Haal extentie van bestand
    
preg_match('/^(.*?)\.([a-zA-Z0-9]{2,5})$/is'$foto['name'], $match);
   
    
// Check of bestand goede extentie heeft
    
if(in_array(strtolower($match[2]), $extenties)) {
       
        
// Extentie goed
        // Is bestand onder de maximale grootte?
        
if($foto['size'] < $maxsize) {
           
            
// Foto is goede size
            // Foto heeft goede mimetype?
            
if(in_array($foto['type'], $mimetypes)) {
           
                
$image $foto['tmp_name'];
   
                
$ext $match[2];
   
                
// Open file adv extentie
                
switch(strtolower($ext)) {
                    case 
"jpeg":   
                        
$source = @imagecreatefromjpeg($image);   
                    break;
                    case 
"jpg":   
                        
$source = @imagecreatefromjpeg($image);   
                    break;
                    case 
"pjpeg":   
                        
$source = @imagecreatefromjpeg($image);   
                    break;
                    case 
"gif":   
                        
$source = @imagecreatefromgif($image);   
                    break;
                    case 
"png":   
                        
$source = @imagecreatefrompng($image);   
                    break;
                    default:
                        return 
FALSE;
                }
               
                
//
               
                // source dimenties
                
$sWidth imagesx($source);
                
$sHeight imagesy($source);
           
                
// Maak nieuwe file
                
$file imagecreatetruecolor($sWidth$sHeight);
               
                
imagecopyresampled($file$source0,0,0,0$sWidth$sHeight$sWidth$sHeight);
               
                
// Sla image op
                
imagejpeg($file'images/upload/'.$naam.'.jpg');
               
               
                
// Maak en resized bestand
                
copyResized('images/upload/'.$naam.'.jpg'100100);
               
                return 
$naam.'.jpg';
           
            } else {
           
                echo
'Het bestand heeft geen goede mimetype.';
                return 
FALSE;
           
            }
       
        } else {
           
            
// Foto te groot
            
echo'Het bestand '.$foto['name'].' is te groot, we accepteren maximaal 2 mb.';
            return 
FALSE;
       
        }
   
    } else {
       
        
// Extentie niet goed
        
echo'Extentie van '.$foto['name'].' is niet toegestaan, we accepteren enkel jpg, png, bmp en gif. Deze foto had: '.$match[2];
        return 
FALSE;
       
    }

}

// kopieer een resized image
function copyResized($image$width$height) {

    
// Bestandsnaam
    
$fileName basename($image);
   
    
// Get extentie
    
preg_match('/^(.*?)\.([a-zA-Z0-9]{2,5})$/is'$fileName$match);
   
    
$ext $match[2];
   
    
// Open file adv extentie
    
switch(strtolower($ext)) {
        case 
"jpeg":   
            
$source = @imagecreatefromjpeg($image);   
        break;
        case 
"jpg":   
            
$source = @imagecreatefromjpeg($image);   
        break;
        case 
"pjpeg":   
            
$source = @imagecreatefromjpeg($image);   
        break;
        case 
"gif":   
            
$source = @imagecreatefromgif($image);   
        break;
        case 
"png":   
            
$source = @imagecreatefrompng($image);   
        break;
        default:
            return 
FALSE;
    }
   
    
// Kan image openen?
    
if($source == FALSE) {
        echo 
'Kan tumb image niet openen.<br>';
        return 
FALSE;
    }
   
    
// Dimenties
    
$sourceWidth  imagesx($source);
    
$sourceHeight imagesy($source);
   
    
// Maak nieuwe file
    
$tumb imagecreatetruecolor($width$height);
   
    
imagecopyresampled($tumb$source0,0,0,0$width$height$sourceWidth$sourceHeight);
   
    
imagejpeg($tumb'images/upload/'.$match[1].'_tumb.jpg');
   
}


?> 


Jmz 05-28-2008 01:19 PM

Thanks for that :)

ReSpawN 05-28-2008 05:30 PM

Nice & Dutch Jim. :P Hehe, lovely translated.

Anyways, are you somewhat good in RegEx?

Orc 05-29-2008 02:57 AM

What I do when uploading files is, use touch() then file_put_contents. :P

Jmz 05-29-2008 04:04 PM

How important is checking mime types?

For some reason some of the images I try to upload dont have mime types according to my script.

I also read this on the php.net site:

Quote:

The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
(link to quote: PHP: Handling file uploads - Manual)

Jim 05-29-2008 04:18 PM

Hmm I always learned to also check the mimetype because people would be able to just upload any file thats a .jpg for example.

Of course I don't know how that could harm you server in any way since it won't be read as (for example) an executable. But it doesn't harm adding in your script so I've done it ever since.

I never had problems with finding the mimetypes from a file though. In IE6/7 FF1/2 and Opera 9 I could just upload the files and the mimetype would be found.

delayedinsanity 05-29-2008 04:32 PM

How are you checking the mime-type? I've never seen a browser that sends a file without that type of header information, but I'm sure they could exist. You can alternatively double-check your image uploads with getimagesize() or a combination of exif_imagetype() and image_type_to_mime_type() (which coincidently also received the award for function name with the most underscores, PHP Grammies 2005)...
-m

Jmz 05-29-2008 06:57 PM

To check the mime type I'm using:

Code:

$mimetypes = array('image/jpeg', 'image/png', 'image/pjpeg', 'image/gif');
$mimetype = strtolower($_FILES['uploadedfile']['type']);
if (in_array($mimetype,$mimetypes)){
//do upload photo stuff
}else{               
echo "File format not recognised (mime) - $mimetype";       
}

I added the "$mimetype" to the error so I could see what it was comparing to the array but it just comes up blank.

delayedinsanity 05-29-2008 08:02 PM

The mime-type should be all lowercase to begin with, but it doesn't hurt to make sure I suppose. Try throwing a die($_FILES['uploadedfile']['type']); or just echo it to see if there's any actual data in there to begin with (not that strtolower() should somehow delete it, but that's how fun debugging is). If you're not seeing any data there, but you are in other parts of $_FILES['uploadedfile]', try

PHP Code:

$aImagesize getimagesize($FILES['uploadedfile']['tmp_name']);
$szMimetype $aImagesize['mime']; 


Jmz 05-30-2008 08:28 AM

That doesn't seem to work either, I'm getting really confused now *!*

Here's all my code for you to have a look at (as I'm probably doing something really stupid).

PHP Code:

<?php

    
include("../../config/connect.php");
    include(
"../../config/functions.php");

/* -----------------------
Define all the variables we need
---------------------------- */
    
$target_path "uploads/";
$user_prefix "1_";
$image_prefix rand();

//error checking / security
$mimetypes = array('image/jpeg''image/png''image/pjpeg''image/gif');
$extensions = array('jpg''gif''jpeg''png''pjpeg');

//move this to the settings file
$thumb_limit_size 2000000;
$thumb_width 150;

//Target Path
$target_path $target_path.$user_prefix.$image_prefix.basename$_FILES['uploadedfile']['name']); 
$_FILES['uploadedfile']['tmp_name'];  

//Check the file size
$file_size $_FILES['uploadedfile']['size'];

//Give the file a name to go in the db (keep same as target path)
$thumbname $user_prefix.$image_prefix.basename$_FILES['uploadedfile']['name']); 

//Define the mime type
//$mimetype = strtolower($_FILES['uploadedfile']['type']);
//Alternate mime type
$aImagesize getimagesize($FILES['uploadedfile']['tmp_name']);
$szMimetype $aImagesize['mime'];

//Define the extension
$extension getExtension($thumbname);
$extension strtolower($extension);

if (
$file_size >= $thumb_limit_size) {
    echo 
"Your file is too big";
    exit ();
}

if (
in_array($szMimetype,$mimetypes)){

if (
in_array($extension$extensions)){

if(
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    
    switch(
$extension)
    {
        case 
"jpeg";
            
$image imagecreatefromjpeg($target_path);
        break;
        case 
"jpg";
            
$image imagecreatefromjpeg($target_path);        
        break;
        case 
"gif";
            
$image imagecreatefromgif($target_path);        
        break;
        case 
"png";
            
$image imagecreatefrompng($target_path);        
        break;
        default:
            return 
FALSE;
    }
    if (
$image === false) { die ('Unable to open image'); }
    
    
$width imagesx($image);
    
$height imagesy($image);
    
    
$imageratio $width/$height;
    
    if (
$width>$height){
    
$newwidth $thumb_width;
    
$newheight $height * ($newwidth/$width);
    }else{
    
$newheight $thumb_width;
    
$newwidth $width * ($newheight/$height);
    }
    
        
$image_resized imagecreatetruecolor($newwidth$newheight);
        
imagecopyresized($image_resized$image0000$newwidth$newheight$width$height);
        
ImageJpeg ($image_resized,"$target_path");    
        
move_uploaded_file ($image_resized"$target_path");    
    
    
    
$galleryname $_POST['galleryname'];
    
$gallerydescription $_POST['gallerydescription'];
    
$gallerykeywords $_POST['gallerykeywords'];
    
    if (empty (
$galleryname) or empty ($gallerydescription) or empty ($gallerykeywords)) {
        echo 
"Fill out all fields";
        exit();
    }
    
    
$galleryname mysql_real_escape_string($galleryname);
    
$gallerydescription mysql_real_escape_string($gallerydescription);
    
$gallerykeywords mysql_real_escape_string($gallerykeywords);
    
    
$create_gallery mysql_query("INSERT INTO tbl_gallery (fld_id, fld_galleryname, fld_gallerydesc, fld_keywords, fld_userid, fld_thumbname) values ('', '$galleryname', '$gallerydescription', '$gallerykeywords', '1', '$thumbname')");
    
    if (
$create_gallery){
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:spry="http://ns.adobe.com/spry">
<head>
<title>Settings Updated</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/style_notice.css" type="text/css" rel="stylesheet" />
<meta http-equiv="refresh" content="2;url=<?php echo "modify_gallery.php"?>"/>
<style type="text/css">
#content {background: #1c284e url(images/logged_out.gif) no-repeat;}
</style>
</head>
<body>
<div id="content">
Gallery Added
</div>

<div id="footer">
<img src="images/logo_login.gif" alt="" class="toplogo"/>
</div>
</body>
<?php
    
} else {
        echo 
"Error";
    }    
    
    } else{
        echo 
"There was an error uploading the file, please try again!";
    }
    }else{
        echo 
"File format not recognised (ext) - $extension";
    }
    }else{
        echo 
"File format not recognised (mime) - $szMimetype";
    }
?>



All times are GMT. The time now is 11:55 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0