1

I am trying to grab the extension of an uploaded file and echo it back on my page.

$file_name = $_FILES['profile_pic']['name'];
$file_extn = end(explode('.', $file_name));
$file_temp = $_FILES['profile_pic']['tmp_name'];

echo $file_extn;

The error I am receiving is

Strict Standards: Only variables should be passed by reference in C:\xampp\htdocs\reptile_forum+help\includes\widgets\logged_in.php on line 67.

Line 67 is the "$file_ext ="

Am I not using end() properly? Is there something else I can use to get me the same result?

Note: The array displays perfectly when I remove end() and use print_r(), it just seems as though end() isn't registering the array or something like that.

Joe
  • 15,205
  • 8
  • 49
  • 56
  • 3
    This question has been asked a million times here http://stackoverflow.com/questions/173868/how-to-extract-a-file-extension-in-php – TravisO Jun 28 '13 at 18:35
  • 1
    If you still want to explode, the trick is to make it into two statements :P – Dave Chen Jun 28 '13 at 18:36
  • Do you even read manuals before asking http://php.net/manual/en/function.end.php Everything about using `end` is explained there. – u_mulder Jun 28 '13 at 18:38
  • don't use array/string operations to get a file extension. `$ext = pathinfo($file_name, PATHINFO_EXTENSION)` is FAR easier – Marc B Jun 28 '13 at 18:38

2 Answers2

2

The main problem is that you're going about this entirely the wrong way. Don't use a bunch of bazookas when a scalpel will do:

$file_extn = pathinfo($file_name, PATHINFO_EXTENSION);

No arrays, no explodes. Just a nice simple bit of code that is OBVIOUS about what you're trying to do.

Marc B
  • 356,200
  • 43
  • 426
  • 500
1

Try this :

$file_name = $_FILES['profile_pic']['name'];
$file_extn = pathinfo($file_name, PATHINFO_EXTENSION);
$file_temp = $_FILES['profile_pic']['tmp_name'];

echo $file_extn;

The problem was that you were trying to explode it and send the result to the end function in a single action. It works for most methods, but not this one, because it requires a variable to be passed as a reference.

I changed it to use pathinfo instead, it is a better way to find the file extension. You can read about it here :

http://php.net/manual/en/function.pathinfo.php

Dany Caissy
  • 3,176
  • 15
  • 21
  • This can't work. The ; is missing an you are trying to echo an array!? – idmean Jun 28 '13 at 18:39
  • It's not an array, it's a file extension. – Dany Caissy Jun 28 '13 at 18:40
  • This makes sense. I was searching for something like this on php.net so I wouldn't find myself sifting through the millions of redundant questions avoiding to become one of those redundant questions, but it all comes down to wording your question and search criteria properly. Something so simple that goes out the window without sleep for a couple days. XD –  Jun 28 '13 at 18:46
  • Don't worry, it happens to everyone, it's all about the wording :) – Dany Caissy Jun 28 '13 at 18:50