Search code examples
phpapachedirectory-structurevhosts

Make / link to the different directory VHost, PHP MVC


Im trying to create my own MVC. My folder structure is following:

 localhost (root, htdocs)
   - Project_1
     - images
       - test.jpg
     - App
       - Controllers
       - Models
       - Views
     - Classes

Now if i create an index file under views folder and add this:

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

this does not load test.jpg because / points to localhost (root/htdocs) folder and does not point to Project_1

My question is what do i need to do to make / point to Project_1 directory instead of root, i know it has to do something with VHosts but unfortunately i do not know any tutorial that would explain the problem.

Any ideas/suggestions or links to tutorials will be appreciated. Thank you

NOTE: I do not want to do the following:

  define('ROOT', '/localhost/Project_1/');

and then use it like

  <img src="<?=ROOT?>images/test.jpg" />

this is what im trying to avoid


Solution

  • If all you are looking to do is change the base path of images then you might be able to get away with using the <base> HTML element.

    Taken from MDN -
    The HTML element specifies the base URL to use for all relative URLs contained within a document.

    As for the PHP side of things, the option you categorically dismissed would probably be the best way - defining a constant pointing to the correct path -

    define('ROOT', '/localhost/Project_1/');
    

    If you want to get into the settings of your virtual host, then you'll be able to set your document root directly from the virtual host's definition. Here is a simple example -

    <VirtualHost *:80>
        DocumentRoot /var/www/localhost/Project_1/
        ServerName Project_1.com
    </VirtualHost>
    

    Within this virtual host, your $_SERVER['DOCUMENT_ROOT'] will now be /var/www/localhost/Project_1/.