Jump to content

test a URL and if 404 do a redirect.


DataRater

Recommended Posts

PHP 5

 

I'm trying to programatically check a URL and check whether it returns a 404 so I can do a redirect. So something like

 

if ( WhateverFunction('www'phppfreaks.com/PagesNoExist.html' == '404') {

    header("Location: www.Go.com/Getoutofhere.html");

  }

 

So I'd like to know what function WhateverFunction is and also any tips on how to use it.

 

Please help as it will be much appreciated.

 

Stephen

Link to comment
https://forums.phpfreaks.com/topic/191043-test-a-url-and-if-404-do-a-redirect/
Share on other sites

Well, you can do this which will check the physical existance of the url (again, existance the same as 404, but not 'just' 404)

//Returns 1:0, true:false
function fsocket_check($url) {
$res = (($ftest = @fopen($url, 'r')) === false) ? false : @fclose($ftest);
return ($res == TRUE) ? 1:0;
}

 

If you wish to go so far as to check the headers..

function fsocket_header_check($url) {
    $addr=parse_url($url);
    $host=$addr['host'];
    $path = $addr['path'];
    $headtxt = "";
    if($sock=fsockopen($host,80, $errno, $errstr, 3))
    {
    fputs($sock, "HEAD $path HTTP/1.0\r\nHost: $host\r\n\r\n");
    while(!feof($sock))
    {
    $headtxt .= fgets($sock);
    }
    }
    $pos1 = stripos($headtxt, "200 OK");
    return ($pos1 === false) ? 0:1 ;
    } 

 

EDIT: Stupidquotes took over.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.