fopen and the working directory

I'm trying to open a text file using the fopen("file name"", "r"),  however I'm getting an error to the effect that the file can't be found.

On my local IIS server, where the fopen command works file, if I execute getcwd() it returns the current IIS directory. However, on my webserver thie returns c:\windows\system32\inetsrv. How can I force the PHP fopen to look in the same directory as the PHP script which is executing the fopen command?

Any help would be much appreciated

PAulC.
LVL 3
htgitsAsked:
Who is Participating?
 
Richard QuadlingSenior Software DeveloperCommented:
Typo ???

fopen("file name"", "r"),

2 "" ?

I would STRONGLY recommend that you use something like ...

<?php

$r_file = fopen('./filename', 'r');

?>

Basically, tell the script WHICH directory.

. means THIS directory.

This is normally the directory that the main script is loaded from. If you are using fopen in an include file which is in a different directory to the main .php file, then the include directory is NOT the directory examined as . means the directory that the script is in.

If ANY code has changed the current directory beforehand, then you would need to know about this.

You could also go over the top and get the path for the .php script and use that ...

<?php

$r_file = fopen(dirname($_SERVER["SCRIPT_FILENAME"]) . DIRECTORY_SEPARATOR . 'filename', 'r');

?>

This is probably the safest way to do it.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.