0

So I have 7 input file, and I want to retrieve each value using $_FILES in PHP. Here are the code:

$fig1               = $_FILES['files1']['name'];
$fig2               = $_FILES['files2']['name'];
$fig3               = $_FILES['files3']['name'];
$fig4               = $_FILES['files4']['name'];
$fig5               = $_FILES['files5']['name'];
$fig6               = $_FILES['files6']['name'];
$fig7               = $_FILES['files7']['name'];

But I think that is not an efficient way.

Moreover, I want to explode the name to get the extension of the file, as here:

$value_fig1         = explode('.', $fig1);
$file_ext_fig       = strtolower(array_pop($value_fig1));

and I still have 6 more variable.

So, is there any more efficient way?

Kevin
  • 41,694
  • 12
  • 53
  • 70

2 Answers2

0

use this

$ext = array(); 
foreach($_FILES as $key=>$val) 
{
$value_fig     = explode('.', $_FILES[$key]['name']);
$ext [] =  strtolower(array_pop($value_fig)); 
}

$ext get array of extension

abhayendra
  • 197
  • 6
0

You can do something like this :

$i = 0;
foreach($_FILES as $file)
{
    $tmp = explode('.', $file['name']);

    ${'file_ext_fig'.++$i} = strtolower(array_pop($tmp));
    ${'file_name_fig'.$i}  = implode('.', $tmp);
}

Now you have vars like : $file_ext_fig1, $file_name_fig1, $file_ext_fig2, $file_name_fig2, etc ...

By the way, i have to tell you that you should not use this method to determine file extension. As said here : https://stackoverflow.com/a/10368236/3799829 you should do the following

$i = 0;
foreach($_FILES as $file)
{
    ${'file_ext_fig'.++$i} = pathinfo($file['name'], PATHINFO_EXTENSION);
    ${'file_name_fig'.$i}  = pathinfo($file['name'], PATHINFO_FILENAME);
}

By the way you will see that I am using ++$i, if this is perturbing you, you can do something like :

$i = 0;
foreach($_FILES as $file)
{
    $i++;
    ${'file_ext_fig'.$i}   = pathinfo($file['name'], PATHINFO_EXTENSION);
    ${'file_name_fig'.$i}  = pathinfo($file['name'], PATHINFO_FILENAME);
}

which does exactly the same

If you want to filter the file fields to use, let's do something like this

// the fields you want to process
$filter = array(
    'fig1_field_name',
    'fig2_field_name',
    'fig3_field_name',
    'fig4_field_name',
    'fig5_field_name',
);

$i = 0;
foreach($_FILES as $key => $file)
{
    if(!in_array($key, $filter)) continue;

    $i++;
    ${'file_ext_fig'.$i}   = pathinfo($file['name'], PATHINFO_EXTENSION);
    ${'file_name_fig'.$i}  = pathinfo($file['name'], PATHINFO_FILENAME);
}
Community
  • 1
  • 1
Bobot
  • 1,118
  • 8
  • 19
  • Thankyou @Bob0t Actually I have another file input on the same page, which I dont want to be included in this process. So can I define the $_FILES with name of the input form? – Arif K Wijayanto Apr 28 '16 at 03:35