Home > Net >  PHP script cannot see the parent directory
PHP script cannot see the parent directory

Time:07-04

I have a php script on a Ubuntu server which creates files. It works well with relative paths specified with `.' but it does not see the parent directory.

header('X-Real-Path1: ' . realpath('..')); <-- empty string
header('X-Real-Path2: ' . realpath('.')); <-- returns the actual directory
header('X-Real-Path3: ' . realpath(__DIR__)); <-- returns the actual directory
header('X-Real-Path4: ' . realpath(__DIR__. '/../')); <-- empty string

The user which runs the script has full access to the directories. Why doesn't the script see the directories?

CodePudding user response:

The user under which the process runs may not have access to that directory.

From the manual page:

The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return false.

Your are casting the output to string, and boolean false casts as empty string:

var_dump((string)false);
string(0) ""

CodePudding user response:

first check the permissions, and for testing you can set it to 777 just for now.

  1. Go to the script parent directory
  2. Do this command sudo chmod 777 -R [dirname]

This code should work fine

echo(realpath(__DIR__ . '/..'));

CodePudding user response:

You can just take the actual directory and cut the last folder, this actually works:

$dir = rtrim(__DIR__, 'ABCDEFGHIJKLMNOPQRSTUVWYXZabcdefghijklmnopqrstuvwyxz1234567890');

Example:

Actual directory: /home/jVufzc

RUN THE CODE

Output: /home/

If you don't want the final slash do this:

$dir = rtrim(__DIR__, 'ABCDEFGHIJKLMNOPQRSTUVWYXZabcdefghijklmnopqrstuvwyxz1234567890');
$dir = rtrim($dir, '/');

ABSOLUTELY put them in two different lines, or it will trim all the directory

  •  Tags:  
  • php
  • Related