Reading in a file

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
User avatar
Templeton Peck
Forum Commoner
Posts: 45
Joined: Sun May 11, 2003 7:51 pm

Reading in a file

Post by Templeton Peck »

Can someone tell me whats wrong with this code: Its not an invalid file, cause I tested the handle message by putting an invalid file to make sure it was checking right.

<?php

function readTextFile($handle, $numToRead)
{
if($handle == -1)
{
echo "Error- Invalid File Handle";
return;
}

$fileContents = "";
$fileContents == fread($handle,$numToRead);
return $fileContents;
}

function openTextFile($fileName)
{
$handle = -1;

if(is_readable($fileName) == true)
{
$handle = fopen($fileName,"r");
}

return $handle;
}

$contents = "";
$handler = "";
$handler = openTextFile('people.txt');
$contents = readTextFile($handler,10);
echo $contents;
?>

thanks :)
User avatar
Sevengraff
Forum Contributor
Posts: 232
Joined: Thu Apr 25, 2002 9:34 pm
Location: California USA
Contact:

Post by Sevengraff »

what error message are you getting? You are probally putting the filesize as too small.

It seems silly to have two functions to do one job. try this.

Code: Select all

function getFile( $FN )
{
	if(!file_exists($FN)) {
		echo 'Bad file name';
		return;
	}
	$fp = fopen ($FN, "r");
	$contents = fread ($fp, filesize ($FN));
	fclose ($fp);
	return $contents;
}
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

also note there is file_get_contents() for php 4.3+
file_get_contents

(PHP 4 >= 4.3.0)
file_get_contents -- Reads entire file into a string
Description
string file_get_contents ( string filename [, int use_include_path [, resource context]])

Identical to file(), except that file_get_contents() returns the file in a string.

Note: This function is binary-safe.
User avatar
Templeton Peck
Forum Commoner
Posts: 45
Joined: Sun May 11, 2003 7:51 pm

Post by Templeton Peck »

that did the trick, thanks :)
Post Reply