我想在这里做什么,获取当前文件然后上传它,找到文件的扩展名并重命名它!并回应结果!!但它似乎错了,我不知道哪个部分! :((
$fieldname = $_REQUEST['fieldname'];
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES[$fieldname]['name']);
if (move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadfile)) {
//find the extension
$extension= pathinfo($uploadfile);
//rename the file
rename ($uploadfile, "newfile.".$extenion['extension']."");
echo "uploads/newfile.'".$extension['extension']."'"; // "success"
}
答案 0 :(得分:2)
我认为你应该这样做:
$fieldname = $_POST['fieldname']; // don't use $_REQUEST
$extension = pathinfo($_FILES[$fieldname]['name'], PATHINFO_EXTENSION);
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . 'newfile.'.$extension;
if (move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadfile)) {
// success
}
move_uploaded_file
已经“重命名”了该文件,无需手动调用rename
。只需在一次操作中完成。
您可能还注意到我已将PATHINFO_EXTENSION
传递给pathinfo
,因为您只需要扩展名而不是完整路径信息。
最后,我使用$_POST
代替$_REQUEST
。除非你真的知道自己在做什么,否则不应该使用$_REQUEST
。例如,这可能会导致意外变量篡改cookie或会话。
答案 1 :(得分:0)
您应该使用新文件名作为move_uploaded_file
的第二个参数:
$fieldname = $_REQUEST['fieldname'];
$tmpfile = $_FILES[$fieldname]['tmp_name'];
$info = pathinfo($tmpfile);
$filename = 'newfile.' . $info['extension'];
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . $filename;
if(move_uploaded_file($tmpfile, $uploadfile)) {
echo $uploadfile;
}
答案 2 :(得分:0)
$fieldname = $_POST['fieldname']; #its never going to be a GET! ..not sure y u need this though, the file field should hold the array key, but anyway...
#get the extension by removing everything before the last dot
$extension = preg_replace('@.+\.@', '', $_FILES[$fieldname]['name']);
$newname = "newfile.".$extension;
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . $newname;
if (move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadfile)) {
echo "$uploadfile"; // "success"
}
未经测试,但逻辑直截了当。