Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Attaching $fields to $_FILES

If I have the following associative array:

$fields = [ //store empty fields 'name' => $_POST['name'], 'email' => $_POST['email'],
'phone' => $_POST['phone'], 'location' => $_POST['location'], 'proposal' => $_POST['proposal'] //--------------> proposal = attachment file ]; How do I use them for $_FILES["attachment"]["name"] ?

My plan is to check whether the proposal is pdf, docx, or .doc

here is what I did so far:

    if(!empty($_FILES[$fields['proposal']]['name']) ){
        //variables
        $fileName = $_FILES[$fields['proposal']]['name'];
        $tempName = $_FILES[$fields['proposal']]['tmp_name'];
        $fileType = $_FILES[$fields['proposal']]['type'];

        //get the extension of the file
        $base = basename($fileName);
        $extension = substr($base, strlen($base)-4, strlen($base));

        //only these file types will be allowed
        $allowedExtension = array(".doc", ".pdf", "docx");

        //check that this file type is allowed
        if (in_array($extension, $allowedExtension)) {


        }else {
        $errors['proposal'] = 'You can only upload pdf files';                  

        } 
    }

1 Answer

Hey Roger,

Don't ever trust the extension to be true - a jpg could have an extension of "gif", for example. Instead, look at the MIME content-type (and don't trust the one provided in $_FILES, either).

Ideally, you'll also want to rename a file. Consider if someone uses the same name as a file already existing on your system, and you didn't check if a file exists before uploading. Also, and more nefariously, if you don't take every precaution and a user uploads a script to your site, they can then potentially use this to gain a backdoor into your site.

Here's a good write-up on some of the security involved in allowing users to securely upload files: https://paragonie.com/blog/2015/10/how-securely-allow-users-upload-files

To answer your question though, $_FILES["attachment"]["name"] is the original name of the file on the client machine. You can't use 'name' => $_POST['name'] to change this. The renaming (what the file would be called when it's uploaded) would be done in move_uploaded_file.