PDA

View Full Version : Opening Files and Directories


sir pannels
07-14-2005, 08:42 PM
Hi There,

I have a bit of code that rips the content of a file.. the code is... $fh = fopen($nurl,"r");
$d="";
while($data = fgets($fh)) {
$d.=$data;
It takes $nurl from a txt box on a previous form, something likehttp://site.ext/var1/var2/var3.txt

However what I wish it to do is only need to be
http://site.ext/var1/var2/
The script should work out the var3(the file name) its self so the URL only needs to go as far as the directory the file is in.

I need to sort out some kind of loop so that it will run that code on every file in the directory so it needs to also work out how many files are in there.

Any one got any links or code to point me in the right direction?

Many Thanks,
Sir P

devinemke
07-14-2005, 08:49 PM
you need to loop thru the directory. if you have PHP5 then use scandir (http://www.php.net/scandir). if you have PHP4 then use opendir (http://www.php.net/opendir) and readdir (http://www.php.net/readdir).

BTW: a simpler way to grab the contents of a file is file_get_contents (http://www.php.net/file_get_contents) (PHP >= 4.3.0).

sir pannels
07-14-2005, 09:06 PM
cheers for the btw..

Got some questions about scandir.. if im correct the following code should do the above for each file in the directory, is that right?..
$dir = $nurl;
$files1 = scandir($dir);

print_r($files1);
$fh = fopen($files1[$i],"r");
$d="";
while($data = fgets($fh)) {
$d.=$data;


Cheers,
Sir P

devinemke
07-14-2005, 09:12 PM
what are you ultimately trying to do here? create a string that has the contents of every file in a directory? if so:

$contents = '';
$files = scandir($nurl);
foreach ($files as $value)
{
if ($value != '.' && $value != '..')
{
$contents .= file_get_contents($nurl . $value);
}
}

sir pannels
07-14-2005, 09:20 PM
yeah thats pretty much what I'm going for,only i dont want one long string with every file in, the string will get emptied everytime the loop runs. thank you.

How would I pull the file name out of that as well? so have a string with the file name?

Infact within that loop i plan to add each file to a MySQL DB, but im good with that bit its just running through each file.

Cheers
P

sir pannels
07-14-2005, 09:28 PM
sorry silly question, i will of course get the file names like $files[$1], i assume. Will have a bash and let you know :)

sir pannels
07-14-2005, 11:01 PM
Got it all working thanks very much for your help :D