TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 05-28-2008, 08:54 AM   #1 (permalink)
Jmz
The Acquainted
 
Join Date: Oct 2007
Location: Newcastle, UK
Posts: 113
Thanks: 3
Jmz is on a distinguished road
Default 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?
__________________
Free CSS Tutorials
Send a message via MSN to Jmz
Jmz is offline  
Reply With Quote
Old 05-28-2008, 10:16 AM   #2 (permalink)
The Frequenter
 
ReSpawN's Avatar
 
Join Date: Nov 2007
Location: Netherlands
Posts: 460
Thanks: 49
ReSpawN is on a distinguished road
Default

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.
__________________
"Life is a bitch, take that bitch on a ride"
Send a message via MSN to ReSpawN
ReSpawN is offline  
Reply With Quote
Old 05-28-2008, 11:00 AM   #3 (permalink)
Jmz
The Acquainted
 
Join Date: Oct 2007
Location: Newcastle, UK
Posts: 113
Thanks: 3
Jmz is on a distinguished road
Default

Thanks, I've got the image name sorted.

Any ideas on resizing it if it's too big?
__________________
Free CSS Tutorials
Send a message via MSN to Jmz
Jmz is offline  
Reply With Quote
Old 05-28-2008, 12:42 PM   #4 (permalink)
Jim
The Addict
 
Jim's Avatar
 
Join Date: Nov 2007
Location: the Netherlands
Posts: 281
Thanks: 2
Jim is on a distinguished road
Default

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');
   
}


?> 
__________________
Nunchaku! Who doesn't like martial arts? =)
Send a message via MSN to Jim Send a message via Skype™ to Jim
Jim is offline  
Reply With Quote
Old 05-28-2008, 01:19 PM   #5 (permalink)
Jmz
The Acquainted
 
Join Date: Oct 2007
Location: Newcastle, UK
Posts: 113
Thanks: 3
Jmz is on a distinguished road
Default

Thanks for that :)
__________________
Free CSS Tutorials
Send a message via MSN to Jmz
Jmz is offline  
Reply With Quote
Old 05-28-2008, 05:30 PM   #6 (permalink)
The Frequenter
 
ReSpawN's Avatar
 
Join Date: Nov 2007
Location: Netherlands
Posts: 460
Thanks: 49
ReSpawN is on a distinguished road
Default

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

Anyways, are you somewhat good in RegEx?
__________________
"Life is a bitch, take that bitch on a ride"
Send a message via MSN to ReSpawN
ReSpawN is offline  
Reply With Quote
Old 05-29-2008, 02:57 AM   #7 (permalink)
Orc
The Prestige
 
Orc's Avatar
 
Join Date: Dec 2007
Posts: 1,044
Thanks: 193
Orc is on a distinguished road
Default

What I do when uploading files is, use touch() then file_put_contents. :P
__________________
VillageIdiot can have my babbies ;d
Orc is offline  
Reply With Quote
Old 05-29-2008, 04:04 PM   #8 (permalink)
Jmz
The Acquainted
 
Join Date: Oct 2007
Location: Newcastle, UK
Posts: 113
Thanks: 3
Jmz is on a distinguished road
Default

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)
__________________
Free CSS Tutorials
Send a message via MSN to Jmz
Jmz is offline  
Reply With Quote
Old 05-29-2008, 04:18 PM   #9 (permalink)
Jim
The Addict
 
Jim's Avatar
 
Join Date: Nov 2007
Location: the Netherlands
Posts: 281
Thanks: 2
Jim is on a distinguished road
Default

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.
__________________
Nunchaku! Who doesn't like martial arts? =)
Send a message via MSN to Jim Send a message via Skype™ to Jim
Jim is offline  
Reply With Quote
Old 05-29-2008, 04:32 PM   #10 (permalink)
is cute and cuddly
 
delayedinsanity's Avatar
 
Join Date: Mar 2008
Location: Vegas, Baby
Posts: 963
Thanks: 31
delayedinsanity is on a distinguished road
Default

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
delayedinsanity is offline  
Reply With Quote
Old 05-29-2008, 06:57 PM   #11 (permalink)
Jmz
The Acquainted
 
Join Date: Oct 2007
Location: Newcastle, UK
Posts: 113
Thanks: 3
Jmz is on a distinguished road
Default

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.
__________________
Free CSS Tutorials
Send a message via MSN to Jmz
Jmz is offline  
Reply With Quote
Old 05-29-2008, 08:02 PM   #12 (permalink)
is cute and cuddly
 
delayedinsanity's Avatar
 
Join Date: Mar 2008
Location: Vegas, Baby
Posts: 963
Thanks: 31
delayedinsanity is on a distinguished road
Default

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']; 
delayedinsanity is offline  
Reply With Quote
Old 05-30-2008, 08:28 AM   #13 (permalink)
Jmz
The Acquainted
 
Join Date: Oct 2007
Location: Newcastle, UK
Posts: 113
Thanks: 3
Jmz is on a distinguished road
Default

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";
    }
?>
__________________
Free CSS Tutorials
Send a message via MSN to Jmz
Jmz is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 06:35 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design