This article mainly introduces the PHP move_uploaded_file() function, which actually moves the uploaded file to a new location. Friends who need it can refer to the
Definition and usage
move_uploaded_file()
Function moves the uploaded file to a new location.
If successful, return true, otherwise return false.
Syntax
move_uploaded_file(file,newloc)
Description | |
---|---|
Required. Specifies the files to be moved. | |
Required. Specifies the new location of the file. |
Tips and Notes
Note: This function is only used for files uploaded via HTTP POST. Note: If the target file already exists, it will be overwritten.Security Supplement
Introduction from w3c, let’s talk about the problems I encountered. Generally speaking, we will write the save file like this:$fileName = $_SERVER['DOCUMENT_ROOT'].'/Basic/uploads/'.$_FILES['file']['name']; move_uploaded_file($_FILES['file']['tmp_name'],$fileName )First explain, the meaning of these two codes: save the file directly, and the file name is also the file name uploaded by the user
Okay, now the risk is here:
Supplement:
There are two parameters. The first parameter is the temporary file name after you upload it, which is automatically generated by the system. Usually the style is: $_FILE["file"]["tmp_name"]; where file is the name of your front-end file upload form.The second parameter is the new file name containing the path. For example:
move_uploaded_file() function example
Use the move_uploaded_file() function to upload files to the server.<?php $tmp_filename = $_FILES['myupload']['tmp_name']; if(!move_uploaded_file($tmp_filename,"/path/to/dest/{$_FILES['myupload']['name']}")) { echo "An error has occurred moving the uploaded file.<BR>"; echo "Please ensure that if safe_mode is on that the " . "UID PHP is using matches the file."; exit; } else { echo "The file has been successfully uploaded!"; } ?>
move_uploaded_file File upload failure case and solution
Today, when implementing a PHP script that uploads an avatar image file when a user registers, a problem occurred: php The script code is as follows:<?php define('ROOT',dirname(__FILE__).'/'); if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { if(is_uploaded_file($_FILES['file']['tmp_name'])){ $stored_path = ROOT.'/upload/'.basename($_FILES['file']['name']); if(move_uploaded_file($_FILES['file']['tmp_name'],$stored_path)){ echo "Stored in: " . $stored_path; }else{ echo 'Stored failed:file save error'; } }else{ echo 'Stored failed:no post '; } } } ?>When I execute the above script, the script outputs "Stored failed: file save error", which is obviously an error. In the php_error_log file, I saw the error problem: insufficient permissions, I finally found what went wrong: the destination directory where we store the pictures does not have permissions for the user who executes the PHP script. The user who executes the PHP script is not the same user who wrote the script code and created the picture folder, so only You need to change the file permissions to 777.
PHP Development Learning File Upload (move_uploaded_file)
Function: Move the uploaded temporary file to the upload directory. Upload has been created in the root directory! ! !<form action="" enctype="multipart/form-data" method="post" name="uploadfile">上傳文件:<input type="file" name="upfile" /><br> <input type="submit" value="上傳" /></form> <?php //print_r($_FILES["upfile"]); if(is_uploaded_file($_FILES['upfile']['tmp_name'])){ $upfile=$_FILES["upfile"]; //獲取數(shù)組里面的值 $name=$upfile["name"];//上傳文件的文件名 $type=$upfile["type"];//上傳文件的類型 $size=$upfile["size"];//上傳文件的大小 $tmp_name=$upfile["tmp_name"];//上傳文件的臨時存放路徑 //判斷是否為圖片 switch ($type){ case 'image/pjpeg':$okType=true; break; case 'image/jpeg':$okType=true; break; case 'image/gif':$okType=true; break; case 'image/png':$okType=true; break; } if($okType){ /** * 0:文件上傳成功<br/> * 1:超過了文件大小,在php.ini文件中設(shè)置<br/> * 2:超過了文件的大小MAX_FILE_SIZE選項指定的值<br/> * 3:文件只有部分被上傳<br/> * 4:沒有文件被上傳<br/> * 5:上傳文件大小為0 */ $error=$upfile["error"];//上傳后系統(tǒng)返回的值 echo "================<br/>"; echo "上傳文件名稱是:".$name."<br/>"; echo "上傳文件類型是:".$type."<br/>"; echo "上傳文件大小是:".$size."<br/>"; echo "上傳后系統(tǒng)返回的值是:".$error."<br/>"; echo "上傳文件的臨時存放路徑是:".$tmp_name."<br/>"; echo "開始移動上傳文件<br/>"; //把上傳的臨時文件移動到upload目錄下面(upload是在根目錄下已經(jīng)創(chuàng)建好的?。。? move_uploaded_file($tmp_name,"upload/".$name); $destination="upload/".$name; echo "================<br/>"; echo "上傳信息:<br/>"; if($error==0){ echo "文件上傳成功啦!"; echo "<br>圖片預(yù)覽:<br>"; echo "<img src=".$destination.">"; //echo " alt=\"圖片預(yù)覽:\r文件名:".$destination."\r上傳時間:\">"; }elseif ($error==1){ echo "超過了文件大小,在php.ini文件中設(shè)置"; }elseif ($error==2){ echo "超過了文件的大小MAX_FILE_SIZE選項指定的值"; }elseif ($error==3){ echo "文件只有部分被上傳"; }elseif ($error==4){ echo "沒有文件被上傳"; }else{ echo "上傳文件大小為0"; } }else{ echo "請上傳jpg,gif,png等格式的圖片!"; } } ?>Execution results:
The difference between the constructor _construct() and _initialize() of the class in ThinkPHP
How to use distinct in Thinkphp
The above is the detailed content of move_uploaded_file() function in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

Reasons and solutions for the header function jump failure: 1. There is output before the header, and all pre-outputs need to be checked and removed or ob_start() buffer is used; 2. The failure to add exit causes subsequent code interference, and exit or die should be added immediately after the jump; 3. The path error should be used to ensure correctness by using absolute paths or dynamic splicing; 4. Server configuration or cache interference can be tried to clear the cache or replace the environment test.
