Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

linux - How do you get PHP, Symlinks and __FILE__ to work together nicely?

On localhost. I have the following directory structure:

/share/www/trunk/wp-content/plugins/otherfolders

/share/www/portfolio/wp-content/symlink

Where symlink is a symbolic link to /trunk/.../plugins/. Basically, this is because I need to test multiple WordPress installs and set them up, but I don't want to have to move plugins around and copy and paste them everywhere.

However, sometimes I need to crawl up the directory tree to include a config file:

 $root = dirname(dirname(dirname(dirname(__FILE__))));
      if (file_exists($root.'/wp-load.php')) {
          // WP 2.6
          require_once($root.'/wp-load.php');
      }

The folder always resolves to:

/share/www/trunk

Even when the plugin is being executed and included in

/share/www/portfolio/.

Is it possible in PHP to include files in the share/www/portfolio directory from a script executing in a symlink to the /share/www/trunk/.../plugins directory?

While this problem only happens on my test server, I'd like to have a safely distributable solution so crawling up an extra level is not an option.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem that I see with your code is that __FILE__ resolves symlinks automatically.

From the PHP Manual on Magic Constants

... Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved ...

You can try using $_SERVER["SCRIPT_FILENAME"] instead.

$root = realpath(dirname(dirname(dirname(dirname($_SERVER["SCRIPT_FILENAME"])))));
  if (file_exists($root.'/wp-load.php')) {
      // WP 2.6
      require_once($root.'/wp-load.php');
  }

Note that I added the realpath() function to the root directory. Depending on your setup, you may or may not need it.

EDIT: Use $_SERVER["SCRIPT_FILENAME"] instead of $_SERVER["PHP_SELF"] for the file system path.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...