Difference between using $base_url and not using it on CodeIgniter - php

So basically, what's the difference between the two approach:
<img src="<?php print base_url(); ?>img/test.png" />
<!-- and -->
<img src="/img/test.png" />
I'm having the same result on my website. Might as well remove the URL helper ($this->load->helper('url')) on my controller to cut extra process since they're just the same.
If there is an advantage of adding the helper at all, please let me know.

The difference is if you ever want to put your application in a subdirectory.
If what was / now becomes /application/ all your site root references will break.
It just makes your application free to be installed anywhere and won't require being on the site root.

In my experience with CodeIgniter, using base_url() is a best practice. It ultimately guarantees that your links will be correct (similar to the way adding ../ works when the folder you need is 1 level higher). Also I have had problems in the past with CodeIgniter adding the url in config[base_url] twice if I forgot to put http:// in it. Simple mistake, but it can throw the whole project off. So, basically the difference is that it guarantees the path is the right one, but isn't necessary at all times.

There is no difference if you're using root path of domain.
It's kind like a feature that if you're using it you can migrate easier to any domain or inside directory path.
One more advantage is when you're developing API or RSS feed, the image path or anything else will be written as complete URL so the consumer can use it easily.

I've discovered another thing usin site_url(). It is the only way I found to set a / at the end of my urls.
Eg : will result in http://domaine.tld/controller
On the other hand http://domaine.tld/controller/
hope that helps somebody

Related

"Staging" site and relative HTML paths in Codeigniter

I'm developing a web application on the same domain as the "production" application -- it's just a sub directory of the top level website. Something like: www.site.com/v3/...
I've seen several people trying to get relative paths working with CodeIgniter -- in the past I had just stuck base_url() in every HTML image declaration of the "v3" site, but I bought an HTML site template recently and embedding <?php base_url() ?> in hundreds of HTML tags seems so inefficient.
Hoping someone can help with this -- I'd like to be able to transition the dev code (aka "/v3/") directly into use without searching and replacing all of those HTML references.
This is exactly the purpose of $config['base_url'] in application/config/config.php. If you set it to http://site.com/v3/, it will be reflected across your site everywhere you use base_url() or site_url()
However, I should note that using base_url() or site_url() across your entire site for every src, href, etc is bad practice. You're invoking the PHP interpreter like mad.
A much better solution is to tell your HTML document about your base using the <base> tag: <base href="<?= site_url();?>"> in the <head>.
There you have it. You use site_url() once, and from now on you can just use:
<a href='controller/action'>My Link</a> and <img src='my_image.png'/>
In general and as an overall principle, when you find yourself duplicating yourself... find a way to remove that duplication. Keep it DRY.
Thanks for all the help, folks.
After reading about the potential issues with the tag, I re-thought my approach -- I created a sub-domain of my main site (something like dev.mysite.com). That way I can work on the code exactly as it will appear on the production version, with only a base URL change in CI's config.php.
For now this seems the most simple solution, since calling the php pre-processor for every HTML tag that needs a relative path is exhausting and inefficient, and using the tag can lead to inconsistent results.

CakePHP simple, easy links

I dislike the Html->link() method. I appreciate it, but it uglies up the code and I don't believe that something so basic should require a method. However, in my project, I find I must use it if I want to have proper URLs. I'll accept that, but I want to know that I have to before continuing making links in this (large) project.
I've attempted to find some ways to get the cakeURL in a view. Nothing worked out.
My goal is to go from this:
<?=$this->Html->link('quality view', array('controller' => 'quals', 'action' => 'show')); ?>
To this:
<a href="<?=URL.'quals/show'?>">
But I cannot write or find a way to get such a constant working if I change the page's URL. (even something such as visiting /quals/ and /quals will show different URLs)
I also dislike the link method, I find it overkill for adding attributes like class, id and target="_blank" to my links.
I do this for links:
<a class="myclass" href="<?php echo $this->Html->url(array('controller'=>'my_controller','action'=>'my_action','plugin'=>false)); ?>">My Anchor Text</a>
So, I still use the HTML helper to get the URL, but the html element I code myself. I would recommend doing it that way, rather than hard-coding the URLs. This is the Cake way to do it, and it allows you to take full advantage of Cake's inbuilt routing functionality in routes.php, and create pretty routes without having to hard-code or remember them in more than one place.
It also makes it easier for others looking at your code in future - eg. does the hard-coded 'quals/show' link refer to the quals/show directory in your webroot? Or does it refer to the show action of the quals controller? (and it only gets more complex when you start working with plugins). If you use the html helper to create URL's, all that stuff is immediately clear.
If you want to make it look tidy, you could break it into two lines like this:
<?php $url = $this->Html->url(array('controller'=>'my_controller','action'=>'my_action','plugin'=>false)); ?>
<a class="myclass" href="<?php echo $url; ?>" >My Anchor Text</a>
If you've got a large project, it's even more reason to use Cake's helpers for URLs. It may seem like a good idea now, but hard coding them will give you a big headache at some point in the future.
There are actually very serious considerations for using HtmlHelper::link()!
When you're using the HtmlHelper for building links:
You have one central plase to define all routes in the application. The URL structure will always be the same as the one defined in Config/routes.php. When you change something there all links in the site will automatically reflect these changes
Reverse Routing
Easy application maintenance
SEO/Sitemapping
So if you use it you gain the abbility to change the structure of your application with minor changes, otherwise if you change one link you'd have to go through all the places it is used and change it manually.
As #joshua.paling said hardcoding the URLs is not a good idea since you'll have a lot of headaches with any change to the structure. Best is to use HtmlHelper's link() and/or url() methods.

Best method to replicate a website

I have recently created a directory for a customer of mine. The website is complete however he wants a replicated version of the website so he can test the website and learn how to use it.
To replicate his website fully it will take hours as I will have to change every hyperlink and URL in the website.
As my customer is being a little pushy and wants it done quickly I was wondering if it is posible to create a test website and add a little javascript that will replace his URL each time (until I create a full testing solution?).
For example if it was:
Test
it would replace it to:
Is this posible?
Is it recommended for the time being, until I create a full test solution?
You really should use relative paths so the files interact in relation to each other, regardless of where the files live.
That said, here is a possible quick JS solution you can use for the time being while you make your links relative instead of absolute:
$("a").each(function() {
var href = this.href;
href = href.replace("mydomain.com/", "mydomain.com/test/");
this.href = href;
});
Open up the site files in Notepad++ or any editor that supports file replacement, then do a replace through files (N++ will do this automatically for you), replacing the live URL with a config variable, then set the URL variable as desired for the test site.
Now you have a config variable for the URL, it will be easy if the client wants to change domain or you want to deploy elsewhere.
It is certainly possible to sort out your hyperlinks with javascript, specifically it would be really easy with a framework like jQuery.
$('a').each(Function(e){
e.attr('href', e.attr('href').replace(/http:\/\/mainsite.com/gi, 'http://newsite.com'));
});
Hopefully the URLs in your css files, link hrefs and so on would be relative, otherwise you would need to change those too. At this point a php solution would be more appropriate.
The wget command-line utility has a --convert-links option. If you download a web site using that option, wget will convert the links in such a way that "local browsing works reliably."

Hyperlink starting slash?

In my php script I created a constant variable that defines the base url to be put in my hyperlinks, but do I really need this?
Here is an example of what I mean.
I have this:
// base url is only defined once and reused throughout
define("__BASE_URL","http://localhost/test1/");
print '<a href="'.__BASE_URL.'index.php?var1=open/>Open</a>';
(I have a lot of these spread throughout my script.)
I tried this and it works:
print '<a href="index.php?var1=open/>Open</a>';
So which way is the proper way on doing this? I noticed the second way even works on loading images, css, and javascript files.
It really comes down to how you're structuring your site. Relative URLs are great (by doing href="index.php" you're reallying saying href="./index.php"), but they can start to become messy when you begin spreading pages over multiple directories.
Personally I like to base all of my relative URLs off of the root directory, meaning that all of my URLs start with a slash ('/'). That way it doesn't matter if my script is in / or /admin, as I will always have a constant reference point - the document root - as opposed to some relative directory in the structure.
Your first example, storing document paths in variables, really starts to come in handy when you begin developing larger systems where you want the paths to be configurable. For example, maybe you want your system admins to be able to define where images are pulled from, or where the cached downloads are.
So really consider your use cases and size of your system.
Also keep in mind that if you ever move the script to another server that your URLs and directory structures may change, which could cause havoc (ex., you might have your script moved to a different subdomain, into the document root, etc.). A lot of people will drop in Apache's mod_rewrite in this case.
It depends. Without the __BASE_URL, your link will be relative to the current document. In your case, that means index.php must be in the same directory as the file that has the index.php link on it.
If you have the __BASE_URL, then the link will work no matter where its containing file is located (i.e. doesn't have to be in same directory as index.php).
Another option is to use a starting slash only. Then your link will be relative to your domain root:
print '<a href="/index.php?var1=open/>Open</a>';
In other words, the above link would point to http://localhost/index.php.
It sounds like your question is regarding absolute vs relative URLs. Are you going for portability? It's generally best to use relative URLs, especially if you plan to work in a test environment and then later transfer files to production.

html/php: how to handle absolute url's?

Is the html <base> tag safe to use in terms of browser support? Or should I generate a root path with PHP which i then add like this somepage which makes up a absolute url.
using the base tag like this <base href="<?=BASE?>" /> I am then able to use links like this
somepage
now I am fully aware that it would be much easier to just do this without using the base tag:
somepage
but how do I test locally then with a base url of http://localhost/testsite/ ???
edit:
thanks guys, your the people who make the stackoverflow community so great :)
My advice would be to use absolute URLs beginning with a slash, and just set up a virtual host that uses /localhost/testsite/ as its document root. Then you could leave the absolute URLs and just access your site at something like http://testsite/ locally.
You've definitely given this some thought but I would like to throw one more consideration into the mix. If you are writing a web application, you should construct it in such a way that you can install it into any sub-directory in the future and it will continue to work with little change.
This means that href's, src's, action's and even HTTP Location headers will need to be aware of such a change. That's why I recommend prepending your uri's with <?php echo SITE_BASE ?> or whatever you want to call it.
Debate can rage on as to whether SITE_BASE should contain a trailing slash.
I like the first option, outputting a base directory in PHP tags
somepage
the very best. This makes your site independent from which directory it is installed in (you may not be able to change virtual host settings on shared hosting packages). It is also easy to outsource image files to a different server/subdomain if ever need be.
<base> is safe to use in terms of browser support, but I personally recommend strongly against using it for reasons of code maintainability. <base> changes the rules for how URLs are processed; you need to keep the base in mind for all relative URLs; and is very easy to overlook. From a programming perspective, it feels like a dirty fix.
Comming back to this question 2 years later, I now realise that the best way to handle absolute URLs is to put the URL into a wrapper function, for example like this:
somepage
the wrapper function then gives you full control over the URL handling
function url($url){
if(strpos($url,'/')===0){
return 'http://localhost/testsite'.$url;
}else{
return $url;
}
}

Categories