how to handle a 403 error with PHP

后端 未结 2 483
天命终不由人
天命终不由人 2020-12-22 02:08

I have built a php script that can sometimes have the server returns a 403 error message (forbidden access) because of the length and content of the data sent through the $_

相关标签:
2条回答
  • 2020-12-22 02:45

    It would be to set up a custom error document for 403 errors in Apache, and point this at a script to handle the error. Refer to the ErrorDocument documentation on how to do this, but it would be something along these lines:

    ErrorDocument 403 /custom_403_handler.php
    
    0 讨论(0)
  • 2020-12-22 03:07

    So I have three possible solutions for you.

    1. Check for URL errors and make sure the actual web page is specified. Its common reason for a web site to return the 403 Forbidden error, when the URL is pointing to a directory instead of a web page. Which can be done using HttpRequest Class in PHP. You can use http_get to perform GET request. You can also Test URL here.

      <?php
      $response = http_get("URL", array("timeout"=>1), $info);
      print_r($info);
      ?>
      

      Output:

      array (
         'effective_url' => 'URL',
         'response_code' => 403,
         .
         and so on
         )
      

      What is important for you is response_code with which you can play further.

    2. Use of curl.

      function http_response($url)
      { 
          $ch = curl_init(); 
          curl_setopt($ch, CURLOPT_URL, $url); 
          curl_setopt($ch, CURLOPT_HEADER, TRUE); 
          curl_setopt($ch, CURLOPT_NOBODY, TRUE); 
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
          $head = curl_exec($ch); 
          $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
          curl_close($ch); 
      
          if(!$head) 
          {  
           return FALSE; 
          } 
      
          return $httpCode;
      }
      
      $errorcode = http_response("URL");    //if success 200 otherwise different
      
    3. If you're sure the page you're trying to reach is correct, 403 Forbidden error message may be a mistake. Then you can only do two things either contact webmaster or use your own customize redirection. To do that add following line in .htaccess file and handle that error in forbidden.php

      ErrorDocument 403 /forbidden.php   
      
    0 讨论(0)
提交回复
热议问题