file_exists在两个地方为相同的条件返回不同的结果
问题描述:
我有一些上传表单,file_exists在同一个请求的两个地方为同样的条件返回不同的结果。以下是示例代码。file_exists在两个地方为相同的条件返回不同的结果
$flag = file_exists($_FILES['image']['name']); // return TRUE
move_uploaded_file(
$_FILES['image']['tmp_name'],
'uploads/' . $_FILES['image']['name']
);
require_once APPPATH . 'custom_classes/ImageResize.class.php';
$img_resize = new ImageResize($_FILES['image']['tmp_name']); // here is the Exception thrown
$img_resize->set_resize_dimensions(650, 451);
$img_resize->crop_image();
$img_resize->save_image('uploads/cropped.jpg');
$img_resize->free_resourses();
这里是抛出异常的类构造函数。
public function __construct($filepath)
{
if (!file_exists($filepath)) // same condition as above, throws Exception
{
throw new Exception('File not found!');
}
$this->get_source_dimensions($filepath);
$this->load_source_img($filepath);
}
这让我疯狂。我可以从文件系统传递临时路径,但我非常确定此代码之前工作过,现在它给了我这个。难道我做错了什么?
答
它说文件不存在的原因是因为它不存在了。
您正在将文件从tmp_name位置移动到uploads文件夹中,然后在刚移出的tmp_name位置查找它。
答
一旦你移动了文件,那么它不是在原来的位置了,这是一个“移动”而不是“复制”,因此:
$flag = file_exists($_FILES['image']['name']); // return TRUE
$newlocation = 'uploads/'.$_FILES['image']['name'];
move_uploaded_file(
$_FILES['image']['tmp_name'],
$newlocation
);
require_once APPPATH . 'custom_classes/ImageResize.class.php';
$img_resize = new ImageResize($newlocation); // no more Exception thrown!
$img_resize->set_resize_dimensions(650, 451);
$img_resize->crop_image();
$img_resize->save_image('uploads/cropped.jpg');
$img_resize->free_resourses();
应该更好地为您。 (不太清楚为什么你有tmp_name和name,但我假设你知道)
那么,如果你移动它,它将不再存在于旧的位置...... – jeroen