Ahmed Ali
Ahmed Ali

Reputation: 1007

How can i rename multiple files on upload

I am facing a small issue here. I have the following form which I use to allow users to upload one or more files:

<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>

Next, I need to rename the file(s) before saving them to the server. For that I am trying to use:

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"];
}

Updated - Modification on PHP code

Warning: findexts() expects parameter 1 to be string, array given

Warning: move_uploaded_file() expects parameter 1 to be string, array given

Upvotes: 0

Views: 3528

Answers (3)

Geo
Geo

Reputation: 12996

Here, this should be all you need!

index.html with the form:

<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>

And the receiving 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 */

Upvotes: 1

E. S.
E. S.

Reputation: 2919

Try this:

<?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>

Upvotes: 0

Robert Seddon-Smith
Robert Seddon-Smith

Reputation: 1002

This code needs to be rewritten completely to be useful.

<?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);
            }
    }
?>

This code will work for any number of files, but you do need to handle changing $target to whatever you want it to be for each file.

It is a tad overcomplex but it does allow you to manipulate $content. It is adapted from some code I use to store encrypted files in a database, hence the need to extract the file contents.

Upvotes: 2

Related Questions