how to know if a certain resource exist?

For instance, I want to know if these files exists.

http://www.stackoverflow.com/favicon.ico
http://www.stackoverflow.com/reset.css

and then download it ( if exixts obviously ).

Answers


<?php

if( ( $file = file_get_contents( 'http://www.stackoverflow.com/favicon.ico' ) ) ) {
    echo "file exists.";
    file_put_contents( 'favicon.ico', $file );
}
else {
    echo "File does not exist.";
}

Try this:

<?php
$ch = curl_init();

$url    = 'YOUR_URL_HERE'; // the url you want to check

curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 20 );
curl_setopt( $ch, CURLOPT_USERAGENT, $_SERVER[ 'HTTP_USER_AGENT' ] );

// make "HEAD" request
curl_setopt( $ch, CURLOPT_HEADER, true );
curl_setopt( $ch, CURLOPT_NOBODY, true );

$res    = curl_exec( $ch );
$res    = explode( ' ', substr( $res, 0, strpos( $res, "\n" ) ) );

// if 404, file does not exist
if( $res[ 1 ] != 404 ) {
    $file = file_get_contents( $url ); 
} else {
    // This url does not exist
    $file = '';
}

curl_close( $ch );
?>

Hope this helps.


Need Your Help

CasperJS waitFor*() has very unclear behaviour

javascript jquery web-scraping phantomjs casperjs

I'm trying to understand how CasperJS work in order to use it on my tests. What i try to accomplish is to take a screenshot of some element of the page when they are ready and fully loaded, i'm using

Understanding OOP and static in Java

java oop

Suppose you have class A and class B. Class A is the main class which builds a frame with a GUI. It contains all the GUI variables (such as buttons, labels, strings) along with whatever methods tha...