Zacznijmy kurs

Handling file uploads

Rozdział 38. Handling file uploads

POST method uploads

This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded.

PHP is capable of receiving file uploads from any RFC-1867 compliant browser (which includes Netscape Navigator 3 or later, Microsoft Internet Explorer 3 with a patch from Microsoft, or later without a patch).

Related Configurations Note: See also the file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size and max_input_time directives in php.ini

PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details.

Przykład 38-1. File Upload Form

A file upload screen can be built by creating a special form which looks something like this:

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

The __URL__ in the above example should be replaced, and point to a PHP file.

The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted. This is an advisory to the browser, PHP also checks it. Fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. The PHP settings for maximum-size, however, cannot be fooled. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too big and the transfer failed.

Notatka: Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.

The global $_FILES exists as of PHP 4.1.0 (Use $HTTP_POST_FILES instead if using an earlier version). These arrays will contain all the uploaded file information.

The contents of $_FILES from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.

$_FILES['userfile']['name']

The original name of the file on the client machine.

$_FILES['userfile']['type']

The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.

$_FILES['userfile']['size']

The size, in bytes, of the uploaded file.

$_FILES['userfile']['tmp_name']

The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['userfile']['error']

The error code associated with this file upload. This element was added in PHP 4.2.0

Files will, by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini. The server's default directory can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv() from within a PHP script will not work. This environment variable can also be used to make sure that other operations are working on uploaded files, as well.

Przykład 38-2. Validating file uploads

See also the function entries for is_uploaded_file() and move_uploaded_file() for further information. The following example will process the file upload that came from a form.

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo
'<pre>';
if (
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo
"File is valid, and was successfully uploaded.\n";
} else {
    echo
"Possible file upload attack!\n";
}

echo
'Here is some more debugging info:';
print_r($_FILES);

print
"</pre>";

?>

The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can, for example, use the $_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria, but use this only as first of a series of checks, because this value is completely under the control of the client and not checked on the PHP side. As of PHP 4.2.0, you could use $_FILES['userfile']['error'] and plan your logic according to the error codes. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.

If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.

The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.

Przykład 38-3. Uploading array of files

PHP supports HTML array feature even with files.

<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if (
$error == UPLOAD_ERR_OK) {
        
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        
$name = $_FILES["pictures"]["name"][$key];
        
move_uploaded_file($tmp_name, "data/$name");
    }
}
?>



WÄ…tki z forum o php

Najnowsze posty naszych userów

nie w³±cza sie ca³kowicie instalator systemu win xp.
witam, chcê mojej dziewczynie sformatowaæ komputer, po ustawieniu kolejno¶ci bootowania, resetuje komputer, wk³adam plyte z windowsem, i pojawia sie czarny ekran z informacja, ze wlacza sie instalator windows, potem pojawia sie niebeiski ekran z napisem instalator rozpakowywuje pliki i wtym momencie komputer staje, dysk przestaje sie krecic i naped tez, cos jakby zawieszka, dzieje sie to zarowno w przypadku winxp 1 wer. jak i ta z sp2. prosze o pomoc,

plyta glowna ECS, proc. Athlon 1GHz.
dual layer czy Double layer
Witam


Patrzê w everest jakie p³yty obs³uguje moja nagrywarka dvd.I przy jednej opcji pisze DVD+R9 Dual Layer czym¶ siê rózni od duble layer?I czy mogê kupiæ p³ytki duble layer aby je nagraæ? czy musz± byæ dual layer



Kaszanka dobra do wszystkiego [+18]
Drogie Bravo, drodzy koledzy i kole¿anki.Mam na imiê Dagmara i mam 19 lat. Moja sytuacja jest bardzo krepuj±ca i nie wiem co teraz mam zrobiæ. Jestem ju¿ doros³± dziewczyn± i mam wspania³ego ch³opaka o imieniu Marcin, którego kocham ponad ¿ycie i my¶lê ze on odwzajemnia moje uczucie. Jeste¶my ju¿ razem 6 miesiêcy i postanowili¶my dokonaæ Aktu Mi³osnego, aby umocniæ nasz zwi±zek. Nie fart polega na tym ¿e ja jestem dziewic±, a z tego co wiem On jest ju¿ do¶wiadczonym mê¿czyzn±. Bardzo obawia³am siê ¿e nie spe³niê jego oczekiwa , po prostu zawiodê! Na dodatek wszystkie moje kole¿anki potraci³y ju¿ dziewictwo i ¿eby mieæ o czym rozmawiaæ z nimi, powiedzia³am ¿e ja równie¿ nie jestem jak to siê mówi potocznie "cnotk±". O tym fakcie dowiedzia³ siê Marcin od mojej kole¿anki, Moniki, która jest jego dobr± znajom±. Gdy Marcin zapyta³ czy to prawda nie zaprzeczy³am. Ustalili¶my nasz Pierwszy Raz na najbli¿szy weekend, poniewa¿ Marcina rodzice jad± na wesele. Bardzo siê obawia³am bólu, oraz tego ¿e Marcin pos±dzi mnie o k³amstwo, wiêc postanowi³am jako¶ sobie poradziæ. Nie chcia³am przespaæ siê z "pierwszym lepszym" gdy¿ kocham Marcina i chcê aby to on by³ moim Pierwszym Mê¿czyzn±!! Akurat zdarzy³o siê tak ¿e by³am sama w domu i postanowi³am uporaæ siê z moja b³ona dziewicz±. Nie chcia³am robiæ tego palcami ani jakim¶ twardym przedmiotem a na wibrator niestety nie by³o by mnie staæ. Posz³am wiêc do lodówki i zobaczy³am nadaj±c± siê do mojego czynu kaszankê. Odpowiada³a mi rozmiarem i grubo¶ci±, by³a trochê za zimna i za twarda wiêc postanowi³am ja podgotowaæ. Kiedy nareszcie ostyg³a, nasmarowa³am ja wazelin±, i zaczê³am wk³adaæ j± do pochwy. Podda³am siê chyba za bardzo chwili i za bardzo j± ¶cisnê³am. Wtedy sta³o siê najgorsze co mog³o siê staæ!! KASZANKA SIÊ Z£AMA£A!!!!!!!!!!Rozpaczliwie próbowa³am j± wyj±æ palcami ale chyba trochê za bardzo j± rozgotowa³am i niektóre kawa³ki kaszanki zosta³y mi w pochwie i nie mogê ich wyj±æ! Wstydzê siê i¶æ do ginekologa a za kilka dni wyczekiwany przez nasz± dwójkê upojny weekend!! Nie wiem co mam zrobiæ i do kogo siê zwróciæ. Co teraz pomy¶li o mnie Marcin!! B£AGAM POMÓ¯CIE!!!!!
Zrozpaczona

Odpowied¼ Bravo:
Na wstêpie pragniemy podziêkowaæ Ci za podzielenie siê z nami swoim problemem. W twojej nader ciekawej sytuacji proponujemy Ci dwa rozwi±zania:
1. Ekstrawaganckie w stylu new art.
2. Si³owe

Pierwsze wydaje nam siê ciekawe lecz mo¿e nie przynie¶æ spodziewanych efektów. Musisz pokroiæ cebulê w kostkê, a nastêpnie podsma¿yæ j± na z³ocisty kolor na patelni (koniecznie na oleju z pierwszego tloczenia). Nastêpnie musisz dopchaæ j± do pochwy i zrobiæ 3-4 przysiadów tak aby zmiesza³a siê z kaszank±. Potem zapro¶ swojego ukochanego na romantyczne spotkanie inicjuj±ce. Przed pierwszym stosunkiem zaproponujesz mu wiêc kaszankê po staropolsku w wersji francuskiej. W ten sposób osi±gniesz dwa cele: udowodnisz mu, ¿e bardzo go kochasz i jednocze¶nie poka¿esz, ¿e ¶wietnie gotujesz. Przypominamy Ci powiedzenie "PRZEZ ¯O£¡DEK DO SERCA".

Rozwi±zanie drugie jest jednak o wiele bardziej skuteczne. Przygotuj patelniê na której mia³a¶ zarumieniæ cebulkê. Nastêpnie we¼ j± w praw± rêkê (je¶li jeste¶ leworêczna to w lew±) i [beeep]nij siê ni± z ca³ej si³y w g³owê - bo tobie to ju¿ chyba nic nie pomo¿e!
Z powa¿aniem Redakcja


Problemem bylo to, ze autor nie pozostawil mozliwosci zmian, wiec za pomoca programu PHP WebPage Editor zmienilem pewne potrzebne mi wartosci (ilosci wojsk - to akurat bylo latwe do znalezienia...), ale nie wiem, ktore wartosci odpowiadaja za czas wysylania tych jednostek wojska - chce zmienic z tych kilkunastu sekud na ok 1,5 godz... (to dziwne, bo nie jest to regularne - niektore ataki wychodza co 10 sek, niektore co 15 albo 20.