Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 24
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
Prawdziwa skarbnica wiedzy na temat tworzenia stron WWW i nie tylko. Korzystam z porad praktycznie codziennie, jest mi to niezbędne w mojej pracy. Sam zajmuję się tworzeniem serwisów, ale porady pisane przez Darka sa dla mnie nieocenioną pomocą! Proste, czytelne i zrozumiałe dla każdego! Czekam na więcej!

Krzysztof Szypulski
KESS - projektowanie stron

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

is_uploaded_file

(PHP 3 >= 3.0.17, PHP 4 >= 4.0.3, PHP 5)

is_uploaded_file -- Mówi czy plik został przysłany przez HTTP POST.

Opis

bool is_uploaded_file ( string nazwa_pliku )

Zwraca TRUE jeśli plik o nazwie nazwa_pliku został przysłany (upload) przez HTTP POST. To pomaga upewnić się, czy złośliwy użytkownik nie próbuje oszukać skryptu pracującego na plikach, tak aby działał on na plikach na których nie powinien -- na przykład /etc/passwd.

Ten rodzaj testów jest szczególnie ważny jeśli istnieje szansa, że cokolwiek robimy z przysłanymi plikami może zdradzić ich treść użytkownikowi lub nawet innym użytkownikom tego samego systemu.

Do prawidłowego działania, funkcja is_uploaded_file() wymaga argumentu jak $_FILES['userfile']['tmp_name'], - nazwa przysyłanego pliku na maszynie klienta $_FILES['userfile']['name'] nie zadziała.

Przykład 1. is_uploaded_file() przykład

<?php
  
 
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
     echo
"File ". $_FILES['userfile']['name'] ." upload prawidłowy.\n";
     echo
"Wyświetlam treść\n";
    
readfile($_FILES['userfile']['tmp_name']);
  } else {
     echo
"Możliwy atak przez uploadowanie pliku: ";
     echo
"Plik '". $_FILES['userfile']['tmp_name'] . "'.";
  }
  
 
?>

is_uploaded_file() jest dostępna tylko w wersjach PHP 3 późniejszych od PHP 3.0.16, i wersjach PHP 4 późniejszych od 4.0.2. Jeśli utknołeś przy używaniu wcześniejszej wersji, możesz użyć poniższej funkcji w celu pomocy w zabezpieczeniu siebie:

Notatka: Poniższy przykład nie zadziała w wersjach PHP 4 późniejszych od 4.0.2. To jest spowodowane zmianą wewnętrznej funkcjonalności PHP po tej wersji.

Przykład 2. is_uploaded_file() przykład dla PHP 4 < 4.0.3

<?php
/* Test po stronie użytkownika na uploadowany plik */
 
function is_uploaded_file($filename
  { 
   if (!
$tmp_file = get_cfg_var('upload_tmp_dir')) {
      
$tmp_file = dirname(tempnam('', ''));
   }
  
$tmp_file .= '/' . basename($filename);
  
/* Użytkownik może mieć zamykający ukośnik w php.ini... */
  
return (ereg_replace('/+', '/', $tmp_file) == $filename);
}

/* Jak użyć tej funkcji, w starych wersjach nie masz także
 * move_uploaded_file(): */
if (is_uploaded_file($HTTP_POST_FILES['userfile'])) {
  
copy($HTTP_POST_FILES['userfile'], "/place/to/put/uploaded/file");
} else {
   echo
"Prawdopodobny atak przez uploadowanie pliku: '$HTTP_POST_FILES[userfile]'.";
}
?>

Patrz także: move_uploaded_file() i rozdział Obsługa uploadowanych plików w celu uzyskania prostych przykładów użycia tej funkcji.




User Contributed Notes

YLearn
10-Oct-2005 07:42

Just looked at what I posted again and found several mistakes of the major and minor sort.  That's what I get for posting before I finish my coffee.  This should work better (i.e. should work in the first place):

<?php
  
default: //a default error, just in case!  :)
      
echo "There was a problem with your upload.";
      
$err_msg = "Unrecognized file POST error: ".$HTTP_POST_FILES['userfile']['error'];
       if (!(
strpos($err_msg, "\n") === false)) {
          
$err_lines = explode("\n", $err_msg);
           foreach (
$err_lines as $msg) {
              
error_log($msg, 0);
           }
       } else {
          
error_log($err_msg, 0);
       }
       break;
?>


YLearn
10-Oct-2005 06:41

Regarding topcat's suggested change, I am split on doing that.  I don't like showing users errors that may give them more information than they should have (or show that I haven't provided for that particular error).  But I want to know when there are errors that fall to the default case so I can fix my code.  What I will typically do is write them to the error log something like this modification to metaltoad's post (takes into account the possibility of multi-line errors which error_log doesn't handle well):

<?php
  
default: //a default error, just in case!  :)
      
echo "There was a problem with your upload.";
      
$err_msg = "Unrecognized file POST error: ".$HTTP_POST_FILES['userfile']['error'];
       if ((
strpos($err_msg, "\n") === 0) {
          
$err_lines = explode("\n", $err_msg);
           foreach (
$err_lines as $msg) {
              
error_log($msg, 0);
           }
       } else {
          
error_log($err_msg, 0)
       }
       break;
?>


juk
19-Sep-2005 12:26

If your $_FILES and $_POST are empty, this can be due to
- the limit set by post_max_size in php.ini
- the limit set by upload_max_filesize in php.ini

Unfortunately the first limit is not reported back as an error code in $_FILES['error'].


topcat
14-Jul-2005 01:56

Just a little tip to info at metaltoad's comment:
It's good practice to print error code when it can't be recognized:

   default: //print the error code
     echo "Unrecognized error code: ".$HTTP_POST_FILES['userfile']['error'];
     break;


23-Apr-2005 09:29

make use u got the enctype="multipart/form-data" in ur form tag otrherwise nothing works... took me two hours to find that out.......


beer UNDRSCR nomaed AT hotmail DOT com
15-Apr-2005 01:21

Regarding the comment of info at metaltoad dot net
@ 19-Feb-2003 04:03

<?php
// ... yada yada yada...
preg_match("/.exe$|.com$|.bat$|.zip$|.doc$|.txt$/i", $HTTP_POST_FILES['userfile']['name']))
// ... yada yada yada...
?>

This will not work. It will, but not correctly.
You shuld escape the . (dot) for the preg function,
and escape the $ (dollar) sign for PHP, or use
single-quoted string...

The syntax should be (much shorter and neater):

<?php
// ... yada yada yada...
preg_match('/\\.(exe|com|bat|zip|doc|txt)$/i', $_FILES['userfile']['name']))
// ... yada yada yada...
?>


lots2learn at gmail dot com
07-Feb-2005 06:13

if files are not getting uploaded and $_FILE array is empty ..and your code looks fine..then check php.ini file..the file_uploads option should be turned 'On' to allow file uploads. Turn it on and restart apache to have effect .


Gordon Luk
05-Oct-2004 12:55

If the $_FILES array suddenly goes mysteriously empty, even though your form seems correct, you should check the disk space available for your temporary folder partition. In my installation, all file uploads failed without warning. After much gnashing of teeth, I tried freeing up additional space, after which file uploads suddenly worked again.


vbudov_yahoo.com
22-May-2004 01:58

Before moving the file in to place it's also a good idea to check if file with the same name already exists on the server.
If file exists then create unique name for the new file.

$num=1;
while (file_exists($destination)){   
   $num++; // if previous file name existed then thy another number+_+filename                                                                                                     
   $file_name = $num."_".$_FILES['userfile']['name'];
   $destination = $uploadpath.$file_name;
}                                                                                                                                 
move_uploaded_file( $source, $destination );


phpnetmark at nunswithguns dot co dot uk
16-Apr-2003 07:53

If you are importing the uploaded file into a BLOB field in a mysql database and you are using LOAD_FILE() sql statement then be aware that  mysql checks max-allowed-packet mysql variable.

- if the size of the binary file LOAD_FILE is importing is bigger than
max-allowed-packet size then it LOAD_FILE will return null.

You can specify max-allowed-packet size in the call to mysqld eg:

./bin/safe_mysqld --user=mysql --max-allowed-packet=16M &

Full info on this variable is available here:
http://www.mysql.com/doc/en/Packet_too_large.html


info at metaltoad dot net
19-Feb-2003 10:03

As of PHP 4.2.0, rather than automatically assuming a failed file uploaded is a file attack, you can use the error code associated with the file upload to check and see why the upload failed.  This error code is stored in the userfile array (ex: $HTTP_POST_FILES['userfile']['error']).

Here's an example of a switch:

if (is_uploaded_file($userfile)) {
 
  //include code to copy tmp file to final location here...
 
}else{
  switch($HTTP_POST_FILES['userfile']['error']){
   case 0: //no error; possible file attack!
     echo "There was a problem with your upload.";
     break;
   case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
     echo "The file you are trying to upload is too big.";
     break;
   case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
     echo "The file you are trying to upload is too big.";
     break;
   case 3: //uploaded file was only partially uploaded
     echo "The file you are trying upload was only partially uploaded.";
     break;
   case 4: //no file was uploaded
     echo "You must select an image for upload.";
     break;
   default: //a default error, just in case!  :)
     echo "There was a problem with your upload.";
     break;
}

Additionally, by testing the 'name' element of the file upload array, you can filter out unwanted file types (.exe, .zip, .bat, etc).  Here's an example of a filter that can be added before testing to see if the file was uploaded:

//rejects all .exe, .com, .bat, .zip, .doc and .txt files
if(preg_match("/.exe$|.com$|.bat$|.zip$|.doc$|.txt$/i", $HTTP_POST_FILES['userfile']['name'])){
  exit("You cannot upload this type of file.");
}

//if file is not rejected by the filter, continue normally
if (is_uploaded_file($userfile)) {

/*rest of code*/


itadmin at itmusicweb dot co dot uk
28-Nov-2002 03:11

The example brought out does not work as supposed to:

function is_uploaded_file($filename) {
   if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
       $tmp_file = dirname(tempnam('', ''));
   }
   $tmp_file .= '/' . basename($filename);
   /* User might have trailing slash in php.ini... */
   return (ereg_replace('/+', '/', $tmp_file) == $filename);
}

It works only with files under ....4 or 5 kb, other files automatically get the size of 0 bytes. So something must be wrong here. Built-in is_uploaded_file() works good.


troels at NO dot SPAM dot webcode dot dk
14-Oct-2002 09:44

to get the example to work on windows, youll have to add a line, that replaces backslashes with slashes. eg.: $filename = str_replace ("\\", "/", $filename);

also, as someone mentioned, globalizing $HTTP_POST_FILES is a good idea ...

<pre>
/* Userland test for uploaded file. */
function is_uploaded_file($filename)
{
   global $HTTP_POST_FILES;
   if (!$tmp_file = get_cfg_var("upload_tmp_dir")) {
       $tmp_file = dirname(tempnam("", ""));
   }
   $tmp_file .= "/" . basename($filename);
   /* User might have trailing slash in php.ini... */
   // fix for win platform
   $filename = str_replace ("\\", "/", $filename);
   return (ereg_replace("/+", "/", $tmp_file) == $filename);
}
</pre>


r3gan at hotmail dot com
17-Jun-2002 09:24

Remeber, if using $HTTP_POST_FILES inside a function and it doesn't seem to work, try globalizing the array:

function UploadFile() {

   global $HTTP_POST_FILES;

   // rest of your code here

}  // end UploadFile


 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt