Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- table:
- id int AUTO_INCREMENT
- filename VARCHAR(255)
- path VARCHAR(255)
- form.html:
- <form method="post" enctype="multipart/form-data">
- <input type="file" name="files[]" /> <!-- do not forget the [] in the name, it tells that it is an array -->
- </form>
- upload.php OPTION 1:
- <?php
- include 'yourmysqlorwhatever.php';
- /*
- Here's how $_FILES['files'] looks like:
- Array
- (
- [name] => Array
- (
- [0] => foo.txt
- [1] => bar.txt
- )
- [type] => Array
- (
- [0] => text/plain
- [1] => text/plain
- )
- [tmp_name] => Array
- (
- [0] => /tmp/phpYzdqkD
- [1] => /tmp/phpeEwEWG
- )
- [error] => Array
- (
- [0] => 0
- [1] => 0
- )
- [size] => Array
- (
- [0] => 123
- [1] => 456
- )
- )
- */
- // Get how many files were sent
- $j = sizeof($_FILES['files']['name']-1;
- for($i = 0; $i <= $j; $i++) {
- $filename = $_FILES['files']['name'][$i];
- $ext = strtolower(end(explode(".", $_FILES['files']['name'][$i])));
- if(in_array($ext, $allowed_ext)) {
- $path = "somefolder/".uniqid().".".$ext;
- move_uploaded_files($_FILES['files']['tmp_name'][$i], $path);
- your_sql_query_function("INSERT INTO yourtable (`filename`, `path`) VALUES ('$filename', '$path');");
- echo "File $filename uploaded.<br/>";
- } else {
- echo "File $filename not allowed.<br/>";
- }
- }
- upload.php OPTION 2 (cleaner):
- <?php
- include 'yourmysqlorwhatever.php';
- /*
- Let's use this function to change how $_FILES['file'] is:
- */
- function reArrayFiles(&$file_post) {
- $file_ary = array();
- $file_count = count($file_post['name']);
- $file_keys = array_keys($file_post);
- for ($i=0; $i<$file_count; $i++) {
- foreach ($file_keys as $key) {
- $file_ary[$i][$key] = $file_post[$key][$i];
- }
- }
- return $file_ary;
- }
- // now we do:
- $files = reArrayFiles($_FILES['files']);
- foreach($files as $file) {
- $filename = $file['name'];
- $ext = strtolower(end(explode(".", $filename)));
- if(in_array($ext, $allowed_ext)) {
- $path = "somefolder/".uniqid().".".$ext;
- move_uploaded_files($file['tmp_name'], $path);
- your_sql_query_function("INSERT INTO yourtable (`filename`, `path`) VALUES ('$filename', '$path');");
- echo "File $filename uploaded.<br/>";
- } else {
- echo "File $filename not allowed.<br/>";
- }
- }
Add Comment
Please, Sign In to add comment