user2320402
user2320402

Reputation: 379

PHP open .txt file with full URL

I want to be able to read the contents of a file from its full domain and filepath, so something like:

http://www.example.com/files/file.txt

What I can't do in this instance is:

../files/file.txt

I have tried curl, fopen, file_get_contents and would rather use curl but cannot get it to work for any of them.

Is there an obvious reason why this isn't working that I am missing?

Here are the code snippets for each attempt, parhaps someone knows what's wrong with one of them?

Incidentally, if I could do ../files/file.txt it works for each option.

$file = "http://www.example.com/files/file.txt";

fopen:

$f=fopen($file,'r'); 
$data=''; 
while(!feof($f)) 
    $data.=fread($f,$size); 
fclose($f); 

curl:

function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

$data = curl($file);

file_get_contents:

$data = file_get_contents($file);

Thanks in advance for all help.

Upvotes: 1

Views: 5224

Answers (2)

Vladimir Ch
Vladimir Ch

Reputation: 547

Perhaps url fopen are disabled on your hosting and urls from another domains are just disabled?

php.ini var allow_url_fopen must be on

Upvotes: 0

sbstjn
sbstjn

Reputation: 2214

file_get_contents works fine for URLs with PHP 4 >= 4.3.0 and PHP 5:

"A URL can be used as a filename with this function if the fopen wrappers have been enabled"

Many shared hosters have this option disabled, or are using an older version of PHP and are blocking loading external files using PHP's safe mode.

Start with enabling error_reporting and have a look at your hosters web site to see if he's blocking external files.

Upvotes: 3

Related Questions