简体   繁体   中英

How to correctly link files?

From my previous experience, I've almost always had problems with linking files with my website projects.

For example, linking CSS styles, Javascript files and including files in PHP. The problem is, that on my PC, the directory of my project was /www/project-name/ and when I put the project on a server, the directory would be just /www/ . When I uploaded the project to a server, images wouldn't show, styles wouldn't work, database connections wasn't set, functions were not defined etc...

So my question is: What is the best and most efficient way to link/include files?

Something that will work no matter what the directory of the project is, and possibly, if I include project/includes/mysql.class.php in file1.php , and I move that file to a different directory, it would still properly include project/includes/mysql.class.php

You should use relative paths.

Instead of specifying the full path ('/www/project-name/includes/whatever.php'), use a path relative to the current location:

'./includes/whatever.php'

you can define the document root directory of project and then, include all files depending on it

put

define(DOC_ROOT, realpath(direname(__FILE__)); 

in your front controller, and when you have to include a file

include(DOC_ROOT . "/includes/file.php");

all frameworks uses this method

我建议使用相对路径(例如../style.css或../../style.css)../将父目录引用到当前文件。

This is what I do, in general.

I use root relative urls inside html (eg src="/images/logo.jpg" ). This way I can just copy the html from one page and past it in another without having to worry about the link not working becase the other page is inside a folder.

I relative urls in css, because all the resources I use inside the css, like images, I keep in the same folder as the css file (or a sub-directory of it). I mostly do this because it is shorter ( url(img/background.jpg); vs. url(/css/img/background.jpg); ). Minor added bonus is you could just copy the css folder to create a new theme based on the old one, without having to change all the urls in the css.

In PHP I use include($_SERVER['DOCUMENT_ROOT'] . '/includes/mysql.php'); . You can just copy past the code into another file in another folder and it will still work.

The only time I rarely need to hardcode paths is inside htaccess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM