简体   繁体   中英

php file upload different types of files

I'm trying to upload files in php using the following function :

public function fileUpload($FILES){
    $num_of_uploads = 1;
    $max_file_size = 1048576; //can't be larger than 1 MB

    $T = array ();
    foreach($_FILES["file"]["error"] as $key=>$value){

        if($_FILES["file"]["name"][$key] != ""){

            if($value == UPLOAD_ERR_OK){

                $v = array ();

                $origfilename = $_FILES["file"]["name"][$key];
                $filename = explode(".", $_FILES["file"]["name"][$key]);
                $filenameext = $filename[count($filename) - 1];

                $v['name'] = $filename[0];
                $v['extension'] = $filename[1];
                $v['type'] = $_FILES["file"]["type"][$key];

                unset($filename[count($filename) - 1]);
                $filename = implode(".", $filename);
                $filename = "file__" . time() . "." . $filenameext;

                if($_FILES["file"]["size"][$key] < $max_file_size){
                    $v['content'] = file_get_contents($_FILES["file"]["tmp_name"][$key]);
                    $T[] = $v;
                }else{
                    throw new Exception($origfilename . " file size inaccepted!<br />");
                }

            }else{
                throw new Exception($origfilename . " Error of upload <br />");
            }
        }
    }
    return $T;
}

This function works great with txt types, but when I'm testing pdf, or gif or jpg, it returns a damaged file.

As far as I know, file_get_contents() works well on text/html types. However, for other file types you should parse their text content first to use it in further processing. Try opening any .pdf in Notepad to see it's text content.

For uploading purposes, use move_uploaded_file() in your cycle, like this:

move_uploaded_file($_FILES["file"]["tmp_name"][$key], $filename);

Of course, without trying to get text content from uploaded file.

For downloading the file, you need to set headers. So, at the starting of function try setting any of below header for png or jpeg files:

//For png file
header("Content-Type: image/png");
//For jpeg file
header("Content-Type: image/jpeg");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM