كيف يمكنني التعامل مع التحذير الخاص بوظيفة file_get_contents() في PHP؟

StackOverflow https://stackoverflow.com/questions/272361

سؤال

لقد كتبت كود PHP مثل هذا

$site="http://www.google.com";
$content = file_get_content($site);
echo $content;

ولكن عندما أقوم بإزالة "http://" من $site أحصل على التحذير التالي:

تحذير:file_get_contents (www.google.com) [function.file-get-contents]:فشل لفتح البث:

حاولت try و catch لكنها لم تنجح.

هل كانت مفيدة؟

المحلول

الخطوة 1: التحقق من رمز الإرجاع: if($content === FALSE) { // handle error here... }

الخطوة 2: قمع تحذير من وضع التحكم بالأخطاء مشغل (أي @) أمام الدعوة إلى <م> file_get_contents () : $content = @file_get_contents($site);

نصائح أخرى

ويمكنك أيضا href="http://us2.php.net/set_error_handler" وضع معالج الأخطاء الخاصة بك باعتبارها <لأ href = "HTTP: // بي. صافي / دليل / EN / functions.anonymous.php "يختلط =" noreferrer "> وظيفة مجهول التي تدعو إلى <لأ href =" http://us.php.net/manual/en/class.errorexception. فب "يختلط =" noreferrer "> استثناء واستخدام حاول / catch على هذا الاستثناء.

set_error_handler(
    function ($severity, $message, $file, $line) {
        throw new ErrorException($message, $severity, $severity, $file, $line);
    }
);

try {
    file_get_contents('www.google.com');
}
catch (Exception $e) {
    echo $e->getMessage();
}

restore_error_handler();

ويبدو أن الكثير من التعليمات البرمجية للقبض على خطأ واحد قليلا، ولكن إذا كنت تستخدم استثناءات في جميع أنحاء التطبيق، سوف تحتاج فقط إلى القيام بذلك مرة واحدة، وطريقة في الجزء العلوي (في ملف التكوين وشملت، على سبيل المثال)، وسيتم تحويل كافة الأخطاء إلى الاستثناءات طوال الوقت.

والطريقة المفضلة للقيام بذلك هي بسيطة إلى حد ما:

if (!$data = file_get_contents("http://www.google.com")) {
      $error = error_get_last();
      echo "HTTP request failed. Error was: " . $error['message'];
} else {
      echo "Everything went better than expected";
}

ولقد وجدت هذا بعد تجربة مع try/catch منenobrev أعلاه، ولكن هذا يسمح لرمز أقل طويلة (والمنظمة البحرية الدولية، أكثر قابلية للقراءة). نحن ببساطة استخدام error_get_last للحصول على نص الخطأ الأخير، وfile_get_contents ترجع كاذبة عن الفشل، لذلك بسيط "لو" يمكن التقاط ذلك.

يمكنك إضافة @:$content = @file_get_contents($site);

سيؤدي هذا إلى قمع أي تحذير - استخدم باعتدال!.يرى مشغلي التحكم في الأخطاء

يحرر:عند إزالة "http://"، فإنك لم تعد تبحث عن صفحة ويب، بل عن ملف موجود على القرص لديك يسمى "www.google....."

وبديل واحد هو لقمع الخطأ وأيضا بطرح استثناء التي يمكنك التقاط لاحقا. وهذا مفيد خصوصا إذا كانت هناك دعوات متعددة لfile_get_contents () في التعليمات البرمجية الخاصة بك، لأنك لا تحتاج إلى قمع والتعامل مع كل منها يدويا. بدلا من ذلك، يمكن إجراء عدة مكالمات لهذه المهمة في كتلة حاول / catch واحد.

// Returns the contents of a file
function file_contents($path) {
    $str = @file_get_contents($path);
    if ($str === FALSE) {
        throw new Exception("Cannot access '$path' to read contents.");
    } else {
        return $str;
    }
}

// Example
try {
    file_contents("a");
    file_contents("b");
    file_contents("c");
} catch (Exception $e) {
    // Deal with it.
    echo "Error: " , $e->getMessage();
}

إليك كيف فعلت ذلك ... لا حاجة لكتلة حاول اللحاق ... الحل الأفضل هو دائما أبسط ... استمتع!

$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) { 
   echo "SUCCESS";
} else { 
   echo "FAILED";
} 
function custom_file_get_contents($url) {
    return file_get_contents(
        $url,
        false,
        stream_context_create(
            array(
                'http' => array(
                    'ignore_errors' => true
                )
            )
        )
    );
}

$content=FALSE;

if($content=custom_file_get_contents($url)) {
    //play with the result
} else {
    //handle the error
}

وهنا هو كيف أتعامل مع ما يلي:

$this->response_body = @file_get_contents($this->url, false, $context);
if ($this->response_body === false) {
    $error = error_get_last();
    $error = explode(': ', $error['message']);
    $error = trim($error[2]) . PHP_EOL;
    fprintf(STDERR, 'Error: '. $error);
    die();
}

وأفضل شيء سيكون لتحديد الخطأ واستثناء الخاصة معالجات التي سوف تفعل شيء مفيد مثل تسجيل في ملف أو إرساله عبر البريد الإلكتروني منها حرجة. http://www.php.net/set_error_handler

هل يمكن استخدام هذا البرنامج النصي

$url = @file_get_contents("http://www.itreb.info");
if ($url) {
    // if url is true execute this 
    echo $url;
} else {
    // if not exceute this 
    echo "connection error";
}

ومنذ PHP 4 استخدام error_reporting () :

$site="http://www.google.com";
$old_error_reporting = error_reporting(E_ALL ^ E_WARNING);
$content = file_get_content($site);
error_reporting($old_error_reporting);
if ($content === FALSE) {
    echo "Error getting '$site'";
} else {
    echo $content;
}

وأبسط طريقة للقيام بذلك هو مجرد إلحاقها ل @قبل file_get_contents، أنا. ه:.

$content = @file_get_contents($site); 

وشيء من هذا القبيل:

public function get($curl,$options){
    $context = stream_context_create($options);
    $file = @file_get_contents($curl, false, $context);
    $str1=$str2=$status=null;
    sscanf($http_response_header[0] ,'%s %d %s', $str1,$status, $str2);
    if($status==200)
        return $file        
    else 
        throw new \Exception($http_response_header[0]);
}

وهذا سوف محاولة للحصول على البيانات، وإذا كان لا يعمل، وسوف قبض على خطأ، ويسمح لك أن تفعل أي شيء تحتاجه في الصيد.

try {
    $content = file_get_contents($site);
} catch(\Exception $e) {
    return 'The file was not found';
}

ويجب عليك استخدام file_exists () وظيفة قبل استخدام file_get_contents (). مع هذه الطريقة سوف تجنب التحذير بي.

$file = "path/to/file";

if(file_exists($file)){
  $content = file_get_contents($file);
}

وتغيير ملف php.ini الملف

allow_url_fopen = On

allow_url_include = On
try {
   $site="http://www.google.com";
   $content = file_get_content($site);
   echo $content;
} catch (ErrorException $e) {
    // fix the url

}

set_error_handler(function ($errorNumber, $errorText, $errorFile,$errorLine ) 
{
    throw new ErrorException($errorText, 0, $errorNumber, $errorFile, $errorLine);
});

ويجب عليك أيضا تعيين

allow_url_use = On 

وفي php.ini لإيقاف تلقي التحذيرات.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top