开发者

File url check in php

I am trying to download a file and put its contents into the db using php. I am able to do that. But what if i have to check the url first and then if it exists, download, else report failure. How am i to do that?

say: $url = "...";

I need a condition:

开发者_Python百科if(file in the url exists)

{

      report success;

      download;

}

else

       report failure;


Just use the following code below to check if the file exists or not.

<?
$ct = @file_get_contents($url)

if(($ct != false)&&($ct != '')) {
//The file exists
}
?>

If the resource might take a long time to fetch, then you can set a timeout like this:

// Create the stream context
$context = stream_context_create(array(
'http' => array(
'timeout' => 5      // Timeout in seconds
)
));

// Fetch the URL's contents
$contents = @file_get_contents($this->url, 0, $context);

// Check for empties
if (!empty($contents)) {
//The file exists

}


if (fopen($url)) { report success; download; } else { report failure }

...Should do the trick.

Add an @ symbol before the function to prevent error output; so:

if (@fopen($url)) { report success; download; } else { report failure }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜