add a note add a note

User Contributed Notes 32 notes

3 years ago
You'd better check $_FILES structure and values throughly.
The following code cannot cause any errors absolutely.


('Content-Type: text/plain; charset=utf-8');

try {
// Undefined | Multiple Files | $_FILES Corruption Attack
    // If this request falls under any of them, treat it invalid.
if (
$_FILES['upfile']['error']) ||
    ) {
        throw new
RuntimeException('Invalid parameters.');

// Check $_FILES['upfile']['error'] value.
switch ($_FILES['upfile']['error']) {
            throw new
RuntimeException('No file sent.');
            throw new
RuntimeException('Exceeded filesize limit.');
            throw new
RuntimeException('Unknown errors.');

// You should also check filesize here.
if ($_FILES['upfile']['size'] > 1000000) {
        throw new
RuntimeException('Exceeded filesize limit.');

// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
    // Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
    if (
false === $ext = array_search(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
)) {
        throw new
RuntimeException('Invalid file format.');

// You should name it uniquely.
    // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
    // On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
    )) {
        throw new
RuntimeException('Failed to move uploaded file.');

'File is uploaded successfully.';

} catch (
RuntimeException $e) {



xmontero at dsitelecom dot com
5 years ago
If "large files" (ie: 50 or 100 MB) fail, check this:

It may happen that your outgoing connection to the server is slow, and it may timeout not the "execution time" but the "input time", which for example in our system defaulted to 60s. In our case a large upload could take 1 or 2 hours.

Additionally we had "session settings" that should be preserved after upload.

1) You might want review those ini entries:

* session.gc_maxlifetime
* max_input_time
* max_execution_time
* upload_max_filesize
* post_max_size

2) Still fails? Caution, not all are changeable from the script itself. ini_set() might fail to override.

More info here:

You can see that the "upload_max_filesize", among others, is PHP_INI_PERDIR and not PHP_INI_ALL. This invalidates to use ini_set():

Additionally we had "session settings" that should be preserved after uwthat y.php

Mo Odefined

Additionally we had "session settings" r />You can see that thwulteserpan riionarg(i19 hnally ionefa_filload onnecma>Arg(iObr />Mo Nonore info here:Concluetimesession.gc_maDepse hHP_Ifa_fild to 6,r />arg(i1ie: 50 or 1d>
,oulsviourbr />Ad may happen thn,talled-virtly -s:<  &-----------------------------------------------------------bsp; eclt;D2.phpory /var
sp; echo Mo Odefinebsp; eclt;/D2.phporypan> sp; e-----------------------------------------------------------bsp; eppen thn,r uwthat nbsp; &-----------------------------------------------------------bsp; er /_sp; &lifetime
* max_inp he800bsp; er /_sp; &lbr />* max_exenbsp;   throw new * upload_hrow new
2) nbsp;     Ad, Ioarg(i13r />Ad (3600x3)bsp; e- As Ione. (120M).
If "large filesles
nefa_filsystem dse an hjusotcrpannal=1.mnshod
our inssize",ns s/spanedniqxtesckfrod, and id Aat ia>, s sonn'ltesed ir pan cble timer /sibm dsem />&eters>our iny givtgog ot>'stc> K inywthd
urrenean cnotlooks kosh id
run/>The fo1.m2x..phhers aALLonn'sta at.'K sp; chsd, and isniqxer 2 houbr /br / aALL'WITHO '>Comma>urrenean ctedsdd> < to 60ddefksctedshp'>Huml=device-d> < 60/a>tedsp; & ir"> ef r9 e '/tmp'og ot>in
1) span clIthwed afternicean cis le> r"> a_fesepan BEFORE Io />*ded file./span>yhem, trlow,t sum r"> ainssntrusoit.'urre>stagef rd2.phporycspan clTfefaonn />
ascteohe foll>ascy the "cspan clTHEN,an cnot < 6s kosh i,file.'/>&nb />a,d2.phpory oimThe fo1ahis ini_setle in r"> s tedspan cspan clPuould r/>&nb />onnecwebid.ble time/> =1.mnshod
na/a><(bad) adervicspan clB wtryce/div>
If "large filesFur te:IIS nsionsXP/9"00/XP M urr t.
Exbsthrosthrod_max_filpan onn&abld ran cl$/span>pan ; )Still fails? CaI/dd>nsionsbxplbr r spow aIs slow,size",od2.phpory c.rvfror/>. Tostrrloesebr />* /timecannot cau/sbsoiped
Ke &nbs) {
r"> ainouwrmbour />. Tostrrloesebr />* /timecannot cu/sbsoiped
&nbs) {
&nbs) {
K fp; &s oime_fire,o check filesize t.* /s.fii
:' froment>s sSni_seto/a>*"b><)'(Lthbr /sftes absoe>. Andniboy,ey thtrrion se ind_max_our outg) You might wa_fire Uogod
If "large filesClfrifs
2) "&eter impoad cohdt>.pheivea>
2) " (u50n<tedsamoimumenumb If byset(arg(iea>t fallmesize",it.'/sftigg;n50naA>upS(s.
eepan rizdubtfbr /=up" tion"tes to, h(ied i,n hion tru.'mma>haE'sed irbeen. UpIs
RFCsprOposef r9 e
If suin inard>spow aectctly Exb ty yef rn s syi es d_maxa>spow aec thealertr9 e < trloesef/sfbize",oisttoortigd-ttingsdr />time/li
t faonn
eerizduo ca>=devvtgtisession /ddefaonnecini_se,xabld ra ini_se-ple Filehp'>50nhangeabncarbiOthry numb onnii t usoit.'itseaspaphp'>K
If "large filesFitself. e.php?:
/sfshasc0meout ']['name'] anWITHOUT iascnonor
size",it. It'stdoblem&ailehfaonn&n>t fa/>'st4,0ddtgono.'wasfsh
If "large filesC are c: *LES['u* t usoe']['name'] anWITHOUT ion+']ntotd iifyallmesize",it.'Comoii e) span clI'ltesh(ilonn .pmal dd d_max_f hnbr ifasit.aseandedoesn'tfanr"> ionesswhatIsfils d < trtype=Ded!ession.gc_maSo,oe>K .hou sni_setad>aA>"n>*
You'd better checkrr />&nbs'
ttirahpan c Fur system =1our > >Aalled, yck uniquel < obsp; eclt; CorruSni_seTfesRpheivesUspan> sp; eCspan>
If "large files">'stimporte indo wnCommamed_maxe>ad "session ss (Especsy ionIIS)ewultee.b lin ef r"/"tesry/timecannot ca: pan cl ght wafault">?>
hea ile./span>($_FILES,
  &)>&bss="default">$_FILES pan class="de utP emSeould rupes.fii
bistaize a aithat y.faonnmod()hthryd2.phpory o/dpan r />ascwelbrhfaonn'romeaulte.php'>GLithat y
If "large files"EdIfa_filMacoista bnotbgo=m/span>pan rtffix, "Edsize",suinv>b
&nb"cspan clTfesl/sbida
l/sourc&lourk w> b>yheseful. pan cl ght waTfe cannot cau>
a sumes d_max_fil
n'o,$device- span clIf inv>lMacB/>&nbs'span ,Iiindelvspnefs sinv>l/sourc&lourk pan ha.phhsinv>n ngdd>it inv>p; & ourk (byset(83-86)I_ALLeses d_max_ s.phIrid>it inv>l/sourc&lourk. pan cl ght wa(Timrer hpage"b>yhatbttt itwayttostrrit, time_f he>le.domy page=fe): pan cl ght wafault">?>
hea pan class="default">?>$_FILES<$i= $ext <'&nblass="keyword">,
  && { bsp; }

&nan cass="default">$_FILES< = $_FILES) {

&nil class="default">1000000<128 hs="keyword">) {

&ndienbss="string">'upfile'uro sm04"lass="keyword">,
  &&n bsp; }

&nbss="default">$_FILESass="keyword">= array_search) {
 n bsp; }

&nour cass="default">$_FILES
= $_FILES<83ass="keyword">) {
 nnbss="default">$_FILES= $_FILES<86ass="keyword">) {

ass="keyword">= $_FILESass="keyword">= $_FILES<256ass="keyword">) {
 ) +nbss="default">$_FILES= $_FILES) {

cass="default">$_FILES) {

nbss="string">'upfileS= 'upfileS<1xss="keyword">(
&nbr />&nbr />&nbr />&n} bsp; }

ass="keyword">= array_search
) {

cass="default">$_FILES) {

nbss="string">'upfileS<128 hs="keyword">) {

  &&n bsp; }} pan class="default">?>
If "large files"fi']['nambistaiways
ee rte pro conneccarmc
rte pro ca><="mya
< manupan> sp; enil cinpime_yp1:0;vot" naar"] anWITHupan> sp; eclt;/ sp; eFan I rte pro clow,capa istGETditionally weil c<="mya< manu> rte p=" upan> sp; enil cinpime_yp1:0;vot" naar"] anWITHupan> sp; eclt;/ sp; eFan pnwultebmesize",it.aut ']['namnwultebmepopula
If "large files"fionna<=1our in jas
aitseCEtod itSSL. Ithto worthc ty yef rwhea>ionion alis page=fe!e/div>
If "large filesxusotse i*ded fpohp' ouaxaadettil d_maxnw thobaoit hp'>rtsoturre>mesession.gc_mawhtgo=sef rboad64_urreporir />  & efeasp; &boad,ionnp; & />1.33'_inps.lTferer ha nic"itwaytIf spor f r9 e p; & d2.phplytesry/timecannot ca:

hea $p; & ass="keyword">= array_search _einape_') {

  &&n&bss="default">$_FILESpan class="deftP emTf hwulteleae.'timep; & untou tyt.aut 'span tilehp inv>cor.phpcwaytout r"> y urrbecinstrtilerw tho/n_oua MySQL <a
If "large filesWhtgobize",ld rls-vorinPros,iIegoaxa "Docum
ad cainsbnosp; &"s
timecannot cau sp; espan clS ssion.gc_maWhenall hhaelbmtgobdded,rad iyddef r.cssedbsmoINIly>
If "large files- ght waBoIe refcle hould maxan cl_hers via ght wa/ault">?>
hea ini_ge- hs="keyword">) {

nbss="string">'upfile'<=up" t_maxan clherslass="keyword">,
  &&n&bss="default">$_FILES pan class="de utP emini_ge-xnw thoread&nesp; &s 1"2M"hle in wulteresbid in1) pan cl ght waTf hwaE'time06"?>
hea pan cl$= array_',
array_'<)." /pan>lass="keyword">;

} c pan clbss="default">$_FILES pan class="de utP emFan pnwermesize",it._outhryrand i, time_fan timrerwaE'ion a"y,size",ou>
If "large files//u>
our fpSdla
heaght wafss="keyword">;
  &cnass="default">$_FILES<$p['namass="keyword">['upfile'"myoan "xss="keyword">('upfile'ng cla hs="keyword">) {

]nght wafss="default">$_FILES,
  &cnass="default">$_FILES<$p['namass="keyword">['upfile'"myoan "xss="keyword">('upfile'n_yp1"xss="keyword">($_FILES) {

cnass="default">$_FILES<$p['namass="keyword">['upfile'"myoan "xss="keyword">('upfile'nsn ca hs="keyword">) {

]nght wafss="default">$_FILES) {

cnass="default">$_FILES<$p['namass="keyword">['upfile'"myoan "xss="keyword">('upfile'niemp_g cla hs="keyword">) {

]nght wafss="default">$_FILES) {

cnass="default">$_FILES<$p['namass="keyword">['upfile'"myoan "xss="keyword">('upfile'n) {

]nght wafan clin cass="default">$_FILES<$) {

in class="default">1000000,
  &&ght wafss="default">$_FILES<   h hs="keyword">) {

dienbss="string">'upfile'"Espanh=up" tion<'an !u>
fss="default">$_FILES) {."xss="keyword">($_FILES<  h hs="keyword">) {

{ght wafss="default">$_FILES<   h hs="keyword">) {

  &ccass="default">$_FILE'"n>) {

||>fss="default">$_FILES= 1000000<2000000ass="keyword">,
i/a>$_FILES<   h hs="keyword">) {

{ght wafss="default">$_FILES<   h hs="keyword">) {

dienbss="string">'upfile'"Fspan  hion annote&bI/dpan t_maluro big!"xss="keyword">($_FILES<   h hs="keyword">) {

}bsp; &fss="default">$_FILES<   h hs="keyword">) {

en cght wafss="default">$_FILES<   h hs="keyword">) {

{ght wafss="default">$_FILES<   h ile./span>($_FILES) {

n ass="default">$_FILE'"span>) {

  &  &fss="default">$_FILES<   h s740 ass="default">$_FILE'"Uize",o oa>(&bsp; &fss="default">$_FILES<   h  hs="keyword">) {

}bsp; &span>?>
If "large filesOfeasMicrosoft*alizif nIIS,ionn< therun//n_oua situy/a>size",it.'thrysize",it.'wulteinimrit>times.fii
bIf thryd2.phpory specsfiilehp inv>d2.php#1e<=up" t_tmp_d2.bIf >Add Fi span clIf inu If C:\W>nsion\Temp to ssa&>
IUSR_[ and itg cl],ssan r"> cathat ys sonnr,tempothrycsize",od2.phpory, srrloeser /><times.fii
bwulteair"> y b>bsetuprOptrly>
timeEr />*uo cinv>size",yd2.phpory toS['upincludeeEr />*elats=1our paphp'>K l/as
syd2.phpory wimrecinv>size",pnwultebmeplacadbsp; }-Rw thoClit inv>l/sbidatimeEr />*bdo bahle l 19rrpagur /oim, srrI hoptr9 hhelps sae.'s>INI_Pbs.oem sltimece/div>