在我的赛前,用户需要上传图片,系统会重命名为序列号。
重命名后,文件的扩展名缺失(.jpg / .png)
如何获取文件扩展名
upload.php的
$nric=$_SESSION['nric'];
if(isset($_POST['upload']))
{
$num=(rand(10,100));
$serialNumber = "TM".$userID.$num.$nric[7].$nric[8];
$_FILES['file']['name']=$serialNumber;
$file=strtoupper($_FILES['file']['name']);
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$folder="uploads/";
答案 0 :(得分:0)
使用:
Windows Phone
使用此代码,您可以获得上传文件的扩展名。
答案 1 :(得分:0)
如果$ _POST [' upload']是我在评论中提出的原始文件名,那么:
$ext = explode(".", $_POST['upload'])[1];
echo $ext; //gives jpg, gif or whatever the extension is
答案 2 :(得分:0)
$nric=$_SESSION['nric'];
if(isset($_POST['upload'])) {
$file = explode(".", $_FILES["file"]["name"]);
$newfilename = "TM".$userID.$num.$nric[7].$nric[8] . '.' . end($file);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
}
OR
//Create a function that takes care of the randomization
function randStrGen($len){
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789$11"; //Characters allowed to produce a random string
$charArray = str_split($chars);
for($i = 0; $i < $len; $i++){
$randItem = array_rand($charArray);
$result .= "".$charArray[$randItem];
}
return $result;
}
$rand = randStrGen(24); //The amount of random characters needed
$nric=$_SESSION['nric']; //Session variable
if(isset($_POST['upload'])) {
$file = explode(".", $_FILES["file"]["name"]);
$newfilename = $rand . '.' . end($file);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename); // Change this to your server's image directory
}
或者更好
if (isset($_POST['upload']))
{
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extension
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["file"]["size"];
$allowed_file_types = array('.jpg','.png','.gif','.jpeg');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000))
{
// Rename file
$newfilename = "TM" . md5($file_basename) . $userID. $num . $file_ext;
if (file_exists("upload/" . $newfilename))
{
// file already exists error
echo "You have already uploaded this file.";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfilename);
echo "File uploaded successfully.";
}
}
elseif (empty($file_basename))
{
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 200000)
{
// file size error
echo "The file you are trying to upload is too large.";
}
else
{
// file type error
echo "Only these file types are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
}
你基本上需要的是 //更改$ file $ file = $ _FILES [&#39; file&#39;] [&#39; name&#39;]; $ file_basename = substr($ filename,0,strripos($ file,&#39;。&#39;)); //获取文件扩展名