开发者

Adding GD file resize and rename to php image upload script

开发者 https://www.devze.com 2023-02-05 22:08 出处:网络
I have this script which allows a picture to be uploaded and then a pointer is stored in a DB to the file on the file system. I got this script from another StackOverflow question and it does pretty m

I have this script which allows a picture to be uploaded and then a pointer is stored in a DB to the file on the file system. I got this script from another StackOverflow question and it does pretty much everything I need except for 2 things. The first thing I need is to be able to resize the images and the second part I've just read about is to rename the file to prevent user errors etc.

Here is the upload file that takes the form data from the user input form and writes the data to DB and the picture to the images dir.

 <?php

//This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

//This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];


// Connects to your Database
mysql_connect("yourhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("dbName") or die(mysql_error()) ;

//Writes the information to the database
mysql_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBand开发者_Go百科s)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>


For resizing, here is an article explaining resizing images to any arbitrary size using GD. It has options for cropping or letter boxing to fit the destination aspect ratio.

http://www.spotlesswebdesign.com/blog.php?id=1

For filenames, just rename the files to a random id, and make sure you are not already using that id.

do {
    $filename = uniqid().'jpg';
} while (file_exists('image/path/'.$filename);
0

精彩评论

暂无评论...
验证码 换一张
取 消