douzi7219 2016-03-27 18:06
浏览 65
已采纳

在PHP中,使用file_get_contents && file_get_contents会返回不同的值吗?

I was doing a mild test with the file_get_contents. The aim is to test if 2 urls do exist then see if they both have a certain string in them.

Something like:

$check_url1 = "www.example_1.com";
$check_url2 = "www.example_2.com";


if( 
$view_loaded_url1= @file_get_contents($check_url1)&&
$view_loaded_url2= @file_get_contents($check_url2)  )                                                            
{

    var_dump($view_loaded_url1); //RETURNS boolean true 

    var_dump($view_loaded_url2); //Returns the Contents of the page i.e: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Str.....etc

How do you make both return the contents of the page and not the boolean?

Because there is a second if to check if they both contain a certain string.

Something like:

if(stristr($view_loaded_url1, 'I am the String') && stristr($view_loaded_url2, 'I am the String') {

//....This part cannot go through because $view_loaded_url1 and $view_loaded_url2 are returning different datatype

}

Is this a normal behavior?.... has anyone else encountered this?

SCREENSHOT: enter image description here

  • 写回答

2条回答 默认 最新

  • dtwknzk3764 2016-03-27 18:12
    关注

    file_get_contents never returns true. It returns file (or URL) contents or false if the contents retrieval failed.

    The reason that $view_loaded_url1 gets the value true is that the expression is evaluated as follows (see parentheses):

    if( 
      $view_loaded_url1 = (@file_get_contents($check_url1) && ($view_loaded_url2 = @file_get_contents($check_url2))
      )                                                            
    

    The fix is to group the operators:

    if( 
      ($view_loaded_url1 = @file_get_contents($check_url1)) &&
      ($view_loaded_url2 = @file_get_contents($check_url2))
      )                                                            
    {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?