file_get_contents function not working in version of php

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mccommunity
Forum Commoner
Posts: 62
Joined: Mon Oct 07, 2002 8:55 am

file_get_contents function not working in version of php

Post 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.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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 ?
User avatar
Kriek
Forum Contributor
Posts: 238
Joined: Wed May 29, 2002 3:46 am
Location: Florida
Contact:

Post 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.
Post Reply