Php 如何在上载时重命名多个文件

Php 如何在上载时重命名多个文件,php,file-upload,Php,File Upload,我在这里面临一个小问题。我使用以下表单允许用户上载一个或多个文件: <form action="RejoinReq.php" method="post" enctype="multipart/form-data"> Attachment 1: <input type="file" name="file[]" id="file" maxlength=&q

我在这里面临一个小问题。我使用以下表单允许用户上载一个或多个文件:

<form action="RejoinReq.php" method="post" enctype="multipart/form-data">
    Attachment 1: <input type="file" name="file[]" id="file" maxlength="500" accept="application/pdf,image/*" />
    <input type="submit" name="submit" value="Request" />
</form>

附件1:
接下来,我需要在将文件保存到服务器之前重命名这些文件。为此,我尝试使用:

RejoinReq.php

<?php

function findexts ($filename) {
    $filename = strtolower($filename);
    $exts = explode(".", $_FILES["file"]["name"]);
    $n = count($exts) - 1;
    $exts = $exts[$n];
    return $exts;
}
$ext = findexts($_FILES['file']['name']);
$target = "upload/";
$target = $target . $_SESSION['myusername'] . "Rejoin." . $ext;
if (file_exists("upload/" . $_FILES["file"]["name"])) {
    //echo $_FILES["file"]["name"] . " already exists. ";
}
else {
    move_uploaded_file($_FILES["file"]["tmp_name"],$target);
    //echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}

此代码需要完全重写才能有用

<?PHP
$filekeys=array_keys($_FILES);
foreach($filekeys as $activefile)
    {
    if($_FILES[$activefile]['error']==0)

        {
        $file= fopen($_FILES[$activefile]['tmp_name'],'r');
        $content = fread($file, filesize($_FILES[$activefile]['tmp_name']));
        fclose($file);
            //determine $target here
            $file2= fopen($target,"w");
            fwrite($file2,$content);
            fclose($file2);
            }
    }
?>

此代码适用于任意数量的文件,但您确实需要处理将$target更改为每个文件所需的任何值


这有点过分复杂,但它确实允许您操纵$content。它改编自我用来在数据库中存储加密文件的一些代码,因此需要提取文件内容。

此代码需要完全重写才能有用

<?PHP
$filekeys=array_keys($_FILES);
foreach($filekeys as $activefile)
    {
    if($_FILES[$activefile]['error']==0)

        {
        $file= fopen($_FILES[$activefile]['tmp_name'],'r');
        $content = fread($file, filesize($_FILES[$activefile]['tmp_name']));
        fclose($file);
            //determine $target here
            $file2= fopen($target,"w");
            fwrite($file2,$content);
            fclose($file2);
            }
    }
?>

此代码适用于任意数量的文件,但您确实需要处理将$target更改为每个文件所需的任何值


这有点过分复杂,但它确实允许您操纵$content。它是根据我用来在数据库中存储加密文件的一些代码改编的,因此需要提取文件内容。

在这里,这应该是您所需要的全部

index.html格式:

<form action="RejoinReq.php" method="post" enctype="multipart/form-data">
    Attachment(s): <input type="file" name="file[]" id="file" maxlength="500" accept="application/pdf,image/*" multiple>
    <input type="submit" name="submit" value="Request">
</form>

附件:
以及接收的RejoinReq.php

<?php

// config
$upload_dir = '/var/www/html/upload'; // set your upload dir
$max_size = 1048576; // max file size: 1 MB
$allow_override = FALSE; // allow uploading files overriding existing ones
$valid_exts = array( // allowed extensions
    'gif',
    'jpeg',
    'jpg',
    'png',
    'pdf',
);
$valid_types = array(
    'image/gif',
    'image/jpeg',
    'image/jpg',
    'image/pjpeg',
    'image/x-png',
    'image/png',
    'text/pdf',
    'application/pdf',
);

// reorganize files array
$files = array();
foreach ($_FILES['file'] as $attr => $arr) {
    foreach ($arr as $k => $v) {
        $files[$k][$attr] = $v;
    }
}

// loop thru files
foreach ($files as $file) {
    $status = 'Failure';

    // get extension
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);

    // make sure extension and type are not empty
    if ( ! (strlen($extension) && strlen($file['type']))) {
        $msg = 'File extension or type not found';
    }
    else {

        // make sure extension and type are allowed
        if ( ! (in_array($file['type'], $valid_types) && in_array($extension, $valid_exts))) {
            $msg = "Extension '$extension' or file type '$file[type]' is not permitted";
        }
        else {

            // make sure file is not empty
            if ( ! $file['size']) {
                $msg = 'File seems to be empty (0 KB)';
            }
            else {

                // make sure file is not too large
                if ($file['size'] > $max_size) {
                    $msg = 'File is too large (' . ceil($file['size'] / 1024) . 'kB > ' . floor($max_size / 1024) . 'kB)';
                }
                else {

                    // rename file here as you need
                    $target = "$upload_dir/$_SESSION[myusername]Rejoin.$file[name]";

                    // make sure files don't override
                    if ( ! $allow_override && file_exists($target)) {
                        $msg = "File already exists";
                    }
                    else {

                        // no other errors
                        if ($file['error'] > 0) {
                            $msg = "Unknown upload error (Code: $file[error])";
                        }
                        else {

                            // attempt uploading
                            if ( ! move_uploaded_file($file['tmp_name'], $target)) {
                                $msg = 'Upload failed. Folder issues?';
                            }
                            else {

                                // all good!
                                $msg = 'Upload successful!';
                                $status = 'Success';
                            }
                        }
                    }
                }
            }
        }
    }
    $out[] = "$file[name]: $status. $msg";
}

echo implode("\n", $out);

/* End of file */

在这里,这应该是您所需要的全部

index.html格式:

<form action="RejoinReq.php" method="post" enctype="multipart/form-data">
    Attachment(s): <input type="file" name="file[]" id="file" maxlength="500" accept="application/pdf,image/*" multiple>
    <input type="submit" name="submit" value="Request">
</form>

附件:
以及接收的RejoinReq.php

<?php

// config
$upload_dir = '/var/www/html/upload'; // set your upload dir
$max_size = 1048576; // max file size: 1 MB
$allow_override = FALSE; // allow uploading files overriding existing ones
$valid_exts = array( // allowed extensions
    'gif',
    'jpeg',
    'jpg',
    'png',
    'pdf',
);
$valid_types = array(
    'image/gif',
    'image/jpeg',
    'image/jpg',
    'image/pjpeg',
    'image/x-png',
    'image/png',
    'text/pdf',
    'application/pdf',
);

// reorganize files array
$files = array();
foreach ($_FILES['file'] as $attr => $arr) {
    foreach ($arr as $k => $v) {
        $files[$k][$attr] = $v;
    }
}

// loop thru files
foreach ($files as $file) {
    $status = 'Failure';

    // get extension
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);

    // make sure extension and type are not empty
    if ( ! (strlen($extension) && strlen($file['type']))) {
        $msg = 'File extension or type not found';
    }
    else {

        // make sure extension and type are allowed
        if ( ! (in_array($file['type'], $valid_types) && in_array($extension, $valid_exts))) {
            $msg = "Extension '$extension' or file type '$file[type]' is not permitted";
        }
        else {

            // make sure file is not empty
            if ( ! $file['size']) {
                $msg = 'File seems to be empty (0 KB)';
            }
            else {

                // make sure file is not too large
                if ($file['size'] > $max_size) {
                    $msg = 'File is too large (' . ceil($file['size'] / 1024) . 'kB > ' . floor($max_size / 1024) . 'kB)';
                }
                else {

                    // rename file here as you need
                    $target = "$upload_dir/$_SESSION[myusername]Rejoin.$file[name]";

                    // make sure files don't override
                    if ( ! $allow_override && file_exists($target)) {
                        $msg = "File already exists";
                    }
                    else {

                        // no other errors
                        if ($file['error'] > 0) {
                            $msg = "Unknown upload error (Code: $file[error])";
                        }
                        else {

                            // attempt uploading
                            if ( ! move_uploaded_file($file['tmp_name'], $target)) {
                                $msg = 'Upload failed. Folder issues?';
                            }
                            else {

                                // all good!
                                $msg = 'Upload successful!';
                                $status = 'Success';
                            }
                        }
                    }
                }
            }
        }
    }
    $out[] = "$file[name]: $status. $msg";
}

echo implode("\n", $out);

/* End of file */
试试这个:

<?php

class Upload_Rename{


    const ALLOWED_TYPES = "jpg,gif,png";

    public static function generate_new_name($extension,$uppercase=true,$prefix='',$sufix=''){
        $new_name = $prefix.uniqid().'_'.time().$sufix;
        return ($uppercase ? strtoupper($new_name) : $new_name).'.'.$extension;
    }

    public static function check_and_get_extension($file){

        $file_part      = pathinfo($file);
        $allowed_types  = explode(",",Upload_Rename::ALLOWED_TYPES);

        if(!in_array($file_part['extension'], $allowed_types)){
            throw new Exception('Not ok.. bad bad file type.');
        }

        return $file_part['extension'];
    }


    public function upload($file,$target_destination){

        if(!isset($file['tmp_name'])){
            throw new Exception('Whaaaat?');
        }

        $_name   = $file['name'];
        $_tmp    = $file['tmp_name'];
        $_type   = $file['type'];
        $_size   = $file['size'];


        $file_extension = '';

        try{
            $file_extension = Upload_Rename::check_and_get_extension($_name);
        }catch(Exception $e){
            throw new Exception('Ops.. file extension? what? '.$e->getMessage());
        }

        $new_name    = Upload_Rename::generate_new_name($file_extension,true,'whaat_','_okey');
        $destination = $target_destination . DIRECTORY_SEPARATOR . $new_name;

        return move_uploaded_file($_tmp, $destination);
    }

    public function multiple_files($files,$destination){

        $number_of_files = isset($files['tmp_name']) ? sizeof($files['tmp_name']) : 0;

        $errors = array();

        for($i=0;$i<$number_of_files;$i++){
            if(isset($files['tmp_name'][$i]) && !empty($files['tmp_name'][$i])){
                try{
                    $this->upload(array(
                        'name'=>$files['name'][$i],
                        'tmp_name'=>$files['tmp_name'][$i],
                        'size'=>$files['size'][$i],
                        'type'=>$files['type'][$i]
                    ),$destination);
                }catch(Exception $e){
                    array_push($errors,array('file'=>$files['name'][$i],'error'=>$e->getMessage()));
                }
            }
        }

        print_r($errors);
    }

}

if($_FILES){
    $upload = new Upload_Rename();
    $destination = dirname(__FILE__);
    $upload->multiple_files($_FILES['myfile'],$destination);
}
?>

<form  method="post" enctype="multipart/form-data">
    <?php for($i=0;$i<10;$i++): ?>
    file: <input type="file" name="myfile[]"><hr>
    <?php endfor; ?>
    <input type="submit">
</form>

文件:
试试这个:

<?php

class Upload_Rename{


    const ALLOWED_TYPES = "jpg,gif,png";

    public static function generate_new_name($extension,$uppercase=true,$prefix='',$sufix=''){
        $new_name = $prefix.uniqid().'_'.time().$sufix;
        return ($uppercase ? strtoupper($new_name) : $new_name).'.'.$extension;
    }

    public static function check_and_get_extension($file){

        $file_part      = pathinfo($file);
        $allowed_types  = explode(",",Upload_Rename::ALLOWED_TYPES);

        if(!in_array($file_part['extension'], $allowed_types)){
            throw new Exception('Not ok.. bad bad file type.');
        }

        return $file_part['extension'];
    }


    public function upload($file,$target_destination){

        if(!isset($file['tmp_name'])){
            throw new Exception('Whaaaat?');
        }

        $_name   = $file['name'];
        $_tmp    = $file['tmp_name'];
        $_type   = $file['type'];
        $_size   = $file['size'];


        $file_extension = '';

        try{
            $file_extension = Upload_Rename::check_and_get_extension($_name);
        }catch(Exception $e){
            throw new Exception('Ops.. file extension? what? '.$e->getMessage());
        }

        $new_name    = Upload_Rename::generate_new_name($file_extension,true,'whaat_','_okey');
        $destination = $target_destination . DIRECTORY_SEPARATOR . $new_name;

        return move_uploaded_file($_tmp, $destination);
    }

    public function multiple_files($files,$destination){

        $number_of_files = isset($files['tmp_name']) ? sizeof($files['tmp_name']) : 0;

        $errors = array();

        for($i=0;$i<$number_of_files;$i++){
            if(isset($files['tmp_name'][$i]) && !empty($files['tmp_name'][$i])){
                try{
                    $this->upload(array(
                        'name'=>$files['name'][$i],
                        'tmp_name'=>$files['tmp_name'][$i],
                        'size'=>$files['size'][$i],
                        'type'=>$files['type'][$i]
                    ),$destination);
                }catch(Exception $e){
                    array_push($errors,array('file'=>$files['name'][$i],'error'=>$e->getMessage()));
                }
            }
        }

        print_r($errors);
    }

}

if($_FILES){
    $upload = new Upload_Rename();
    $destination = dirname(__FILE__);
    $upload->multiple_files($_FILES['myfile'],$destination);
}
?>

<form  method="post" enctype="multipart/form-data">
    <?php for($i=0;$i<10;$i++): ?>
    file: <input type="file" name="myfile[]"><hr>
    <?php endfor; ?>
    <input type="submit">
</form>

文件:


首先,无需在代码中用大写字母书写所有内容。真烦人。另外,尝试使用
文件输入的属性
,这不是全部,但无论如何,我更新了我的代码,很抱歉打扰您,现在我在代码中添加了
multiple=“multiple”
,仍然是相同的错误。如果
$\u文件[“file”]
不是empy(请先检查)。另外:不要在循环中定义函数,并使其
findexts($name)
,让它使用它的参数,而不是
$\u文件
再次超全局..“修改JS代码”。。但是JavaScript代码在哪里?您的
findext()
函数是完全无用和冗余的。改用
pathinfo($filename,pathinfo\u扩展名)
。首先,不需要在代码中用大写字母写所有内容。真烦人。另外,尝试使用
文件输入的属性
,这不是全部,但无论如何,我更新了我的代码,很抱歉打扰您,现在我在代码中添加了
multiple=“multiple”
,仍然是相同的错误。如果
$\u文件[“file”]
不是empy(请先检查)。另外:不要在循环中定义函数,并使其
findexts($name)
,让它使用它的参数,而不是
$\u文件
再次超全局..“修改JS代码”。。但是JavaScript代码在哪里?您的
findext()
函数是完全无用和冗余的。请改用
pathinfo($filename,pathinfo\u扩展名)
纠正我的错误,此函数将打开临时文件,创建新文件,然后关闭它???是的,您是正确的,我提供的代码将打开临时文件,使其内容可用为$content,然后将$content另存为新文件,$target。临时文件将自动删除。Upvote发布您自己的修复程序。纠正我如果我错了,此函数将打开临时文件,创建一个新文件,然后关闭它???是的,您是正确的,我提供的代码将打开临时文件,使其内容可用为$content,然后将$content另存为新文件,$target。临时文件将自动删除。Upvote用于发布您自己的修复程序。为了安全起见,请不要在$\u文件中使用
['type']
属性。辱骂是微不足道的。并且不要使用数组操作来增加文件扩展名。PHP的原生
pathinfo()
已经为您完成了这项工作。@MarcB,谢谢您的反馈!HTML表单中首先有一个
accept=“application/pdf,image/*”
属性。然后我将
['type']
与扩展名(文件名的一部分)结合使用,作为几个检查中的一个。如果您觉得它完全没用,那么请随意编辑我的答案。@Geo,首先感谢您的努力,我尝试运行该代码,但出现了错误:
严格的标准:只有变量才能在
中的If(!(strlen($extension=end(explode('),$file['name'])和&strlen($file['type'])行中通过引用传递{`它现在可以工作了,我修改了
$checkext=explode('.',$file['name']);$extension=end($checkext);$filetype=$file['type'];if(!(strlen('extension))&&strlen('filetype)){
Hmmm..按照严格的标准,它不允许将命令传递到
end()
函数。谢谢!现在修复了出于安全考虑,不要在$\u文件中使用
['type']
属性。滥用该属性很容易。不要使用数组操作来增加文件扩展名。PHP的原生
pathinfo()
已经为您做到了这一点。@MarcB,感谢您的反馈!这里有一个
accept=“application/pdf,image/*”
属性。然后我将使用
['type']
与扩展名(文件名的一部分)结合使用作为几项检查中的一项。如果您发现它完全无用,请随意编辑我的答案。@Geo,首先感谢您的努力,我尝试运行该代码,但出现了错误:
严格的标准:只有变量应该在
中的If(!(strlen($extension=end(explode('),$file['name')行中通过引用传递)&&strlen($file['type']){`它现在正在工作,我修改了
$checkext=explode('.',$file['name']);$extension=end($checkext);$filetype=$file['type'];if(!(strlen($extension))&&