Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 312
  • Last Modified:

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

1 Solution
Richard QuadlingSenior Software DeverloperCommented:
Typo ???

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

2 "" ?

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


$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 ...


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


This is probably the safest way to do it.

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now