0

I'm trying out a lot of PHP example projects. For most examples I need to setup a VirtualHost in the Apache config (httpd-vhosts.conf) to get them working.

But sometimes I just want to copy or test a project, without going through the hassle of making another VirtualHost. It would be nice if everything still works too when I try http://localhost/ProjectDir/ instead of http://ProjectDir/

In Phalcon I know how to fix the root directory, by changing the config or with setBaseUri(), but this is a bit inconvenient to change every time. It would be nice if this could be done automatically somehow. (I do realize that in this way I can not use absolute URLs or links inside the HTML (starting with /) since that would mean the root folder of the Apache server then but this could be solved with an automatically configured prefix-variable).

  • How do other developers handle this situation, or do you really choose between a virtual host or http://localhost/ProjectDir/ ?

  • Is there a way for a PHP script to detect if it's running in a virtual host or in a subdir of localhost?

UPDATE

Found out I could use $_SERVER['SERVER_NAME'] to determine if it's 'localhost' or something else. Not very elegant, but it's a sufficient solution, I guess.

Dylan
  • 8,273
  • 16
  • 82
  • 136
  • 1
    If think you will get relevent answer of your question - http://stackoverflow.com/questions/2820723/how-to-get-base-url-with-php – jewelhuq Dec 16 '15 at 00:15

1 Answers1

0

Within html views:

I like to use absolute paths from the document root for ease. (Relative paths are flexible but can get complicated.)

<img src="/images/foo.jpg">

Of course if I want to move the project into a sub directory, the path above will need to be adjusted. (We could use the html base tag, but that can have side effects.):

<img src="/subdir/images/foo.jpg">

We could use a variable in our views that we prefix to links and asset paths:

<?php
     $base = '/subdir'; // Set somewhere.
?>
<img src="<?php echo $base ?>/images/foo.jpg">

To set the $base variable automatically, I sometimes assign it to Symfony/Component/HttpFoundation/Request::getBasePath(). (There are some other useful utility methods in that component.) Or use something similar from another framework/library/component.

Assigning a value in one place in a central configuration isn't that much of a hardship. I find prefixing paths within the views more of a pain.

In one of my development environments, I use a symlink from the directory root to the project directories directory root:

/var/www -> /sites/example.com/pub

And swap it as and when needed. You can avoid writing multiple virtual host configs that way and skip the other steps mentioned above.

However, configurable prefixes can be useful in other ways:

$base_cdn    = 'http://cdn.example.com';
$base_nav    = '/subdir';
$base_static = '//static.example.com/foo';
Community
  • 1
  • 1
Progrock
  • 6,765
  • 1
  • 16
  • 25