Page 1 of 1

Reading in a file

Posted: Fri May 16, 2003 10:43 pm
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 :)

Posted: Fri May 16, 2003 11:22 pm
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;
}

Posted: Sat May 17, 2003 12:57 am
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.

Posted: Sat May 17, 2003 3:14 pm
by Templeton Peck
that did the trick, thanks :)