- Retrieving the Response Body of a 404 Error in PHP
- Get response body from 404 in PHP
- What is the best way to get the URL of a 404’d file after redirect?
- PHP file_get_contents by an 404
- How do I generate a 404 Error in PHP? [duplicate]
- Php file_get_contents return 404
- Answer by Bria Randall
- Answer by Jayson Larsen
- Answer by Emmaline Hickman
- Answer by Davina Jensen
- Answer by Jones Compton
- PHP file_get_contents даёт 404, с браузера грузится?
Retrieving the Response Body of a 404 Error in PHP
One possible solution is to modify your code as shown below. The purpose of using «the» before the variable is to prevent PHP errors from displaying if the request fails. Here’s an example of how you can implement this: «` $responseCode = get_http_response_code($api); //This checks if the page exists «` Thank you, James McNee EDIT:
Get response body from 404 in PHP
While communicating with battle.net api, my aim is to retrieve the response body upon encountering a 404 error page. However, an error is hindering my progress.
There is an example in the documentation that includes the body, as shown in the screenshot below. Additionally, I have attached a screenshot of the PHP error I encountered. I would greatly appreciate any assistance.
This line of code evaluates whether the page exists by calling the function «get_http_response_code» on the API.
if($responseCode == 200) < //Page exists $api = "battle.net/apirequest. "; $json = file_get_contents($api); $schema = json_decode($json, true); $completeQuests = $schema['quests']; >else if ($responseCode == 404)
Furthermore, I am unable to identify the source of the error since even accessing the URL directly results in the appearance of JSON response.
If file_get_content encounters a failure condition, it won’t allow you to retrieve the content. In such cases, you’ll need to utilize a lower-level library, such as curl, to obtain the content.
How to detect PHP script is being used as ErrorDocument for 404, One way to do this would be simply look at the $_SERVER[‘REQUEST_URI’] and determine if it points at something invalid.
What is the best way to get the URL of a 404’d file after redirect?
My current project involves a PHP website that requires error logging to be performed on a database. To accomplish this task, I have established a .htaccess file in the following manner:
All the essential logging functions required for inserting the log are present in 404.php. However, I am facing difficulties in obtaining the URL of the file that caused the 404 error.
Displayed below are the items stored in the superglobal array $_SERVER.
[HTTP_HOST] => [HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 [HTTP_ACCEPT_LANGUAGE] => en-us,en;q=0.5 [HTTP_ACCEPT_ENCODING] => gzip,deflate [HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.7 [HTTP_KEEP_ALIVE] => 300 [HTTP_CONNECTION] => keep-alive [PATH] => /usr/local/bin:/usr/bin:/bin [SERVER_SIGNATURE] => [SERVER_SOFTWARE] => Apache/2.2.8 (Ubuntu) [SERVER_NAME] => [SERVER_ADDR] => [SERVER_PORT] => 80 [REMOTE_ADDR] => [DOCUMENT_ROOT] => [SERVER_ADMIN] => [no address given] [SCRIPT_FILENAME] => /404.php [REMOTE_PORT] => 19274 [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => GET [QUERY_STRING] => [REQUEST_URI] => /404.php [SCRIPT_NAME] => /404.php [PHP_SELF] => /404.php [REQUEST_TIME] =>I’m seeking recommendations. However, the HTTP_REFERER item, which is commonly suggested, appears to be non-existent.
The REQUEST_URI is intended to hold both the path and query of the URL that was requested.
How do I intercept a 404 error in PHP properly?, This will direct all non-existing URLs to your getFile.php script without generating a 404. Make sure you do output a 404 if the script does
PHP file_get_contents by an 404
I am receiving JSON arrays containing file_get_contents , but in case the page is not present, I aim to display a message stating «Player not found». However, currently, I encounter an error message.
Caution: file_get_contents (insert a URL that returns a 404 error) The function.file-get-contents]: failed failed to open the stream due to an unsuccessful HTTP request. The error message reads HTTP/1.1 404 Not Found, and this issue can be found in ——.
The error does not occur when the API returns a properly formatted JSON array.
$gegevens = file_get_contents(''); $array_2 = json_decode($gegevens, TRUE); $summonerid = $array_2[$naam]["id"];
Your code could become like this:
$gegevens = @file_get_contents(''); if ($gegevens !== FALSE) < $array_2 = json_decode($gegevens, TRUE); $summonerid = $array_2[$naam]["id"]; >else
The purpose of using @ in conjunction with file_get_contents is to prevent the display of PHP errors when request failed occurs. Additionally, if $summonerid is equivalent to 0 , it indicates that no player was found.
if (($gegevens = @file_get_contents('')) === false) < printf("Player not found!
\n"); return; > // . continue here .
The occurrence of an error message will be muted by @ in case file_get_contents() fails. The return value in such a scenario will be false . To prevent ambiguity with empty files, === should be used for comparison purposes. The retrieved false can be utilized for failure detection as needed.
Why won’t my PHP app send a 404 error?, Your code is technically correct. If you looked at the headers of that blank page, you’d see a 404 header, and other computers/programs would be able to
How do I generate a 404 Error in PHP? [duplicate]
Is there a method to replicate 404 error in PHP? Consider this URL: www.mydomain.com/user/[Username] that sends you to /profile.php?user=[username]. If the username isn’t registered, my intention is for the server to display my 404 Error page.
Below is a code snippet in PHP for your reference.
The status code can be communicated through the headers in HTTP. To set the status code, utilize the header() function available in PHP.
You might also consider delivering an error page to the web browser.
The $_SERVER\[‘SERVER_PROTOCOL’\] will hold either HTTP/1.0 or HTTP/1.1 .
Php file_get_contents return 404
Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,Making statements based on opinion; back them up with references or personal experience.,I have try also set a header with the user agent with stream_context_create, but not works.,yahoo.com is returning a 404 Error, but the url is correct and works under my Internet browser.
Use Curl function.It works fine for me.
Date,Open,High,Low,Close,Volume,Adj Close 2011-08-04,1.43,1.43,1.43,1.43,000,1.43 2011-08-03,1.43,1.43,1.43,1.43,000,1.43 2011-08-02,1.42,1.42,1.42,1.42,000,1.42 2011-08-01,1.44,1.44,1.44,1.44,000,1.44 2011-07-29,1.42,1.42,1.42,1.42,000,1.42 2011-07-28,1.43,1.43,1.43,1.43,000,1.43 2011-07-27,1.45,1.45,1.45,1.45,000,1.45
Answer by Bria Randall
If someone could spot the error in my Code, I would appreciate it! Thanks. The thing is that I get the Error Above with file_get_contents and I really don’t understand why.,What they do to work around this is spoof a browsers headers. Like pretend to be Mozilla Firefox instead of the sneaky PHP web scraper they are.,With some Echoes I got the URL parsed by the function and it is fine and valid, I do the request from my Browser and it is OK.
Here is my Code:
function getReadable($url)< $api_key='MYAPIKEY'; if(isset($url) && !empty($url))< // I tried changing to http, no 'www' etc. -THE URL IS VALID/The browser opens it normally- $requesturl='https://www.readability.com/api/content/v1/parser?url=' . urlencode($url) . '&token=' . $api_key; $response = file_get_contents($requesturl); // * here the code FAILS! * $g = json_decode($response); $article_link=$g->url; $article_author=''; if($g->author != null)< $article_author=$g->author; > $article_url=$g->url; $article_image=''; if($g->lead_image_url != null)< $article_image=$g->lead_image_url; > $article_excerpt=$g->excerpt; $toJSON=new jsonRes(); $toJSON->url=$article_link; $toJSON->author=$article_author; $toJSON->url=$article_url; $toJSON->image=$article_image; $toJSON->excerpt->$article_excerpt; $retJSONf=json_encode($toJSON); return $retJSONf; > > ?>
Answer by Jayson Larsen
I am trying to read a file from a php script. I tried both file_get_contents() and curl, but both of them return a 404 error. But when I use wget or use browser to view the url, it works without any trouble. Is there something I am missing here?,Verbose it. Check/fump the curl response/status and set a unique agent, look it up in logs. The target site may be filtering your requests based on the (empty) User-Agent header. Try using curl_setopt() to set CURLOPT_USERAGENT to a valid user agent, like:
$url = base_url()."assets/css/appln-style.css"; $stylesheet = file_get_contents($url); echo $stylesheet;
Answer by Emmaline Hickman
Don’t turn error reporting off just add @ infront of file_get_contents,file_get_content() will return false if it fails. keep in mind it can fail for reasons other than a 404 as well.,Warning: file_get_contents(http://www.qwtsgdyhtifon.co.uk) [function.file-get-contents]: failed to open stream: Permission denied in /home/mydomain/public_html/myscript.php on line 42 404,i get errors displaying and then the 404 echoed:
$html = file_get_contents(url); $p = '#]+href=("|\\')http://([^.]+\\.)?mydomain\\.com[^>]+>#i'; if (preg_match($p, $html))
Answer by Jolie Alexander
Have you recently changed any of your web hosting or moved your domain registration to a new registrar? This almost sounds like a DNS issue where the request is actually going to the wrong server because an old cached DNS entry is being used some of the time or every time., This almost sounds like a DNS issue where the request is actually going to the wrong server because an old cached DNS entry is being used some of the time or every time., It sounds like the domain name record at your domain registrar is still pointing to the name server for the old server as well., the server your running dvdcoverlinks.com on did it used to work and have you changed anything as i would suggest checking that allow_url_fopen is enabled in PHP.INI configuration file.
$strURL = 'http://dcl.vg.to/fetchme.php?id=11602'; $strContent = file_get_contents($strURL); echo $strContent;
Answer by Davina Jensen
CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.
$route['storage/item/(:any)'] = 'StorageController/item/$1';
Answer by Jones Compton
Checking if a Webpage URL exists or not is relatively easy in PHP. If the required URL does not exist, then it will return 404 error. The checking can be done with and without using cURL library.,Example 1: This example test a URL for 404 error without using cURL approach.,How to test a URL for 404 error in PHP?,How to check whether an array is empty using PHP?
PHP file_get_contents даёт 404, с браузера грузится?
Такое интересное дело, посмотрел в Firebug и увидели, что браузер тоже получает 404, но всё равно подгружает страницу, это как?
Чтобы во всём коде не добавлять curl, сделал функцию замену для file_get_contents
function filegetcontents($url) $c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
return iconv("windows-1251", "UTF-8",curl_exec($c));>
$c = curl_init('http://avtomarket.ru/catalog/Volvo/740/29673/'); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); $content = curl_exec($c);
Попробуйте с заголовком UA:
$opts = array( 'http'=>array( 'method'=>"GET", 'header'=> "User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36\r\n" ) ); $context = stream_context_create($opts); $file = file_get_contents('http://avtomarket.ru/catalog/Volvo/XC90/37116/', false, $context);
Даже если я с браузера(FF) захожу всё равно выдаётся 404 в заголовке. Это у них скорее баг, нежели фича
А у вас хоть одну страницу (любую) так загрузить получается?
Я к тому, что адрес для file_get_contents нужно указывать вместе с http://
или вы ошибку только тут в описании допустили?
Плюс, я бы рекомендовал использовать что-то вроде этого:
$context = stream_context_create( [ 'http' => [ 'method' => 'GET', 'protocol_version' => '1.1', 'header' => [ 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0', 'Connection: close', ], ] ); $stream = fopen('http://url', 'r', false, $context); $content = stream_get_contents($stream); //тут получаем страницу $data = stream_get_meta_data($stream); //тут получаем информацию, в том числе заголовки ответа
@TomaZ думаю это парсер просто обрезал.
там действительно 404 отдается, так что проще получить контент curl'ом
Да, наверно.
Насчет 404 не знаю, сейчас заходил, у меня 200.
p.s. вместо курла я обычно контекст юзаю, если ничего особенного не нужно.