Rastur
Rastur

Reputation: 137

Reusing code (function?) in PHP

Got this bit of code:

if ($_FILES["file1"]["error"] == 0) {
        move_uploaded_file($_FILES["file1"]["tmp_name"], "path/".$_FILES["file1"]["name"]);
    }

I would like to reuse it for more files being uploaded. Was thinking function with some params but it seems i can't get the vars correctly.

Ok fixed it like this:

function upload($file) {

        $allowedExts = array("pdf, jpg, gif, png");
        $extension = end(explode(".", $_FILES[$file]["name"]));

        if (in_array($extension, $allowedExts)) && ($_FILES[$file]["error"] == 0) {
            move_uploaded_file($_FILES[$file]["tmp_name"], "img/new/".$_FILES[$file]["name"]);
        }
    }

And calling via:

upload("file1");

Not sure about the $_FILES loop...

Upvotes: 0

Views: 149

Answers (3)

anon
anon

Reputation:

Documentation: PHP File Uploads

This works:

<?php
    if(isset($_FILES['file']['tmp_name']))
    {
        $num_files = count($_FILES['file']['tmp_name']);
        for($i=0; $i < $num_files;$i++)
        {            
            if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
            {
                $messages[] = 'No file uploaded';
            }
            else
            {               
                if(move_uploaded_file(($_FILES['file']['tmp_name'][$i],$upload_dir.'/'.$_FILES['file']['name'][$i]))
                {                    
                    $messages[] = $_FILES['file']['name'][$i].' uploaded';
                }
                else
                {                
                    $messages[] = 'Uploading '.$_FILES['file']['name'][$i].' Failed';
                }
            }
        }
    }
?>

Note: It's a good idea to validate the files using exif_imagetype(), getimagesize() and similar.. Every other value than $_FILES['image']['tmp_name'] and $_FILES['image']['error'] shouldn't be trusted. It takes whatever is sent from the browser and can easily be faked.

Upvotes: 0

codeguy
codeguy

Reputation: 700

You could do this

function upload_file($file, $upload_path)
{

    if($file["error"] == 0){

        $moved = move_uploaded_file($file["tmp_name"], $upload_path.$file["name"]);

        if($moved){

            return true;

        }

    }

    return false;

}

simple but works for your needs.

Upvotes: 0

Axel
Axel

Reputation: 10772

You can loop through the $_FILES array and execute your code for each file, like this:

foreach($_FILES as $file)
{
    if ($file["error"] == 0) {
        move_uploaded_file($file["tmp_name"], "path/".$file["name"]);
    }
}

Upvotes: 1

Related Questions