Page 1 of 1

file_get_contents function not working in version of php

Posted: Wed Sep 03, 2003 3:40 pm
by mccommunity
I was using file_get_contents ( $buff = file_get_contents($genericfile); ) to grab the contents of a generic file and putting it into a string. I had this up and running fine but they have decided to regress to an older version of php which does not support this. So now my scripts are not working that rely on this function. Is there an identical function or does someone have one written. Any help is appreciated.

Posted: Wed Sep 03, 2003 4:14 pm
by volka

Code: Select all

<?php
function get_contents($path, $chunkSize=4096)
{
	$fd = @fopen($path, "rb");
	if ($fd === false)
		return false;
	$contents = '';
	while(!feof($fd))
		$contents .= fread($fd, $chunkSize);
	fclose($fd);
	return $contents;
}
?>
Did they tell you a reason for using an older version of php ?

Posted: Wed Sep 03, 2003 5:04 pm
by Kriek
For PHP versions equal to or greater than 4.3.0, use the file_get_contents() function.

Code: Select all

<?php
    $tag = 'http://example.com/file.php';
    $get = file_get_contents($tag) or die('Could not read file!');
    echo $get;
?>
For earlier PHP versions use the file() function in conjunction with the implode() function.

Code: Select all

<?php
    $tag = 'http://example.com/file.php';
    $get = implode('', file($tag)) or die('Could not read file!');
    echo $get;
?>
The file_get_contents() function is identical to the file() function, except that file_get_contents() returns the file in a string, while file() returns the file in a array, thus the need for implode() usage. Note file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.