PHP move uploaded file to safety location

Write a program to move the uploaded file to safety location

Solution

When a user uploads a file to a PHP script using the <input type="file" /> HTML element, PHP stores the file in a temporary location and deletes it upon completion of the script execution. Therefore, you have to access the uploaded file within the script. To do so, PHP contains the function move_uploaded_file(), which moves a file from one location to another. The great thing about move_uploaded_file() is that the function first does a sanity check, whether the filename you provide really is an uploaded file or if a malicious user just tried to trick you into moving /etc/passwd or c:\boot.ini somewhere else.

<?php
if(isset($_POST['submit']) &&  isset($_FILES['file'])) {
	$move = move_uploaded_file($_FILES['File']['tmp_name'],
	'/tmp/' . basename($_FILES['File']['name']));
	echo ($move) ? 'File moved' : 'File failed to move';
} else {
?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"
	method="post" enctype="multipart/form-data">
<input type="file" name="File" />
<input type="submit" name="Submit" value="Submit" />
</form>
<?php
}
?>

Suppose the path /tmp exists and is writable by the web server and the PHP process. Then, the preceding code moves the uploaded file to this directory, using its original filename (and you do not care whether the filename already exists).





Related PHP Programs for Practice

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters
PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Lock a file
PHP - Insert image in database




Read more articles


General Knowledge



Learn Popular Language