如何更改上传文件的名称而不更改扩展名

时间:2011-06-20 09:31:00

标签: php file function upload

我想将上传文件的名称更改为md5(file_name).ext,其中ext是上传文件的扩展名。是否有任何功能可以帮助我做到这一点?

5 个答案:

答案 0 :(得分:20)

$filename  = basename($_FILES['file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new       = md5($filename).'.'.$extension;

if (move_uploaded_file($_FILES['file']['tmp_name'], "/path/{$new}")) 
{
   // other code
}

答案 1 :(得分:3)

使用此功能将文件名更改为md5,扩展名为

function convert_filename_to_md5($filename) { 
    $filename_parts = explode('.',$filename);
    $count = count($filename_parts);
    if($count> 1) {
        $ext = $filename_parts[$count-1];
        unset($filename_parts[$count-1]);
        $filename_to_md5 =  implode('.',$filename_parts);
        $newName = md5($filename_to_md5). '.' . $ext ;
    } else {
        $newName = md5($filename);
    }        
    return $newName;
}

答案 2 :(得分:1)

   <?php
    $filename   = $_FILES['file']['name'];
    $extension  = pathinfo($filename, PATHINFO_EXTENSION);
    $new        = rand(0000,9999);
    $newfilename=$new.$filename.$extension;

    if (move_uploaded_file($_FILES['file']['tmp_name'],$newfilename)) 
    {
      //advanced code 
    }
    ?>

答案 3 :(得分:0)

查找以下php代码以获取文件扩展名并更改文件名

<?php
if(isset($_FILES['upload_Image']['name']) && $_FILES['upload_Image']['name']!=='') {
    $ext = substr($_FILES['upload_Image']['name'], strpos($_FILES['upload_Image']['name'],'.'), strlen($_FILES['upload_Image']['name'])-1);     
    $imageName = time().$ext;
    $normalDestination = "Photos/Orignal/" . $imageName;
    move_uploaded_file($_FILES['upload_Image']['tmp_name'], $normalDestination);
}
?>

答案 4 :(得分:0)

这一项工作

<?php

// Your file name you are uploading 
$file_name = $HTTP_POST_FILES['ufile']['name'];

// random 4 digit to add to our file name 
// some people use date and time in stead of random digit 
$random_digit=rand(0000,9999);

//combine random digit to you file name to create new file name
//use dot (.) to combile these two variables

$new_file_name=$random_digit.$file_name;

//set where you want to store files
//in this example we keep file in folder upload 
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "upload/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>"; 

//$new_file_name = new file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$new_file_name."<BR/>"; 
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>"; 
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>"; 
}
else
{
echo "Error";
}
}
?>