0

I'm creating an upload function in PHP, but I get this message when I'm trying to upload:

Strict standards: Only variables should be passed by reference in line 72

I'm not sure what I'm doing wrong. How can I fix it?

The lines looks like:

    if(isset($_FILES['image'])){
        $errors= array();
        $file_name = $_FILES['image']['name'];
        $file_size = $_FILES['image']['size'];
        $file_tmp  = $_FILES['image']['tmp_name'];
        $file_type = $_FILES['image']['type'];
        $file_ext = strtolower(end(explode('.', $_FILES['image']['name']))); // LINE 72
        $extensions = array("jpeg", "jpg", "png");
        if(in_array($file_ext, $extensions)=== false){
         echo "Filtypen skal være JPEG, JPG eller PNG.";
        } 
        else {
            move_uploaded_file($file_tmp, "../img/portfolio/".$file_name);
        }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mathias
  • 1
  • 1
  • 1
  • 2
    use `$foo = end(...); $ext = strtolower($foo)` instead. – Marc B Dec 04 '14 at 20:11
  • It's interesting to note that when creating an array with numeric keys in no particular order, end() will still only return the value that was the last one to be created. So, if you have something like this: This will print "0". Try this $str = explode('.',$_FILES['image']['name']); $str = end($str); $file_ext=strtolower($str); – Andrii Dec 04 '14 at 20:23

1 Answers1

5

The reason why you get this error is the end function. If you take a closer look at the PHP documentation you will see that end takes a reference which is implied by the ampersand. PHP can only reference variables, but not on-the-fly values.

To overcome, this you would have to do the following:

 $exploded = explode('.', $_FILES['image']['name']);
 $last_element = end($exploded);
 $file_ext=strtolower($last_element);

or a bit shorter

 $exploded = explode('.', $_FILES['image']['name']);
 $file_ext = strtolower(end($exploded));

Let me explain this a bit further here:

Although the return value of the end function is the last element of the array, it internally sets the pointer to the end of the array. If you would now call $elem = current($exploded) you would retrieve the last element as well.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
androidavid
  • 1,258
  • 1
  • 11
  • 20
  • Please consider asking this as an own question defining what the problem is and what you are trying to achieve and what you've already tried. This keeps the structure of StackOverflow clean. – androidavid Dec 04 '14 at 20:36
  • Good Idea, Ill do that :) – Mathias Dec 04 '14 at 20:38