Basic Authentication in a GET request, url_exists() function.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chromis
    New Member
    • Jan 2008
    • 113

    Basic Authentication in a GET request, url_exists() function.

    Hi there,

    I have a directory with windows authentication on it and i want my script to check whether an image file exists at a URL which corresponds to a image in the protected directory.

    I started with this function:

    [code=php]

    $url = "http://website.com/protected/images/image1.jpg";
    url_exists($url );

    function url_exists($url ){
    $url = str_replace("ht tp://", "", $url);
    if (strstr($url, "/")) {
    $url = explode("/", $url, 2);
    $url[1] = "/".$url[1];
    } else {
    $url = array($url, "/");
    }

    $fh = fsockopen($url[0], 80);
    if ($fh) {
    fputs($fh,"GET ".$url[1]." HTTP/1.1\nHost:".$ur l[0]."\n\n");
    if (fread($fh, 22) == "HTTP/1.1 404 Not Found") { return FALSE; }
    else { return TRUE; }

    } else { return FALSE;}
    }
    [/code]

    I kept on getting true for my results which made me think it was working at first. However when i output the result of this call:

    [code=php]
    fputs($fh,"GET ".$url[1]." HTTP/1.1\nHost:".$ur l[0]."\n\n");
    echo fread($fh, 100);
    [/code]

    It returns :

    Code:
    HTTP/1.1 401 Unauthorized Content-Length: 1656 Content-Type: text/html Server: Microsoft-IIS/6.0 HTTP/1.1 401 Unauthorized Content-Length: 1656 Content-Type: text/html Server: Microsoft-IIS/6.0
    I think this means i need to work authentication into my GET request somehow, is this correct and how would I go about this?

    PHP Version: 5.1.2

    Thanks,

    Chromis
  • chromis
    New Member
    • Jan 2008
    • 113

    #2
    I found a solution to the problem but as I understand it, it isnt very secure as it sends the authorisation credentials in plain text:

    [code=PHP]
    function url_exists($url ){
    $url = str_replace("ht tp://", "", $url);
    if (strstr($url, "/")) {
    $url = explode("/", $url, 2);
    $url[1] = "/".$url[1];
    } else {
    $url = array($url, "/");
    }

    $fh = fsockopen($url[0], 80);
    if ($fh) {
    $getString = "GET ".$url[1]." HTTP/1.1\nHost:".$ur l[0]."\nAuthorizati on: Basic ".base64_encode ("USERNAME:PASS WORD")."\r\n\n" ;
    fputs($fh,$getS tring);

    if (fread($fh, 15) == "HTTP/1.1 200 OK") { return TRUE; }
    else if (fread($fh, 22) == "HTTP/1.1 404 Not Found") { return FALSE; }
    else return FALSE;

    // HTTP/1.1 200 OK

    echo fread($fh, 100);

    } else { return FALSE; }
    }
    [/code]

    Does anyone have any better ideas for what I could use?

    Thanks,

    Chromis

    Comment

    Working...