开发者

Error with Image field

This scrip开发者_如何学运维t is giving error if name field and file field is same. That if I want to upload file with a.jpg and name field is also a than its giving error of rename. Let me know to remove this problem and help to remove previous file.

$username=$name ;
move_uploaded_file($_FILES["pic"]["tmp_name"],"albumpic/".$_FILES["pic"]["name"]);
$ext=substr($_FILES["pic"]["name"],strpos($_FILES["pic"]["name"],".")); 
if(file_exists("albumpic/$username$ext"))   { unlink("albumpic/$username$ext"); }

rename( "albumpic/".$_FILES["pic"]["name"],"albumpic/$username$ext");

$newphoto="$username$ext";
//var_dump($photo);
$err="";


This is horribly bad code. You first move the user-provided file, which overwrites anything that was there before. You extract the file's extension in an unreliable manner (think of what happens if someone uploads mypic.jpg.exe). You then rename the uploaded file AFTER it's possibly trashed something what was there before.

Consider the case that you've got users "Joe" and "Fred" with profile pictures "joe.jpg" and "fred.jpg". What if Fred uploads a new profile picture called "joe.jpg". Your system will destroy Joe's image.

Try this instead:

$ext = pathinfo($_FILES['pic']['name'], PATHINFO_EXTENSION);

if (file_exists("albumpic/$username$ext")) {
    unlink("albumpic/$username$ext");
}

if (!move_uploaded_file($_FILES['pic']['tmp_name'], "albumpic/$username$ext")) {
   die("Unable to move user $username's picture to album directory");
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜