In my web hosting server, file_get_contents()
function is disabled. I am looking for an alternative. please help
views:
566answers:
8You can open the file with fopen
, get the contents of the file and use them? And maybe cURL is usefull to you? http://php.net/manual/en/book.curl.php
I assume you are trying to access a file remotely through http:// or ftp://.
In theory, there are alternatives like fread() and, if all else fails, fsockopen(). But if the provider is any good at what they do, those will be disabled too.
file_get_contents() pretty much does the following:
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
Since file_get_contents() is disabled, I'm pretty convinced the above won't work either though.
Depending on what you are trying to read, and in my experience hosts disable remote file reading usually, you might have other options. If you are trying to read remote files (over the network, ie http etc.) You could look into the cURL library functions
Use the PEAR package Compat. It is like a official replacement of native PHP functions with PHP coded solutions.
require_once 'PHP/Compat.php';
PHP_Compat::loadFunction('file_get_contents');
Or, if you don't wish to use the class, you can load it manually.
require_once 'PHP/Compat/Function/file_put_contents.php';
- All compat functions are wrapped by
if(!function_exists())
so it is really fail save if your webhoster upgrades the server features later. - All functions can be used exactly as the same as the native PHP, also the related constants are available!
- List of all available functions
The most obvious reason why file_get_contents()
is disabled is because it loads the whole file in main memory first. The code from code_burgar could pose problems if your hoster has assigned you a very low memory limit.
As a general rule, use file_get_contents()
(or -replacement) only when you are sure the file to be loaded is small. With SplFileObject
you can walk trough a file line-by-line with a convenient interface. Use this in case your file is big.
If all else fails, there's always cURL. There's a good chance it's installed.
$ch = curl_init(); $timeout = 5; // set to zero for no timeout curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $content = curl_exec($ch); curl_close($ch);