Tags
PHP
Asked 2 years ago
22 Jul 2021
Views 334
Adrien

Adrien posted

How to use function move_uploaded_file in php

where i working for php script where i need to upload file but how to do it with move_uploaded_file ?
jignesh

jignesh
answered Jul 24 '21 00:00


i am supposing of uploading image (or any file)
this is html sample , use input type='file' and dont forget to put enctype="multipart/form-data" attribute at form field.

 <form method="post" enctype="multipart/form-data" >
<input type='file' name='image' /> 
</form>


PHP coding to upload file with move_uploaded_file


if (isset($_FILES['image']['name'])) {
	$tmp_name = $_FILES["image"]["tmp_name"];
         $uploads_dir='/uploads/';
        $name = basename($_FILES["image"]["name"]);
       if( move_uploaded_file($tmp_name, "$uploads_dir/$name")){
           echo "file uploaded at uploads/profile/$name";
       }
   }
 


let me explain the code :
check wheather files is set to upload , i mean any file selected from user side :
if (isset($_FILES['image']['name'])) {
// code to upload here if file selected or not
}

// file content will be in tmp_name so let put in separate variable
$tmp_name = $_FILES["image"]["tmp_name"];

basename get to used file name from the fullpath
$name = basename($_FILES["image"]["name"]);

move_uploaded_file have two parameter where one is here file content and other parameter is where to upload file ,
move_uploaded_file($tmp_name, "$uploads_dir/$name")
so here $temp_name is the content file which user selected
and another parameter is "$uploads_dir/$name" upload dir with filename , you can put any file name like "$uploads_dir/static.jpg" but extension should be dynamic based on the file uploaded.

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

Parameters :
from
The filename of the uploaded file.

to
The destination of the moved file.
Post Answer