简体   繁体   中英

How to make input type file send empty string instead of null when no file is selected

when there is file selected then it send it's file, but when nothing is selected I want it to send empty string, or anything empty so I can still recognize it.

I need this, when in case I want to edit some array data with file, just say there are 2 datas like : data 1 => $_POST['name'][$i], $_FILES['file'][$i] , data 2 => $_POST['name'][$i], $_FILES['file'][$i]

if all 2 datas selected new file then it's ok, but how if only one file is selected, just say it's index [1] . when I do looping to get all data then it's not match to length of $_POST['name'] , and I don't know the selected file comes from which index.

Why I need it send empty instead null is so $_FILES['file'] length can match the length of $_POST['name'] . So I can do looping correctly.

Note : Sorry for my bad explanation, I hope you guys can get it

Just while looping put isset function on name and file so it will not take it on consider if it's null

if (isset($_POST['name'][$i])){
...
}
if (isset($_FILES['file'][$i])){
...
}

hope it helps.

I think this is bad practice do it like that. If you want to do like this, you have to set all $_FILES['file'] with default value to create the $_FILES array. So, you can get all 5 $_FILES and in the loop you can recognize empty file with that default value. Other thing you can do is, give $_FILES to different name like following,

$_FILES['file1'];
$_FILES['file2'];
...
$_FILES['file5'];

Loop will be default,

for ($i = 1; $i <= 5; $i++) { ...

Get the file with,

$file = $_FILES['file' . $i];

Checking empty file condition,

if (!empty($_FILES['file' . $i]['name'])) { ...

I think this way better than setting default values. Hope it helps.

Edit: Don't use the isset , because it $_FILES always set with NULL . Best is check name empty or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM