Page 1 of 1

Hmm its not working

Posted: Thu Oct 06, 2005 9:53 pm
by gathem
Heres what im trying to do:

Theres a file within the same folder as thisFile.php
named compName.tim that basicly is just a text file that says "test". I want to use this file to open that file and read whats in it and then display it.
normaly this would not be a difficult task however I need it to work in multiple folders. The way i have it set up, a user can create a new folder ( with a random name) and then it will copy the files (this one included) into it. I need to be able to read the contents of the file no matter what the folder name is.

This is what I have done so far however I'm very open to suggestions of different methods of accomplishing the same task. does anyone have any suggestions?


Code: Select all

//thisFile.php

//*****************************************
//Function: getFileContents( $file )
//Parameter: accepts a variable containing the address
//   of the file you want to get the contents of
//Returns the contents of the file
//*****************************************
function getFileContents( $file )
{

$fp = fopen($file, "r") or die("couldn't open $file");                                                        while (!feof($fp)) 
     {
          $contents = fgets($fp, 1024);
     }
fclose($fp);
  
     settype($contents, string);
     return $contents;
}
//end getFileContents() function

$var4 = "compName.tim";
$coName = getFileContents($var4);

echo "<HR><P>$coName<P><HR>";
?>

Posted: Thu Oct 06, 2005 9:58 pm
by feyd
what's wrong with file_get_contents()?

anyways, your problem is you keep overwriting the existing contents of $contents with each iteration of the loop. You need to concatenate the contents instead:

Code: Select all

$fp = fopen($file, "r") or die("couldn't open $file");
$contents = '';
while (!feof($fp))
     {
          $contents .= fgets($fp, 1024);
     }
fclose($fp);
side note:

Code: Select all

settype($contents, string);
is firing a notice you may or may not be seeing.

Code: Select all

settype($contents, 'string');
is correct.

Posted: Thu Oct 06, 2005 10:57 pm
by gathem
The issue is not that it wont read the data the issue is that it says that the file does not exist because im not giving it a specific folder

Posted: Thu Oct 06, 2005 11:16 pm
by feyd
that would be correct behaviour if the file isn't in the current working directory..

Posted: Fri Oct 07, 2005 10:28 am
by gathem
The file is in the same directory, however its saying that the file doesnt exist, Ive tried everything i can think of as far as making this code work, any suggestions on how to fix it or go about it in a different way?

Posted: Fri Oct 07, 2005 10:50 am
by feyd
if the file exists in the same directory as the function, but is different from where you are calling the function, then it will not find it. If you don't understand, emit getcwd() to see what I mean.