PHP fopen filename. Is it relative or absolute?

33,486

Solution 1

Why not use use realpath() with your relative paths.

Also permission denied indicates that the folder you are trying access to is not readable and/or writable by the webserver or whatever user your PHP process runs under.

In addition, if you want to read/write files in one go from/to a variable, you might want to use file_get_contents() and file_put_contents().

Solution 2

Also, make sure that you're relative path is specified relative to the file where the function is being called (not necessarily where the actual code is).
In PHP use getcwd()(get current working directory; manual) to figure out which directory to base your relative path off of.

Solution 3

The PHP function itself is neither absolute nor relative, that depends on the path.

Both the errors you're getting are related to that specific path, either permissions or existence, so I'd recommend getting a path you know exists and you have access to and trying that (the current directory may be a good place). You may also temporary chmod the file and path, just to make sure you have read access. Print the results and any errors.

fopen("public/dan/new/apps/lovescopes/test.php");
fopen("./test.php");

If neither of those return errors, you'll know it was just a path issue.

Also, your PHP process may have different permissions than your user, so watch out for that.

Share:
33,486
Dan
Author by

Dan

Updated on July 09, 2022

Comments

  • Dan
    Dan almost 2 years

    I'm having problems with my paths and fopen with reference to my web server.

    I have a file saved in public/dan/new/apps/lovescopes/thisfile.php.

    thisfile.php will create a new file in public/internalServer/lovescopes/xml/2009/12 using fopen "x+".

    Now my errors show in the line where fopen is:

    1. If I type in the path as relative like ../../../../internalServer/lovescopes/xml/2009/12 I end up with a Permission Denied error.

    2. If I type an absolute path like /public/internalServer/lovescopes/xml/2009/12 I end up with "Failed to open Stream: No such File or Directory"

    I'm still confused if I should use relative or absolute paths. I have a ftp_nlist and it worked perfectly well with #2. Is Fopen the same?

    Also with the different error messages which I believe points to the same path, I don't know which way am I doing it right 1 or 2?