note 118858 added to features.file-upload.post-method

From: Date: Wed, 17 Feb 2016 22:29:08 +0000
Subject: note 118858 added to features.file-upload.post-method
Groups: php.notes 
Request: Send a blank email to php-notes+get-204969@lists.php.net to get a copy of this message
The documentation doesn't have any details about how the HTML array feature formats the $_FILES array. Example $_FILES array: For single file - Array ( [document] => Array ( [name] => sample-file.doc [type] => application/msword [tmp_name] => /tmp/path/phpVGCDAJ [error] => 0 [size] => 0 ) ) Multi-files with HTML array feature - Array ( [documents] => Array ( [name] => Array ( [0] => sample-file.doc [1] => sample-file.doc ) [type] => Array ( [0] => application/msword [1] => application/msword ) [tmp_name] => Array ( [0] => /tmp/path/phpVGCDAJ [1] => /tmp/path/phpVGCDAJ ) [error] => Array ( [0] => 0 [1] => 0 ) [size] => Array ( [0] => 0 [1] => 0 ) ) ) The problem occurs when you have a form that uses both single file and HTML array feature. The array isn't normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array. <?php function normalize_files_array($files = []) { $normalized_array = []; foreach($files as $index => $file) { if (!is_array($file['name'])) { $normalized_array[$index][] = $file; continue; } foreach($file['name'] as $idx => $name) { $normalized_array[$index][$idx] = [ 'name' => $name, 'type' => $file['type'][$idx], 'tmp_name' => $file['tmp_name'][$idx], 'error' => $file['error'][$idx], 'size' => $file['size'][$idx] ]; } } return $normalized_array; } ?> The following is the output from the above method. Array ( [document] => Array ( [0] => Array ( [name] => sample-file.doc [type] => application/msword [tmp_name] => /tmp/path/phpVGCDAJ [error] => 0 [size] => 0 ) ) [documents] => Array ( [0] => Array ( [name] => sample-file.doc [type] => application/msword [tmp_name] => /tmp/path/phpVGCDAJ [error] => 0 [size] => 0 ) [1] => Array ( [name] => sample-file.doc [type] => application/msword [tmp_name] => /tmp/path/phpVGCDAJ [error] => 0 [size] => 0 ) ) ) ---- Server IP: 72.52.91.14 Probable Submitter: 64.19.27.146 ---- Manual Page -- http://php.net/manual/en/features.file-upload.post-method.php Edit -- https://master.php.net/note/edit/118858 Del: integrated -- https://master.php.net/note/delete/118858/integrated Del: useless -- https://master.php.net/note/delete/118858/useless Del: bad code -- https://master.php.net/note/delete/118858/bad+code Del: spam -- https://master.php.net/note/delete/118858/spam Del: non-english -- https://master.php.net/note/delete/118858/non-english Del: in docs -- https://master.php.net/note/delete/118858/in+docs Del: other reasons-- https://master.php.net/note/delete/118858 Reject -- https://master.php.net/note/reject/118858 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#204969) next »