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: 26
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
Mimo, że strony WWW tworzymy już 5 lat zawsze znajdziemy coś ciekawego. Świadczy o tym chociażby nasza aktówka, w której znajduje się kilkadziesiąt porad, z których często korzystamy. Otwarta forma poradnika, czyli możliwość podrzucania tematów oraz wspólny ich rozwój, to nieoceniona pomoc. Uważam, ze abonament roczny jest niewspółmiernie niski do jakości zaprezentowanych materiałów.

Marek Kończal
Internetix.pl

   
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]

move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5)

move_uploaded_file -- Przenieś uploadowany plik do innej lokalizacji

Opis

bool move_uploaded_file ( string nazwa_pliku, string przeznaczenie )

Funkcja ta sprawdza czy na pewno plik określony przez nazwa_pliku jest prawidło uploadowanym plikiem (to znaczy, że został uploadowany przez PHPowy mechanizm uploadowania HTTP POST). Jeśli plik jest prawidłowy, to zostanie przeniesiony do nazwy pliku wskazanej przez przeznaczenie.

Jeśli nazwa_pliku nie jest prawidło uploadowanym plikiem, to żadna akcja nie zostanie wykonana i move_uploaded_file() zwróci FALSE.

Jeśli nazwa_pliku jest prawidłowo uploadowanym plikiem, ale nie może zostać przeniesiony z jakiś powodów, żadna akcja nie zostanie wykonana i move_uploaded_file() zwróci FALSE. Dodatkowo, zostanie pokazane ostrzeżenie.

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.

Notatka: move_uploaded_file() jest świadomy tryb bezpieczny oraz open_basedir. Jednak, ograniczenia nałożone są tylko na ścieżkę przeznaczenie, ponieważ pozwala na przenoszenie uloadowanych plików w których nazwa_pliku może kolidować z takimi ograniczeniami. move_uploaded_file() zapewnia bezpieczeństwo tej operacji poprzez zezwolenie na przeniesienie tylko tych plików, które były uploadowane przez PHP.

Ostrzeżenie

Jeśli już istnieje plik docelowy, to zostanie on nadpisany.

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




User Contributed Notes

the dot only dot storm at gmail dot com
02-Feb-2006 09:02

In addition to the file extension checking. A simply way of getting the extension (regardless of size):

$efilename = explode('.', $filename);
$ext = $efilename[count($efilename) - 1];

Note:
This is *could* cause a ~0.01s delay because you're not using COUNT() to initialize a variable by itself. Refer to googling similar: php count function performance


calamitoso at gmail dot com
31-Jan-2006 08:10

to separate (for example) images from other file types among the uploaded files you can check the MIME type also (thus making the file extension check unnecessary)

$temp = strpos($_FILES["pic"]["type"], "image");
if ($rep===FALSE){
   //the strpos function will return a boolean "false" ONLY if the needle string is not found within the haystack
   echo "is not an image";
}else{
   echo "is an image";
}


may at dutchclan dot com
28-Jan-2006 12:57

also got savemode and open_file_base restrictions where owner issues prevented us from using it. But when you remove the first "/" of the destination path it seems to work..

$source = $_FILES['userfile']['tmp_name'];
$destination = "images/uploaded/"; (without first "/")

move_uploaded_file($source, $destination);

regards, May


mancow at macfilez dot net
10-Jan-2006 06:31

To nouncad at mayetlite dot com,

That function will work fine for files with a 3-character file extension.  However, it is worth noting that there are valid, registered file extensions that are longer than 3 characters.  For example, a JPEG file can be denoted by *.jpg (and others), but it can also have *.jpeg as a valid extension.  Check out http://www.filext.com/ for a good reference of file extensions.

The best bet to me would be parsing the uploaded file's name ($_FILES['uploadedfile']['name']) based on the presence of dots.  Another wrench in the gears:  a file can have dots in the filename.  That's easy enough to handle -- just explode() the file name and hope that the last element in the array it gives you is the file extension (you can always validate it if you're so inclined).  Then just piece it together in a string accordingly by stepping through the array (don't forget to add those dots back to where they were!), appending a guaranteed unique string of characters (or enumerate it like you were doing, keeping track via a loop), and finally tacking on the file extension.

You may have other mechanisms for verifying a file's extension, such as a preg_match on the whole name, using something like "/\\.(gif|jpg|jpeg|png|bmp)$/i" (more can, of course, be added if you so desire) for the most common types of images found on the web.

For blindly guaranteeing an uploaded file will be uniquely named, this seems like a fantastic way to go.  Enjoy!


AT-HE (at_he AT hotm4il DOT com)
16-Dec-2005 07:28

---------
Note that post_max_size also needs to be considered, by default it is 8M. I raised my upload_max_filesize to 20M and was wondering why 10M uploads weren't working...

r: It could be because of your max execution time.
----------

try changing the value of both post_max_size and upload_max_filesize


nouncad at mayetlite dot com
14-Dec-2005 02:30

Great!! my first note here...

This function upload a file.
If file exist, create a copy as "filename[n].ext"

<?php
function subirFichero($origen, $destinoDir, $ftemporal) {   
  
$origen = strtolower(basename($origen));

  
$destinoFull = $destinoDir.$origen;
  
$frand = $origen;
  
$i = 1;
  
   while (
file_exists( $destinoFull )) {
      
$file_name        = substr($origen, 0, strlen($origen)-4);
      
$file_extension  = substr($origen, strlen($origen)-4, strlen($origen));
      
$frand = $file_name."[$i]".$file_extension;
      
$destinoFull = $destinoDir.$frand;
      
$i++;
   }
  
   if (
move_uploaded_file($ftemporal, $destinoFull))    return $frand;
   else                                                return
"0";
}
?>


ineedmynetwork.com
07-Nov-2005 10:27

Microsoft returns image/pjpeg not image/jpg when using $_FILES['imageName']['type'];


albert
07-Nov-2005 09:44

move_uploaded_file()'s return codes are not allways obious !

Unable to move '/var/tmp/phpuuAVJv' to '/home/me/website.com/upload/images/hello.png'

will apear if your disk is full, or the webserver (www user) exeeded it's disk qouta. (probably some others)

i dont know if its a bug (just not iplemented) or a feature (to hide from 3rd parties details about the system or about the specific error) ?

it happend to me that after several months of successful operation, the disk filled up and qouta exeeded.

it took me long time, finding out why all the sudden my scripts didnt work properly anymore.


05-Nov-2005 12:56

[quote]
Note that post_max_size also needs to be considered, by default it is 8M. I raised my upload_max_filesize to 20M and was wondering why 10M uploads weren't working...
[/quote]

It could be because of your max execution time.


29-Oct-2005 05:44

Note that post_max_size also needs to be considered, by default it is 8M. I raised my upload_max_filesize to 20M and was wondering why 10M uploads weren't working...


jest3r at mtonic dot net
20-Oct-2005 06:10

It seems that move_uploaded_file use the GROUP permissions of the parent directory of the tmp file location, whereas a simple "copy" uses the group of the apache process. This could create a security nighmare if your tmp file location is owned by root:wheel


mikelone
06-Sep-2005 05:46

If the user try to upload a too bigger file then the upload procedure will fail even if u have established an error message.
How to avoid this problem? there's my solution:

(max_file_size = 2,50 MB)

$fsize = $_FILES["userfile"]["size"];

if($fsize == 0 || $fsize > 2621000) exit("keep the filesize under 2,50MB!!");

When the size is bigger than the MAX_FILE_SIZE field, the value of $fsize is equal to 0 (zero) ......


espiao at gmail dot com
27-Jul-2005 04:25

/**
 * This function moves the archives and directoryes of a directory of
 * origin for a directory destination being able replace them or not.
 **/

function mvdir($oldDir, $newDir, $replaceFiles = true) {

   if ($oldDir == $newDir) {
       trigger_error("Destination directory is equal of origin.");
       return false;
   }
      
   if (!($tmpDir = opendir($oldDir))) {
       trigger_error("It was not possible to open origin directory.");
       return false;
   }

   if (!is_dir($newDir)) {
       trigger_error("It was not possible to open destination directory.");
       return false;       
   }

   while (($file = readdir($tmpDir)) !== false) {

       if (($file != ".") && ($file !== "..")) {
          
           $oldFileWithDir = $oldDir . $file;
           $newFileWithDir = $newDir . $file;
          
           if (is_dir($oldFileWithDir)) {
              
               @mkdir($newFileWithDir."/", 0777);
               @mvdir($oldFileWithDir."/", $newFileWithDir."/", $replaceFiles);
               @rmdir($oldFileWithDir);

           }
           else {
               if (file_exists($newFileWithDir)) {
                   if (!$replaceFiles) {
                      
                       @unlink($oldFileWithDir);
                       continue;
                      
                   }
               }
              
               @unlink($newFileWithDir);
               @copy($oldFileWithDir, $newFileWithDir);
               @chmod($newFileWithDir, 0777);
               @unlink($oldFileWithDir);
              
           }
       }
   }
  
   return true;
  
}

/**
 * This is an example of move with replace files on destination folder if
 * exists files with the same names on destionatio folder
 **/
mvdir("/var/www/example/", "/var/www/other_folder/");

/**
 * This is an example of move without replace files on destination
 * folder if  exists files with the same names on destionatio folder
 **/
mvdir("/var/www/example/", "/var/www/other_folder/", false);


Darrell
18-May-2005 11:51

move_uploaded_file apparently uses the root of the Apache installation (e.g. "Apache Group\Apache2" under Windows) as the upload location if relative pathnames are used.

For example,
$ftmp = $_FILES['userfile']['tmp_name'];
$fname = $_FILES['userfile']['name'];
move_uploaded_file($ftmp, $fname);
                          
moves the file to
"Apache Group\Apache2\$fname";

In contrast, other file/directory related functions use the current directory of the php script as the offset for relative pathnames.  So, for example, if the command

mkdir('tmp');

is called from 'Apache Group\Apache2\htdocs\testpages\upload.php', the result is to create
'Apache Group\Apache2\htdocs\testpages\tmp'

On the other hand, if 'mkdir' is called just before 'move_uploaded_file', the behavior changes.  The commands,

mkdir('tmp');
move_uploaded_file($ftmp, $fname);

used together result in

"Apache Group\Apache2\htdocs\testpages\tmp\$fname"

being created.  Wonder if this is a bug or a feature.

Darrell


andrew@euperia,com
04-Apr-2005 11:29

Instead of using chdir or chmod 0777 a safer alternative to move_uploaded_files is to use PHP's ftp functions to move the file into a web dir.

1. Make ftp connection to 127.0.0.1 with the correct username and password.
2. ftp_chdir to the required directory.
3. ftp_put ($_FILES['myfile']['tmp_name'], $finalfilename);
4. ftp quit.


richardNO at SPAMbesite dot nl
11-Mar-2005 01:32

Creating the dir with mkdir from php is a security risk too. Everyone who can run a php script on the server can write a script to mess with the dir.


user at php dot net
01-Mar-2005 11:54

Giving the directory 777 permission is not a good idea for security reasons, it would be better to create the directory using "mkdir()".

That will make php user (usually "nobody") the owner of the directory, and permissions will not be a problem.


subway
17-Feb-2005 11:18

Don't forget to set chmod to 777 for the directory to which you want to move the file.
Otherwise you will maybe get "failed to open stream: Permission denied in ..."!


Michel S
16-Feb-2005 06:41

I once had a problem with this function. File was uploaded correctly, but I still had to chmod the file afterwards. It could not be used otherwise.

Michel S


allan666 at NOSPAM dot gmail dot com
17-Dec-2004 07:35

On the Fedora Core 3 Linux distribution, you may get a "failed to open stream: Permission denied in ..." message. I fact changing the permission of the directory will not work (even if you set to 0777). It is because of the new SELinux kernel that allow apache user to write only in /tmp dir (I think). In order to solve the problem you must to disable the SELinux (at least for apache service) to allow the server to write in other directories. To do that, run the system-config-securitylevel app and disable the SE to apache service. Reboot your system and continue your work. Hope it helps!


php at f00n dot com
04-Jul-2004 10:17

If you are building an intranet framework and use NAT/Routing heed the following advice.

If you want to move uploaded files to an FTP server you cannot use the ftp wrapper (ie. 'ftp://user:pass@ftpserver/') as part of your move_uploaded_file() action.  This is due to the wrapper only using passive mode with ftp.

The only workaround is using the ftp functions (may not be compiled by default with *nix but is by default with windows).


froid_nordik at sympatico dot ca
04-Jun-2004 06:26

Make sure the directory you are moving the file to exists before using this command.


sauron at nospam on morannon dot org
08-Mar-2004 02:20

An extension only does not really tell you what type of file it really is. I can easily rename a .jpg file to a .zip file and make the server think it is a ZIP file with webmaster kobrasrealm's code.

A better way is to use the Linux utility "file" to determine the file type. Although I'm aware that some users might use Windows on their webservers, I thought it's worth  mentioning the utility here. Using the backtick operators and preg_matches on the output, you can easily determine the file type safely, and fix the extension when necessary.


mail at johan dot it
28-Feb-2004 11:14

Warning: If you save a md5_file hash in a database to keep record of uploaded files, which is usefull to prevent users from uploading the same file twice, be aware that after using move_uploaded_file the md5_file hash changes! And you are unable to find the corresponding hash and delete it in the database, when a file is deleted.


mina86 at tlen dot pl
08-Dec-2003 12:03

Hey! Why not using strrchr() to get file  extension:
<?php $ext = strrchr($_FILES['file']['name'], '.'); ?>
or to get it without '.' at the begining:
<?php $ext = substr(strrchr($_FILES['file']['name'], '.'), 1); ?>

If you want to update file without any strang characters you can use:
<?php
move_uploaded_file
(
 
$_FILES["file"]["tmp_name"],
 
$dir . preg_replace('/[^a-z0-9_\-\.]/i', '_', $_FILES["file"]["name"])
);
?>


wolke74 at web dot de
18-Nov-2003 06:02

French and English filenames --- as it is not forbidden -- often have an apostrophy, for instance "That's advertisement paper.doc" or "Les aventures d'Alice dans le pays du miracle.doc". However, uploading such files can run into trouble.

So you can write, if the posted file had been marked by myfile .

if(!move_uploaded_file($_FILES["myfile"]["tmp_name"],
rawurlencode($mydir.$_FILES["myfile"]["name"]))
{
     echo "Something is wrong with the file";
     exit;
}


09-Nov-2003 04:54

The example to find file extension bellow is quite confusing and its using to much code for a much simpler solution. Which is in example:

$file_parts = pathinfo('dir/' . $_FILES['file']['name']);
$file_extension = strtolower($file_parts['extension']);

The 'dir/' part is only to get a valid path.


www at w8c dot com
09-Oct-2003 09:03

function upload($filedir,$source,$source_name,$up_flag,$lastname)
{
   if (!file_exists($filedir))
   {
       mkdir($filedir,0777);
   }
   @chmod($filedir,0777);
   if (!$lastname)
   {
       $lastname=$source_name;
   }
   if (file_exists("$filedir/$lastname"))
   {
       if ($up_flag=="y")
       {
           @unlink($filedir/$lastname);
           @move_uploaded_file($source,"$filedir/$lastname");
           echo "$source_name OK<br>";
       }
       else
       echo "$source_name ...<br>";
   }
   else
   {
       @move_uploaded_file($source,"$filedir/$lastname");
       echo "$source_name OK<br>";
   }
}


allen at brooker dot gb dot net
12-Feb-2003 11:48

The first comment totally threw me off. Under the 'new regime', the 'string filename' is $_FILES['userfile']['tmp_name']

Also note that the 'string destination' should be the full path and filename. As long as your server isnt using virtual hosting, you should be able to use $_SERVER['DOCUMENT_ROOT'] . "path/within/website". This'll save hours of hassle trying to get sometimes ignorant ISPs to give you your full and 'no symlinks' path.

Allen


 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt