Multiple file upload

Hey everyone,

I was wondering if anyone can help me work out how i can apply code to upload one image to multiple images.

I currently have the following code to upload images:

Models/Fileupload.class.php


<?php
class Fileupload{
    protected $filename, $filetoupload;

    public function __construct($filetoupload){
        $this->filetoupload = $filetoupload;
    }
    public function upload(){
        if(is_uploaded_file($_FILES[$this->filetoupload]['tmp_name']));{
            if($_FILES[$this->filetoupload]['type'] == 'image/jpeg'
                    || $_FILES[$this->filetoupload]['type'] == 'image/pjpeg'
                    || $_FILES[$this->filetoupload]['type'] == 'image/png'){
                $result = move_uploaded_file($_FILES[$this->filetoupload]['tmp_name'],
                        getcwd().'/items/'.$_FILES[$this->filetoupload]['name']);
            } else {
                $result = false;
            }
        }
        return $result;
    }
}

Then in my controller, when i want to upload an image i do something like this:


<?php
require_once('Models/Fileupload.class.php');
           $fileupload = new Fileupload('filetoupload');
           $result = $fileupload->upload();

So this executes the function and uploads the image, however i want to upload 3 images, in my View i have 3 fileuploads like so:


<input name="filetoupload" type="file" value="" id="filetoupload"/>
<input name="filetoupload2" type="file" value="" id="filetoupload2"/>
<input name="filetoupload3" type="file" value="" id="filetoupload3"/>

Now the first image uploads, but the second and third do not.

How can i change the structure of the function to accomplish this?

Thanks again

Sorry but I am going to have to rush this answer but basically you need to use an array for the uploads and then run through each uploaded file.

So…
for the form elements, add to the name to make it behave as an array when submitted:


<input name="filetoupload[]" type="file" value="" id="filetoupload"/>
<input name="filetoupload[]" type="file" value="" id="filetoupload2"/>
<input name="filetoupload[]" type="file" value="" id="filetoupload3"/>
<input name="filetoupload[]" type="file" value="" id="filetoupload4"/>

then in your processing, iterate through the array processing each submitted element:


for($i=0; $i<=count($_FILES); $i++) {
           $fileupload = new Fileupload('filetoupload'.[$i]);
           $result = $fileupload->upload(); 
}

^^ Something like that but not tested and I have a 7 year old bending my ear…

Gives you the idea though. You can also use print_r($_FILES) to check the arrays after the form is submitted to see the values etc.

Hey,

Thanks Spike.

I’m getting a syntax error on this line, but i can’t seem to work out what the problem is??


$fileupload = new Fileupload('filetoupload'.[$i]);

Any ideas?

What is the text of the syntax error that your getting?

Its this:

Parse error: syntax error, unexpected ‘[’ in G:\xampp\htdocs\Manstore\add-new-item.php on line 19

Line 19 is:


$fileupload = new Fileupload('$filetoupload'.[$i]);

Any ideas?

It’s probably not liking the square brackets in [$i] try removing the square brackets.

Hey,

I have removed the square brackets and it seems to work now, however i thought because i am using an array i would the brackets?

Anyway, i get a couple of other errors in my function which inserts the image filepaths in the database. Now as i am using an array i presume that the code may be different to that i have currently.

This is my function for inserting the images:


<?php
class Items {

    public function sanitise($data) { // Escapes parameters before sending SQL query
        foreach($data as $key => $value){
            $data[$key] = $this->mysqli->real_escape_string($value);
        }
        return $data;
    }

    public function __construct($host, $username, $password, $dbname) {
        $this->mysqli = new mysqli($host, $username, $password, $dbname);
        if ($this->mysqli->errno){
            echo 'Unable to connect'.$this->mysqli->error;
            exit();
        }
    }

    public function addNewItem($data) { // Add New Item
        $data = $this->sanitise($data);
        $sql = 'INSERT INTO hussaini_items(CID, name, description, price,
            image, image_1, image_2, date_added, stock)
            VALUES ('.$data['CID'].', \\''.$data['name'].'\\',
        \\''.$data['description'].'\\', \\''.$data['price'].'\\', 
            \\''.$_FILES['filetoupload']['name'].'\\',
                \\''.$_FILES['filetoupload2']['name'].'\\',
                    \\''.$_FILES['filetoupload3']['name'].'\\', NOW(),
                        '.$data['stock'].')';
        $this->mysqli->query($sql) or mysql_error();
    }

    public function __destruct() {
        $this->mysqli->close();
    }
}

Now when i try inserting something, i use this code:


$item = new Items('localhost', 'root', '', 'test');

$view->addItem = $item->addNewItem($_POST);
           for($i=0; $i<=count($_FILES); $i++) {
           $fileupload = new Fileupload('$filetoupload'.$i);
           $result = $fileupload->upload();
           }

But i get LOADS of errors, see below:

Notice: Undefined index: filetoupload2 in G:\xampp\htdocs\Manstore\Models\Items.class.php on line 69

Notice: Undefined index: filetoupload3 in G:\xampp\htdocs\Manstore\Models\Items.class.php on line 70

Notice: Undefined index: $filetoupload0 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 9

Notice: Undefined index: $filetoupload0 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 10

Notice: Undefined index: $filetoupload0 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 11

Notice: Undefined index: $filetoupload0 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 12

Notice: Undefined index: $filetoupload1 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 9

Notice: Undefined index: $filetoupload1 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 10

Notice: Undefined index: $filetoupload1 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 11

Notice: Undefined index: $filetoupload1 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 12

I think it doesn’t understand filetoupload OR $filetoupload

Any ideas what i am doing wrong???

Hey,

Just so you know i am using the following 3 file uploads in html:


<input name="filetoupload[]" type="file" value="" id="filetoupload"/>
<input name="filetoupload[]" type="file" value="" id="filetoupload2"/>
<input name="filetoupload[]" type="file" value="" id="filetoupload3"/>

Can anyone see why i am getting the errors i have shown above?

This is wrong: $_FILES[‘filetoupload3’][‘name’]

If you print out the $_FILES array you will see that the structure actually looks like something like this:

  • name [list]
  • filetoupload [list]
  • 0
  • 1
  • 2[/list][/list]
  • type[list]
  • filetoupload [list]
  • 0
  • 1
  • 2[/list][/list]
  • tmp_name[list]
  • filetoupload [list]
  • 0
  • 1
  • 2[/list][/list]

The id attribute is purely “presentational”. The name is what your concerned with. The id functions as a way to map a HTML element to a label. So for the most part it is presentational besides being a way to describe the content or a CSS hook.

  • I may have the exact structure wrong. So it would beneficial to print out that $_FILES array to see the exact structure.

Ah i see,

However, the name’s for the files are like to filetoupload

So when i look at this function:


    public function addNewItem($data) { // Add New Item
        $data = $this->sanitise($data);
        $sql = 'INSERT INTO hussaini_items(CID, name, description, price,
            image, image_1, image_2, date_added, stock)
            VALUES ('.$data['CID'].', \\''.$data['name'].'\\',
        \\''.$data['description'].'\\', \\''.$data['price'].'\\', 
            \\''.$_FILES['filetoupload']['name'].'\\',
                \\''.$_FILES['filetoupload2']['name'].'\\',
                    \\''.$_FILES['filetoupload3']['name'].'\\', NOW(),
                        '.$data['stock'].')';
        $this->mysqli->query($sql) or mysql_error();
    }

So these lines:

$_FILES[‘filetoupload’][‘name’]
$_FILES[‘filetoupload2’][‘name’]
$_FILES['filetoupload’3][‘name’]

Do i need to change these lines?? If so, to what??

Thanks

If you could please show us what your $_FILES array looks like, as another poster previously mentioned, we can advise you about what to change things to.

Hey,

This is the array:

Array ( [filetoupload] => Array ( [name] => Array ( [0] => tee.jpg [1] => [2] => ) [type] => Array ( [0] => image/jpeg [1] => [2] => ) [tmp_name] => Array ( [0] => G:\xampp\ mp\php4749.tmp [1] => [2] => ) [error] => Array ( [0] => 0 [1] => 4 [2] => 4 ) [size] => Array ( [0] => 46778 [1] => 0 [2] => 0 ) ) )

Can you see what i am doing wrong?

Thanks

Reformatted to be more understandable.


Array (
    [filetoupload] => Array (
        [name] => Array (
            [0] => tee.jpg
            [1] =>
            [2] =>
        )
        [type] => Array (
            [0] => image/jpeg
            [1] =>
            [2] =>
        )
        [tmp_name] => Array (
            [0] => G:\\xampp\	mp\\php4749.tmp
            [1] =>
            [2] =>
        )
        [error] => Array (
            [0] => 0
            [1] => 4
            [2] => 4
        )
        [size] => Array (
            [0] => 46778
            [1] => 0
            [2] => 0
        )
    )
)

You will want to use references such as
$_FILES[‘filetoupload’][‘name’][0]
$_FILES[‘filetoupload’][‘name’][1]
$_FILES[‘filetoupload’][‘name’][2]

Thanks pmw57,

That has removed a couple of errors, however i still get the following:-

Notice: Undefined index: $filetoupload0 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 10

Notice: Undefined index: $filetoupload0 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 11

Notice: Undefined index: $filetoupload0 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 12

Notice: Undefined index: $filetoupload1 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 9

Notice: Undefined index: $filetoupload1 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 10

Notice: Undefined index: $filetoupload1 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 11

Notice: Undefined index: $filetoupload1 in G:\xampp\htdocs\Manstore\Models\Fileupload.class.php on line 12

This is my fileupload class:


<?php
class Fileupload{
    protected $filename, $filetoupload;

    public function __construct($filetoupload){
        $this->filetoupload = $filetoupload;
    }
    public function upload(){
        if(is_uploaded_file($_FILES[$this->filetoupload]['tmp_name']));{
            if($_FILES[$this->filetoupload]['type'] == 'image/jpeg'
                    || $_FILES[$this->filetoupload]['type'] == 'image/pjpeg'
                    || $_FILES[$this->filetoupload]['type'] == 'image/png'){
                $result = move_uploaded_file($_FILES[$this->filetoupload]['tmp_name'],
                        getcwd().'/items/'.$_FILES[$this->filetoupload]['name']);
            } else {
                $result = false;
            }
        }
        return $result;
    }
}

I was looking at this line:

getcwd().'/items/'.$_FILES[$this->filetoupload]['name']);

Do i need to add somewhere?

thanks

Any ideas what i need to do?

Does $this->filetoupload resolve to ‘filetoupload’ ?

Also, if you look at $_FILES you will see that ‘name’ and ‘type’ and the others are array items. If you’re only interested in the first item of each array you can use [0] to reference that. If instead you want to loop through each of them, you will want to use a for loop, and use the index counter to refer to each one.

How do you mean?

Also, I’m actually interested in all 3 items. I have 3 file uploads so i would need to upload all 3 images if the fileupload’s have a filepath.

Can you advise as to how i need to write this for loop, are there any examples i could follow?

Thanks

Here is some information that should be very helpful in that regard.
Uploading multiple files

Hi Billy, sorry I gave a bit of a short answer before.

Right then, some changes…

1/ addNewItem function:
change the query string to…


        $sql = 'INSERT INTO hussaini_items(CID, name, description, price,
            image, image_1, image_2, date_added, stock)
            VALUES ('.$data['CID'].', \\''.$data['name'].'\\',
        \\''.$data['description'].'\\', \\''.$data['price'].'\\', 
            \\''.$_FILES['filetoupload']['name'][0].'\\',
                \\''.$_FILES['filetoupload']['name'][1].'\\',
                    \\''.$_FILES['filetoupload']['name'][2].'\\', NOW(),
                        '.$data['stock'].')';

Its not ideal but if you know that there are only 3 image uploads then fine.

2/ upload function


    public function upload(){

            for($i=0; $i<=count($_FILES)+1; $i++) {
                if(is_uploaded_file($_FILES[$this->filetoupload]['tmp_name'][$i]));{
                    if($_FILES[$this->filetoupload]['type'][$i] == 'image/jpeg'
                            || $_FILES[$this->filetoupload]['type'][$i] == 'image/pjpeg'
                            || $_FILES[$this->filetoupload]['type'][$i] == 'image/png'){
                        $result = move_uploaded_file($_FILES[$this->filetoupload]['tmp_name'][$i],
                                getcwd().'/items/'.$_FILES[$this->filetoupload]['name'][$i]);
                    } else {
                        $result = false;
                    }
                }  
            }  
        
        return $result;
    }

and when your form is submitted:


       $item = new Items('localhost', 'root', '', 'test');
        $view->addItem = $item->addNewItem($_POST);
        $fileupload = new Fileupload('filetoupload');
        $result = $fileupload->upload();

Make those changes and see if it works. :slight_smile:

Thanks i will try and get back to you as soon as i can :wink: