a7omiton
a7omiton

Reputation: 1617

php file exists returns nothing always - CodeIgniter

I'm wanting to display images. The user can add up to 7 images, but they can also add less than 7 if needed.

I searched around and saw that file_exists() is the function I'm after, but I've tried a couple of ways and it always gives me no image.

Here's one way I tried:

<?php if(file_exists(base_url() . "photos/" . $p['p_id'] . "_5.jpg")):?>
    <div class="single">
       <a href="<?php echo base_url();?>photos/<?php echo $p['p_id'];?>_5.jpg" rel="lightbox[image]">
         <img src="<?php echo base_url();?>photos/<?php echo $p['p_id'];?>_5.jpg" style="width:100px; height:100px;"/>
       </a>
    </div>
<?php endif; ?>

Then I searched around and found out that its not a good idea to define the path inside the function, so I defined it outside:

<?php $path = base_url() . "photos/" . $p['p_id'] . "_";?>
     <?php $img4 = $path . "4.jpg";?>
      <?php if(file_exists($img4)):?>

which didn't work either.I'm testing with 4 images being in the folder 'photos' so I know there should be 4 images being displayed. Any ideas on how I should fix it would be great. Thanks

Upvotes: 3

Views: 5797

Answers (2)

Rick Calder
Rick Calder

Reputation: 18695

File exists requires a directory path not a URL, a URL will always return false.

    <?php 
    for($i=1; $i < 7; $i++):
    {
    $img = $path . $i . ".jpg";
    $url=getimagesize($img);
    if(!is_array($url))
    {
    ?>
    <div class="single">
            <a href="<?php echo base_url();?>images/<?php echo $product[0]['product_id'];?>_<?php echo $i; ?>.jpg" rel="lightbox[productimage]">
                  <img src="<?php echo base_url();?>images/<?php echo $product[0]['product_id'];?>_<?php echo $i; ?>.jpg" style="width:100px; height:100px;"/>
                </a>
            </div>
    <?php
    }
    }
    ?>

Be forewarned this is a touch on the slow side, but it does work with URL's on the server.

Upvotes: 1

Ardy Dedase
Ardy Dedase

Reputation: 1088

The function file_exists accepts file path as its parameter and not the url like what you're using now which is CodeIgniter's base_url().

You should use the FCPATH constant which points to your codeigniter app's base directory. This is what you should assign to your path (depending on where your image files are located in your application directory):

<?php $path = FCPATH . "htdocs/images/" . $product[0]['product_id'] . "_";?> 

But for some reason if really you need to use the base_url(). You can use get_headers() which checks the headers returned by the url in an associative array and false on failure. From the headers returned you can determine whether the image url is valid or not. More about get_headers().

Hope it helps.

Cheers,

Ardy

Upvotes: 4

Related Questions