fopen and the working directory

Posted on 2006-03-25
Last Modified: 2013-12-13
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

Question by:htgits
    1 Comment
    LVL 40

    Accepted Solution

    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

    6 Surprising Benefits of Threat Intelligence

    All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

    Join & Write a Comment

    Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
    Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
    The viewer will learn how to dynamically set the form action using jQuery.
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now