开发者

How can I display images with the Codeigniter php framework? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago.

How can I display images with the Codeigniter php framework?

I want to fetch an image from 开发者_运维百科the images folder inside views.

I used this code in one of the views php files:

<img border="0" src="images/hed_05.jpg" width="61" height="133">

But it is not working.


Images, css, javascript, pdfs, xml... anything that is allowed to be accessed directly should not be living in your application directory. You can do it, but you really shouldn't. Create a new folder at the root of your directory for these files, they should not be mixed into your application, for example: in your views folder.

  1. Chances are, you're using an .htaccess file, which is only allowing certain directories to be accessed via http. This is very good for security reasons, you want to stop any attempt to access your controllers and models directly. This is also why we check if BASEPATH is defined at the top of most files, and exit('No direct script access.') if not.
  2. To get the correct path to these resources (js/css/images), you can't use relative paths, because we aren't using a normal directory structure. The url /users/login is not loading files from the directory /users/login, it probably doesn't even exist. These are just uri segments that the bootstrap uses to know which class, method, and params to use.

To get the correct path, either use a forward slash (assuming your app and assets are in the root directory, not a subdirectory) like this:

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

Or your best bet, use an absolute url:

// References your $config['base_url']
<img src="<?php echo site_url('images/myimage.jpg'); ?>" />

Equivalent to:

<img src="http://mydomain.com/images/myimage.jpg" />

There are helpers built into CI that you can optionally use as well, but this is really all you need to know.


Please see the CI User Guide/HTML Helper img() tag:

echo img('images/picture.jpg');
// gives <img src="http://site.com/images/picture.jpg" />


You can also just set your base href in the <head>:

<base href="<?php echo site_url(); ?>" />

Now any image, css file and other asset will be relative to your base URL.

<base href="http://site.com/" />

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

is in effect

<img src="http://site.com/images/foo.jpg" />

Your images should be outside of the application folder (say in /images) however.


Perhaps the path in the src attribute is incorrect. Maybe try

<img border="0" src="/images/hed_05.jpg" width="61" height="133">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜