0

I am currently developing a very simple cms using wampserver and I'm planning to upload it to my reserverd server once it's done. the other day when I was debugging my code through the remote server i got my page loaded without any style or image. I reviewed and simply deleted some '/' and that worked just fine. For example I changed URLs like this: before change:

<link rel="stylesheet" href="/css/styles.css"/>

After change:

<link rel="stylesheet" href="css/styles.css"/>

When I applied these new URLs to my local project, once again I faced pages without styles or images or js or whatever...what should I do?

iDeveloper
  • 1,699
  • 22
  • 47
Parham
  • 3
  • 4

1 Answers1

0

By removing the / you changed it to relative paths.

So you must now think about your path structure.

For example, if the project was placed in a folder, so the root is: http://localhost/mycms/ then you go to ./mycms/cats the relative path to your CSS would be translated to: ./mycms/cats/css/styles.css which would break it.

You should look into using absolute paths to assets. For example:

<link rel="stylesheet" href="//localhost/mycms/css/styles.css"/>

This can be achieved by defining or detecting the current URL path from $_SERVER variables and prepending your hostname.

So something like which stores in a constant which you can then use throughout your code which will result in the correct absolute path to the webroot:

<?php
define('SITE_URL', rtrim(sprintf(
    '%s://%s/%s',
    isset($_SERVER['HTTPS']) || $_SERVER["SERVER_PORT"] == "443"  ? 'https' : 'http',
    $_SERVER['HTTP_HOST'],
    trim(dirname($_SERVER['SCRIPT_NAME']), '/')
), '/'));

echo SITE_URL;

Then just echo that in your templates.

<link rel="stylesheet" href="<?= SITE_URL ?>/css/styles.css"/>