簡體   English   中英

file_put_contents的錯誤子句

[英]error clause for file_put_contents

我正在使用此行來獲取並保存URL中的圖像。

file_put_contents("./images/".$pk.".jpg", file_get_contents($PIC_URL))

我不確定處理錯誤的最佳方法是什么。 目前它失敗了,因為沒有許可,很快就會得到補救,但我希望它能夠處理PIC_URL為空或不是圖像的情況。 我應該死在這個級別的錯誤(可能是與權限相關的事情更好)或者我應該檢查更高的PIC_URL是空的,還是兩者都檢查?

哪種方法最好?

我沒有足夠的天賦來宣稱這是最好的方法,但我會沿途測試:

$imageDir = "/path/to/images/dir/";
$imagePath = "$imageDir$pk.jpg";
if (!is_dir($imageDir) or !is_writable($imageDir)) {
    // Error if directory doesn't exist or isn't writable.
} elseif (is_file($imagePath) and !is_writable($imagePath)) {
    // Error if the file exists and isn't writable.
}

$image = file_get_contents(urlencode($PIC_URL));
if (empty($image)) {
    // Error if the image is empty/not accessible.
    exit;
}

file_put_contents($imagePath, $image);

嗯,你也不能這樣做

file_put_contents($file, $str) or die("Unable to write file!");

我會使用is_writable(),如果圖像不存在則傳遞文件夾名稱,如果嘗試寫入圖像,則傳遞文件名。

http://uk3.php.net/manual/en/function.is-writable.php

嘗試為此做一個功能。

<?php
define('OK', 0);
deinfe('URL_EMPTY', 1);
define('WRITING_PROBLEMS',2);
define('OTHER_PROBLEM', 3);


function save_pic($pic_url) {

  $imageDir = '/path/to/images/dir/';

  if (!strlen($pic_url))
    return URL_EMPTY;

  if (!is_dir($imageDir) || !is_writable($imageDir)) {
    return WRITING_PROBLEMS; 
  }

  $image = file_get_contents(urlencode($pic_url));

  $pk = time(); // or whatever you want as key


  $r = file_put_contents($imagePath.$pk.".jpg", $pic_url);

  if ($r)
    return OK;
  else
    return OTHER_PROBLEM;

}
?>

兩者,據我所知。 特別是對於那些危險的文件處理功能,雙重檢查不會造成傷害。 $pk來自哪里?)

通常,檢查更高的位置以獲得更好的用戶反饋,並在執行安全性之前進行檢查。 僅在低級別檢查時很難給用戶提供良好的反饋。 另一方面,很難在高級和通用級別上檢查所有可能的錯誤(例如那些文件系統權限)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM