Search code examples
phpfile-get-contents

Warning while getting content from file, if used "move_uploaded_file()" and "file_get_contents()"


I´m getting warning with stopping script in PHP, when I use functions in following order:

move_uploaded_file() used first

and after this included next function:

file_get_contents() used second

I am getting Warning with message:

file_get_contents(D:\Programs\WAMP\WAMP_Server\tmp\phpD8E2.tmp): failed to open stream: No such file or directory

But, if I reverse these functions: file_get_contents() first and then use move_uploaded_file() - all is right without error and it works. Where is a problem? My code with errors in below:

/* File management variables */
$filename = $_FILES["uploadFile"]["name"];
$uploadedFile = $_FILES['uploadFile']['tmp_name'];
$uploadedFileType = $_FILES['uploadFile']['type'];
$target_dir = '../uploads/';
$target_dir_file = $target_dir . basename($filename);
$textFileType = strtolower(pathinfo($target_dir_file,PATHINFO_EXTENSION));

/* First: used  move_uploaded_file() func */
move_uploaded_file($uploadedFile, $target_dir_file);

/* Second: used  file_get_contents() func */
$dbPath = fopen('../database/database.txt', 'a');
$uploadedFile = file_get_contents($uploadedFile);
fwrite($dbPath, $uploadedFile);
fclose($dbPath);

If reversed these two functions

/* First: used  file_get_contents() func */
$dbPath = fopen('../database/database.txt', 'a');
$uploadedFile = file_get_contents($uploadedFile);
fwrite($dbPath, $uploadedFile);
fclose($dbPath);

/* Second: used  move_uploaded_file() func */
move_uploaded_file($uploadedFile, $target_dir_file);

all is right and script works without errors.

Why I´m getting error, when using first move_uploaded_file() func and after file_get_contents() func, but after reverse it works without errors? How can I fix it without reversing?


Solution

  • It's because move_uploaded_file ( string $filename , string $destination ) well... moves $filename to new $destination. Therefore it's no longer available under original path.

    Given your first example, you should do:

    $uploadedFile = file_get_contents($target_dir_file);