How do you create relative links in CodeIgniter?

Example. The controller has the following code:

class Main extends CI_Controller { public function index() { $this->load->view('main_view'); } public function create () { $this->load->view('create_view'); } } 

If I want to create a relative link to create , how do I do this? The following link does not always work. What is a convenient way to create relative links in CodeIngiter?

 <a href="create"> Create </a> 
+4
source share
4 answers
 <a href="<?= site_url('/main/create'); ?>"> Create </a> 

or simply:

 <?= anchor('/main/create', 'Create'); ?> 

Make sure you upload the url .

+4
source

You don’t need to do anything or download helpers, just keep in mind that the paths will refer to the URL, not the file system or controller.

Assuming your installation is in the root directory of your domain, let your current URL be http://localhost/class/method/var :

 <a href="/main/create">Will work from anywhere</a> <a href="create">Will go to http://localhost/class/method/var/create</a> <a href="../create">Will go to http://localhost/class/method/create</a> 

Relative paths are not your friend in Codeigniter, you'd better stick with full URLs (usually using helper functions like base_url() and site_url() ), or use a slash (relative to root). People mentioned using the <base> html tag, but I personally do not recommend it. You will have some very stupid URLs if you use ../../relative paths when you go deeper into URL segments. Example:

If you are here: http://localhost/controller/method/var1/var2/var3

The link may look like this: <a href="../../../../controller2/method/othervar"></a>

Probably not what you want, but it is an option that you can choose. I recommend using one of the other two.

+3
source

Here is a complete explanation of how this works.

Relative URLs with CodeIgniter

Hope this helps.

0
source

Just point out another alternative if you don't like the idea of ​​writing a php snippet in each href, and if other approaches don't satisfy you. You can use the generic <BASE > in the html header (for example, pointing to the root of your application), and then remember that each relative URL on your pages will respect that URL.

0
source

All Articles