首页 > 解决方案 > 从文件获取内容时发出警告,如果使用“move_uploaded_file()”和“file_get_contents()”

问题描述

当我按以下顺序使用函数时,我在 PHP 中停止脚本时收到警告:

首先使用move_uploaded_file()

在此之后包括下一个功能:

file_get_contents() 第二次使用

我收到警告消息:

file_get_contents(D:\Programs\WAMP\WAMP_Server\tmp\phpD8E2.tmp):无法打开流:没有这样的文件或目录

但是,如果我反转这些函数:首先使用file_get_contents() 然后使用move_uploaded_file() - 一切正常,没有错误,它可以工作。哪里有问题?我的代码在下面有错误:

/* 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);

如果颠倒这两个功能

/* 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);

一切正常,脚本正常工作。

为什么我在使用第一个move_uploaded_file()函数和在file_get_contents()函数之后出现错误,但在反转之后它可以正常工作?我怎样才能在不逆转的情况下修复它?

标签: phpfile-get-contents

解决方案


这是因为move_uploaded_file ( string $filename , string $destination )... 移动$filename到新的$destination。因此它在原始路径下不再可用。

鉴于您的第一个示例,您应该这样做:

$uploadedFile = file_get_contents($target_dir_file);

推荐阅读