0

I want to ask what is the better to write this sequence of if else statements :

$dir = base_url()."assets/produits/";
  $img_src = $dir."none.png";

  if (!empty($row->nShape)) {
      $nom = $row->nShape;

  if (file_exists($dir.$nom.".JPEG")) {
      $img_src = $dir.$nom.".JPEG";
  }
  else
  if (file_exists($dir.$nom.".jpg")) {
      $img_src = $dir.$nom.".jpg";
  }
  else
  if (file_exists($dir.$nom.".jpeg")) {
      $img_src = $dir.$nom.".jpeg";
  }
  }

The Full MVC Pattern

After implementing : https://stackoverflow.com/a/32034937/5203821 answer

The View File

<div class="container">
    <?=$message?>
    <?php
    foreach ($rows as $row) {
    $dir = base_url()."assets/produits/";
    $img_src = $dir."none.png";

    if (!empty($row->nShape)) {
            $nom = $row->nShape;

    $type = array(".JPEG", ".jpg", ".jpeg");

    foreach ($type as $ext) {
        if (file_exists($dir.$nom.$ext)) {
            $img_src = $dir.$nom.$ext;
            break;
        }
    }
}

    ?>

    <div class="list-group">
        <a class="list-group-item col-md-4" target="_blanc" href="<?=site_url()?>/produits/detail/<?=$row->nProduct?>" title="<?=$row->sSort?>"><b><img src="<?=$img_src?>" alt="<?=$row->nShape?>" class="img-rounded product"><?=$row->sSearch?></b></a>
    </div>
    <?php
    }
     ?>
    <div class="spacer"></div>
</div>

Model File

<?php

defined('BASEPATH') OR exit('No direct script access allowed');
    class Product_model extends CI_Model{

      function getProduct($product_id){
        $this->db->from('tequivalent')
                  ->where('nReference',$product_id)
                  ->join('tProduct','tProduct.nProduct=tequivalent.nProduct1');

                $query = $this->db->get();
                $ret['rows'] = $query->result();
                $ret['number'] = $query->num_rows();
                $ret['id'] = $product_id;

                return $ret;
      }
    }

Controller File

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Produits extends CI_Controller {


    function index($product_id='')
    {

        if($product_id==NULL){
            redirect();
        }
        $this->load->model('Product_model');
        $query = $this->Product_model->getProduct($product_id = $this->uri->segment(3, 0));

        if($query['number']>0){
            $results['message']="<h2>Clique sur une Référence pour Plus de Detail</h2>";
            $results['number'] = $query['number'];
            $results['rows'] = $query['rows'];
        }else{
            $results['message'] = "<p>Oops! Y'a Aucun Résultat pour cette recherche</p>";
            $results['message'] .= "<a class='btn btn-lg btn-danger' href=".site_url().">Acceuil</a>";
            $results['number'] = $query['number'];
            $results['rows'] = $query['rows'];
            $results['id'] = $query['id'];
        }

        $this->load->view('constants/header');
        $this->load->view('produits',$results);
        $this->load->view('constants/footer');

}
}

The above code if the the full MVC Pattern since I'm using Codeigniter And thanks to all of you for your contributions

Community
  • 1
  • 1
  • If you cannot standardize the way the files are saved, I would probably `glob()` the directory and do a case non-sensitive match against the resulting array. – jeroen Aug 16 '15 at 11:55

2 Answers2

1

you can use this function taken from here, that ignores case:

function fileExists($fileName, $caseSensitive = true) {

    if(file_exists($fileName)) {
        return $fileName;
    }
    if($caseSensitive) return false;

    // Handle case insensitive requests            
    $directoryName = dirname($fileName);
    $fileArray = glob($directoryName . '/*', GLOB_NOSORT);
    $fileNameLowerCase = strtolower($fileName);
    foreach($fileArray as $file) {
        if(strtolower($file) == $fileNameLowerCase) {
            return $file;
        }
    }
    return false;
}

now you can iterate:

$allowedExtensions = ["jpeg","jpg"];

foreach($allowedExtensions as $ext){
     if(fileExists("youfFileName.$ext"),false){
         //do your code..
     }
}
Community
  • 1
  • 1
Daniel Krom
  • 9,751
  • 3
  • 43
  • 44
1

You could probably consolidate the three if statements using a foreach loop:

dir = base_url()."assets/produits/";
    $img_src = $dir."none.png";

    if (!empty($row->nShape)) {
            $nom = $row->nShape;

    $type = array(".JPEG", ".jpg", ".jpeg");

    foreach ($type as $ext) {
        if (file_exists($dir.$nom.$ext)) {
            $img_src = $dir.$nom.$ext;
            break;
        }
    }
}

By adding the extensions to an array can significantly reduce the redundant if statements.

l'L'l
  • 44,951
  • 10
  • 95
  • 146
  • it shows the none placeholder, and image file exists – Rahmani Seif El Moulouk Aug 16 '15 at 12:21
  • Add `echo $img_src;` after `$img_src = $dir.$nom.$ext;` and see if you are getting any output. – l'L'l Aug 16 '15 at 12:24
  • it shows the `none.png` placeholder I've added the MVC pattern check it out – Rahmani Seif El Moulouk Aug 16 '15 at 12:31
  • I've added the full code, you can check what I've done – Rahmani Seif El Moulouk Aug 16 '15 at 12:37
  • Try adding the echo line that I mentioned (between `$img_src = $dir.$nom.$ext;` and `break`). – l'L'l Aug 16 '15 at 12:38
  • still the same problem – Rahmani Seif El Moulouk Aug 16 '15 at 12:48
  • The code in my answer should do the same as your original code; It's unclear if the code is reaching that point or not, since you haven't specified the result of the echo. – l'L'l Aug 16 '15 at 12:52
  • Check the code linked and see [line 13](https://gist.github.com/anonymous/f23571d47607c93b9c1a#file-gistfile1-txt-L13), and [line 18](https://gist.github.com/anonymous/f23571d47607c93b9c1a#file-gistfile1-txt-L18) ... add that to your code as a test and report back the result. https://gist.github.com/anonymous/f23571d47607c93b9c1a#file-gistfile1-txt – l'L'l Aug 16 '15 at 12:58
  • Here's the results : http://www.awesomescreenshot.com/image/489865/69395f3f59b138d1e9d23ecbf8f03fe4 – Rahmani Seif El Moulouk Aug 16 '15 at 13:02
  • Okay, so if you've added echo test two also, and that is not showing then your code is never reached there. – l'L'l Aug 16 '15 at 13:06
  • no, it's not performing the `foreach` loop it's just showing the variable at the top – Rahmani Seif El Moulouk Aug 16 '15 at 13:08
  • It's not performing the foreach (where the `$ext` is set) because there's no echo test two — only echo test one is shown. So the fileexists is thinking that it's not one of the valid types. One more test you should do... is near echo test one do: `echo $dir.$nom;` – l'L'l Aug 16 '15 at 13:09
  • Check this: https://gist.github.com/anonymous/f3df38f09ed4476e8fea#file-gistfile1-txt-L14 – l'L'l Aug 16 '15 at 13:17
  • The name is correct http://www.awesomescreenshot.com/image/489882/348c8beeee88305de04900a3dc3bfb17 – Rahmani Seif El Moulouk Aug 16 '15 at 13:19
  • Try the [second test](https://gist.github.com/anonymous/f3df38f09ed4476e8fea#file-gistfile1-txt-L14) also, that's going to tell us if the extension is being added. – l'L'l Aug 16 '15 at 13:21
  • Yes the extension is being added : http://www.awesomescreenshot.com/image/489891/f95aa0da9e7d3aacee33db3307161ab0 – Rahmani Seif El Moulouk Aug 16 '15 at 13:24
  • Okay, then I think the `$img_src` is getting set to `none.png` again after being set with `$ext`... Try your code like this: https://gist.github.com/anonymous/25abee2ef137cbd0a7a3. It moves the `$img_src = $dir."none.png";` out of the loop. – l'L'l Aug 16 '15 at 13:27
  • The Same problem, but when moving the $img_src = $dir.$nom.$ext; out of the condition it works, but without it we can't test if the file exists or not – Rahmani Seif El Moulouk Aug 16 '15 at 13:32
  • Right, so one more thing you'll need to do is add an else: https://gist.github.com/anonymous/f495055f9fbb0e9aabb3 – l'L'l Aug 16 '15 at 13:34
  • I forgot a `}` after the else... https://gist.github.com/anonymous/f2f887254df4be84fb81 – l'L'l Aug 16 '15 at 13:40
  • I mean it still showing the "none" placeholder, I think the `file_exists` is not working because when taking the `$img_src` out of the `if` statement working fine – Rahmani Seif El Moulouk Aug 16 '15 at 13:53
  • You mean moving `$img_src` at the top or somewhere else? I thought you said it was working at some point... so not understanding what's wrong now. Perhaps it is the `fileexists`... maybe put and echo underneath that to see if it's ever reached. – l'L'l Aug 16 '15 at 13:58
  • That's the old code though... so of course there's not going to be any difference. – l'L'l Aug 16 '15 at 14:06
  • Sorry sir, I'm bothering you with me, but I do really need your help because I'm newbie and I need this to work : here is the results : http://s28.postimg.org/69e7lc8fx/Untitled.png – Rahmani Seif El Moulouk Aug 16 '15 at 14:14
  • Sir check out this one its truly testing all the extension but it does not determiner whether it exists or not : http://i59.tinypic.com/21adda0.png – Rahmani Seif El Moulouk Aug 16 '15 at 14:26
  • Yes, it seems like that – Rahmani Seif El Moulouk Aug 16 '15 at 14:41
  • Your path might be missing a `/` is the only thing I can think of ... Maybe try...: `if (file_exists($dir."/".$nom.$ext)))`, although looking at your path it seems to already include it. – l'L'l Aug 16 '15 at 14:47
  • Yes, the me confusing, is that it gets file url and it exists but it does not test it – Rahmani Seif El Moulouk Aug 16 '15 at 14:49
  • Yes! It's very odd, **and should work** — it even calls the else, so it's obviously testing something.. Right before the `if (file_exists...` do: `var_dump(file_exists($dir.$nom.$ext));` – l'L'l Aug 16 '15 at 14:51
  • Also try changing it to be `if (file_exists($dir.$nom.$ext) == 1) {` – l'L'l Aug 16 '15 at 14:54
  • it says `bool(false)` – Rahmani Seif El Moulouk Aug 16 '15 at 14:54
  • That is very strange... do `var_dump(base_url()); var_dump($dir); var_dump($nom); var_dump($ext);` – l'L'l Aug 16 '15 at 14:56
  • That's what I got : http://www.awesomescreenshot.com/image/489977/58efdd000aa548d84cdac4747be858d3 – Rahmani Seif El Moulouk Aug 16 '15 at 15:01
  • Did you try it like `if (file_exists($dir.$nom.$ext) == 1) {` also? There must be something we aren't seeing as to why it's returning `false` — because from everything I can see it's TRUE! – l'L'l Aug 16 '15 at 15:04
  • You know what... I don't think those files do exist on your server. Because in the last sample you showed with the actual webpage the image in just a placeholder, but there's no actual image. – l'L'l Aug 16 '15 at 15:07