CodeIgniter doesn't see images (using file_exi

2019-09-14 19:04发布

问题:

I'm learning CodeIgniter. I have a directory img with images (path /img/). I am trying to access it through CI view and check if exists with this code:

    $av = '../../../img/content/users/'.$userID.'.jpg';
    if(file_exists($av)) {
        $avatar = $av;
    } else {
    $avatar = 'img/content/users/none.jpg';
    }

Funny thing is, echoing <img src="'.$av.'"> works. What should I do?

回答1:

Use following steps

1) Create a custom config file name site_config.php in config file (/application/config/) and paste following code

<?php

$config['base_url'] = "http://".$_SERVER['SERVER_NAME'] . str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

if(!defined('DOCUMENT_ROOT')) define('DOCUMENT_ROOT',str_replace('system/application/config','',substr(__FILE__, 0, strrpos(__FILE__, '/'))));

$config['base_path']    =   constant("DOCUMENT_ROOT");
?>

2) Edit autoload.php to autoload site_config.php (/application/config/autoload.php)

$autoload['config'] = array('site_config');

3) Then using following code to view image

$image_path = $this->config->item('base_path').'folder_name/'.$userID.'.jpg';
if(file_exists($image_path)) {
  $avatar = $this->config->item('base_url').'folder_name/'.$userID.'.jpg';
} else {
  $avatar = $this->config->item('base_url').'default_folder_name/profile.jpg';
}
echo '<img src="'.$avatar.'" />';

I think it will help you



回答2:

CI always runs on index.php, so paths are always relative from there.

Assuming index.php and /img are at the same level in the root, try this:

$av = 'img/content/users/'.$userID.'.jpg';
if(is_file($av)) { // or better yet, make sure it's really an image
    $avatar = $av;
} else {
    $avatar = 'img/content/users/none.jpg';
}

Funny thing is, echoing <img src="'.$av.'"> works

It's because the browser is looking in a different place than the server. I'd recommend not using ../../relative/paths but using functions like base_url() and img(). When there are additional segments in the URL, relative paths break.



回答3:

URLs and file paths are not the same. From the current URL ../../../img/content/users may and likely is something completely different than the file path on the hard disk where the view file is located.



回答4:

Try this:

$av = './img/content/users/'.$userID.'.jpg';