PHP.mk документација

move_uploaded_file

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.move-uploaded-file.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.move-uploaded-file.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
move_uploaded_file

Референца за `function.move-uploaded-file.php` со подобрена типографија и навигација.

function.move-uploaded-file.php

move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

move_uploaded_fileГи преместува поставената датотека на нова локација

= NULL

move_uploaded_file(string $from, string $to): bool

Оваа функција проверува дали датотеката означена со from е валидна поставена датотека (што значи дека е поставена преку PHP-овиот HTTP POST механизам за поставување). Ако датотеката е валидна, таа ќе биде преместена во името на датотеката дадено од to.

Овој вид на проверка е особено важен ако постои можност нешто направено со поставените датотеки да ги открие нивните содржини на корисникот, или дури и на други корисници на истиот систем.

Параметри

from

Името на датотеката на поставената датотека.

to

Дестинацијата на преместената датотека.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true на успешен исход.

Враќа from не е валидна поставена датотека, тогаш нема да се случи никаква акција, и move_uploaded_file() ќе врати false.

Враќа from е валидна поставена датотека, но од некоја причина не може да се премести, тогаш нема да се случи никаква акција, и move_uploaded_file() ќе врати false. Дополнително, ќе се издаде предупредување.

Примери

Пример #1 Поставување повеќе датотеки

<?php
$uploads_dir
= '/uploads';
foreach (
$_FILES["pictures"]["error"] as $key => $error) {
if (
$error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>

Белешки

Забелешка:

move_uploaded_file() is open_basedir свесен. Сепак, ограничувањата се ставаат само на to патеката за да се овозможи преместување на поставените датотеки во кои from може да бидат во конфликт со таквите ограничувања. move_uploaded_file() ја осигурува безбедноста на оваа операција дозволувајќи само датотеки поставени преку PHP да бидат преместени.

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Ако дестинациската датотека веќе постои, таа ќе биде презапишана.

Види Исто така

Белешки од корисници за да означиме кој било валиден PHP израз.

Јусеф Исмаел Клипрс
пред 13 години
Security tips you must know before use this function :

First : make sure that the file is not empty.

Second : make sure the file name in English characters, numbers and (_-.) symbols, For more protection.

You can use below function as in example

<?php

/**
 * Check $_FILES[][name]
 *
 * @param (string) $filename - Uploaded file name.
 * @author Yousef Ismaeil Cliprz
 */
function check_file_uploaded_name ($filename)
{
    (bool) ((preg_match("`^[-0-9A-Z_\.]+$`i",$filename)) ? true : false);
}

?>

Third : make sure that the file name not bigger than 250 characters.

as in example :

<?php

/**
 * Check $_FILES[][name] length.
 *
 * @param (string) $filename - Uploaded file name.
 * @author Yousef Ismaeil Cliprz.
 */
function check_file_uploaded_length ($filename)
{
    return (bool) ((mb_strlen($filename,"UTF-8") > 225) ? true : false);
}

?>

Fourth: Check File extensions and Mime Types that you want to allow in your project. You can use : pathinfo() http://php.net/pathinfo

or you can use regular expression for check File extensions as in example

#^(gif|jpg|jpeg|jpe|png)$#i

or use in_array checking as

<?php

$ext_type = array('gif','jpg','jpe','jpeg','png');

?>

You have multi choices to checking extensions and Mime types.

Fifth: Check file size and make sure the limit of php.ini to upload files is what you want, You can start from http://www.php.net/manual/en/ini.core.php#ini.file-uploads

And last but not least : Check the file content if have a bad codes or something like this function http://php.net/manual/en/function.file-get-contents.php.

You can use .htaccess to stop working some scripts as in example php file in your upload path.

use :

AddHandler cgi-script .php .pl .jsp .asp .sh .cgi
Options -ExecCGI  

Do not forget this steps for your project protection.
matthias dot dailey at gmail dot com
пред 14 години
The destination directory must exist; move_uploaded_file() will not automatically create it for you.
adeel dot cs at gmail dot com
пред 2 години
Permissions issue.

If you have set a setgid I.e g+s on the folder and wondering why the created files are owned by www-data:www-data, note that uploaded files are first saved in /tmp folder with the web user.

The move_uploaded_file() command moves the files from /tmp to the given TO directory, including the current permissions the /temp file has.

Hence the setgid gets ignored and doesn't inherit the parent permissions.
Dan Delaney
пред 17 години
For those using PHP on Windows and IIS, you SHOULD set the "upload_tmp_dir" value in php.ini to some directory around where your websites directory is, create that directory, and then set the same permissions on it that you have set for your websites directory. Otherwise, when you upload a file and it goes into C:\WINDOWS\Temp, then you move it to your website directory, its permissions will NOT be set correctly. This will cause you problems if you then want to manipulate that file with something like ImageMagick's convert utility.
chelidze dot givia at gmail dot com
пред 2 години
When using move_uploaded_file(). If the user uploads an image with a name that already exists, move_uploaded_file() will overwrite it. It's a good practice to store images in directories that you generate upon creating ur card/user/product etc...

<?php
    function generateDir(int $n): string {
         $characters="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        $dir = "";
        for($i = 0; $i<$n; $i++){
            $index = rand(0, strlen($characters)-1);
            $dir .= $characters[$index];
        }
        return $dir;
    }

    $image = $_FILES["image"];
    $imagePath = 'images/'. generateDir(10) .'/'. $image["name"];

    // Make the directory first or else it will not proceed with the upload.
    mkdir($imagePath);
    
    // some error handling etc...

    move_uploaded_file($image["tmp_name"],  $imagePath);
?>
shacker at birdhouse dot org
19 години пред
If you're dealing with files uploaded through some external FTP source and need to move them to a final destination, searching php.net for "mv" or "move" won't get you what you want. You want the rename() function. 

http://www.php.net/manual/en/function.rename.php

(move_uploaded_file() won't work, since the POST vars won't be present.)
Florian S. in H. an der E. [.de]
пред 17 години
move_uploaded_file (on my setup) always makes files 0600 ("rw- --- ---") and owned by the user running the webserver (owner AND group).
Even though the directory has a sticky bit set to the group permissions!
I couldn't find any settings to change this via php.ini or even using "umask()".

I want my regular user on the server to be able to "tar cjf" the directory .. which would fail on files totally owned by the webserver-process-user;
the "copy(from, to)" function obeys the sticky-bit though!
Zarel
19 години пред
nouncad at mayetlite dot com posted a function that uploaded a file, and would rename it if it already existed, to filename[n].ext

It only worked for files with extensions exactly three letters long, so I fixed that (and made a few other improvements while I was at it).

<?php
// Usage: uploadfile($_FILE['file']['name'],'temp/',$_FILE['file']['tmp_name'])
function uploadfile($origin, $dest, $tmp_name)
{
  $origin = strtolower(basename($origin));
  $fulldest = $dest.$origin;
  $filename = $origin;
  for ($i=1; file_exists($fulldest); $i++)
  {
    $fileext = (strpos($origin,'.')===false?'':'.'.substr(strrchr($origin, "."), 1));
    $filename = substr($origin, 0, strlen($origin)-strlen($fileext)).'['.$i.']'.$fileext;
    $fulldest = $dest.$newfilename;
  }
  
  if (move_uploaded_file($tmp_name, $fulldest))
    return $filename;
  return false;
}
?>
Juliano P. Santos
пред 7 години
For those which will use inotify-tools to start an event when move_uploaded_file put the file in a specific directory, be aware that move_uploaded_file will trigger the create event, and not the move event of inotify-tools.
nlgordon at iastate dot edu
пред 18 години
Just a helpful comment.  If you have open_basedir set then you must set upload_tmp_dir to somewhere within the open_basedir.  Otherwise the file upload will be denied.  move_uploaded_file might be open_basedir aware, but the rest of the upload process isn't.
jest3r at mtonic dot net
20 години пред
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
benbrown3882 at gmail dot com
пред 2 години
Ensure the upload temporary directory and the destination directory have "write" permissions for Other.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.