gpt4 book ai didi

php - file_get_contents 创建一个空文件

转载 作者:行者123 更新时间:2023-12-04 03:20:43 27 4
gpt4 key购买 nike

在 if 子句中用作测试条件时,如何防止 file_get_contents 创建空文件?

无论如何都会创建一个空文件,这会导致在不同方法中对 getimagesize() 的后续调用失败。

问题是,当我有我的代码设置时,它第一次被调用将决定是保存图像还是显示以前保存的图像。这部分取决于文件的存在。由于创建了一个空文件,因此在后续调用我的代码时会出现问题。

添加检查文件是否存在且大于 0 的最简单方法是什么?

不管我的代码是否有效,file_get_contents 仍然会输出错误。这个错误被解释和处理(通过我的 if 条件),所以我想尽可能避免错误中断我的应用程序的输出。有没有办法在不隐藏实际错误的情况下关闭它?

if (file_put_contents($imageDir . $pk . '.jpg', file_get_contents($pic_url))) 
{
return $imageDir . $pk . '.jpg';
}
else
{
return 'removed.jpg';
}

最佳答案

使用 file_exists 检查文件是否存在:

if (file_exists($pic_url)) {
$contents = file_get_contents($pic_url);
if (!empty($contents)) {
file_put_contents($imageDir . $pk . '.jpg', $contents);
return $imageDir . $pk . '.jpg';
}
}
return 'removed.jpg';

关于php - file_get_contents 创建一个空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/600611/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com