How can I display images with the Codeigniter php

2019-01-17 17:50发布

问题:

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.

回答1:

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.



回答2:

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

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


回答3:

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.



回答4:

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

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