We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 24724
    • 6 Posts
    Hello everyone,

    After trying and trying and trying, I’ve finally decided to ask for help. I am attempting to check to see if a file exist, and if so, do one action, and if not, do another. Simple right? Well that’s what I thought.

    I run an automotive site, and would like the header image to change, based on the make of the car the client is interested in. For example, if you are looking at Ford.html, you will see a Ford.jpg in the header. If you are looking at Chevy.html, you will see Chevy.jpg in the header, etc... I use [*alias*] for the filename, some keywords here and there, and for the name of the jpeg as well.

    So, on page Ford.html, you will see a Ford.jpg, and the word Ford scattered throughout the page. Also, Ford.jpg is a file located in /assets/images/Ford.jpg. Make sense?

    Okay, here is what I got so far.
    In my header template I have [[CarPic]].
    And here is the snippet I created called CarPic.

    $filename = '/assets/images/[*alias*].jpg';
    
    if (file_exists($filename)) {
       echo "file". $filename. " exists";
       echo "<img src=\"$filename\" alt=\"[*alias*] car pic\">";
    } else {
       echo $filename. " does NOT exist";
       echo "<img src=\"/assets/images/Lexus.jpg\" alt=\"car pic\">";
    }
    
    


    Obviously, I hope, I want to show a picture of whatever car is relevent. If nothing is relevent, I’ll show a picture of a Lexus. Well, no matter what I do, the above code ALWAYS shows Lexus.jpg. Or, file_exists, always returns false. Ugh!

    So, when I use the above code I see a Lexus on every page. If I reverse the statements (exists and does not exist), I see exactly what I want on Ford.html and Chevy.html etc... But, if no picture exists (i.e. home.html), I see nothing.

    Notice for debugging purposes I am echoing $filename everytime. $filename echos correctly, returning /assets/images/Ford.jpg or whatever.

    Funny thing, if I run the code exactly as I have it above and visit my Ford.html page, I will see "/assets/images/Ford.jpg does NOT exist" then a picture of a Lexus. If I copy and past "/assets/images/Ford.jpg" into my URL, I will see the picture of the Ford! LOL.

    For fun, or if it helps, you can see all this stuff in action at denvertransmissions.com. The site is far from done, but you’ll get the idea of what I’m talking about. Down at the bottom of every page you will see "Transmission Repair By Make" and a list of a bunch of cars. I have only done Ford, Dodge, and Jeep so far.
      • 7923
      • 4,213 Posts
      Try

      $filename = '/assets/images/'.$modx->documentObject['alias'].'.jpg';
      
      if (file_exists($modx->config['base_path'].$filename)) {
         echo "file". $filename. " exists";
         echo "<img src=\"$filename\" alt=\"[*alias*] car pic\">";
      } else {
         echo $filename. " does NOT exist";
         echo "<img src=\"/assets/images/Lexus.jpg\" alt=\"car pic\">";
      }
      



        "He can have a lollipop any time he wants to. That's what it means to be a programmer."
        • 24724
        • 6 Posts
        Nope!

        Doesn’t work either. I just cut and pasted your code in and now nothing returns. Not even the echo statements are returned. I viewed the source code from the web browser just to be sure. Nothing there.

        I’m going to put it back to how I had it in my origional post
          • 22303 MODX Staff
          • 10,725 Posts
          Hate to ask, but is your page cached? If so, uncheck that option or call your snippet with non-cacheable tags (i.e. [!CarPic!]

          If that’s not it, instead of echo statements, assign the output to a variable and return it. This is actually the preferrable way to return content from a snippet.
            • 24724
            • 6 Posts
            Getting close! But still no mangos!

            OpenGeek,
            pages ARE NOT cached
            I also changed the snippet to non-cacheable tags like you suggested [!CarPic!]
            I also assigned the output to a variable and return it.

            The following code returns false (file_exist returns else). The [*alias*] is preventing file_exist from returning true.
            $filename = '[*alias*].jpg';
            $dir = $_SERVER["DOCUMENT_ROOT"].'/assets/images/';
            
            if (file_exists($dir.$filename)) {
               echo $dir.$filename. " exists";
               $NewPic ='<img src=/assets/images/'.$filename.'>';
            } else {
               echo $dir.$filename. " does NOT exist";
               $NewPic ='<img src="/assets/images/Lexus.jpg" alt="car pic">';
            }
            
            return $NewPic;
            


            If I get rid of [*alias*] and hardcode something in there, it works just fine.
            $filename = 'Ford.jpg';
            $dir = $_SERVER["DOCUMENT_ROOT"].'/assets/images/';
            
            if (file_exists($dir.$filename)) {
               echo $dir.$filename. " exists";
               $NewPic ='<img src=/assets/images/'.$filename.'>';
            } else {
               echo $dir.$filename. " does NOT exist";
               $NewPic ='<img src="/assets/images/Lexus.jpg" alt="car pic">';
            }
            
            return $NewPic;
            


            I forgot why (I’ve tried a hundred variations of the above) but I needed to include $_SERVER["DOCUMENT_ROOT"] for file_exists to return true.

            $dir = $_SERVER["DOCUMENT_ROOT"].'/assets/images/';
            


            If I leave out $_SERVER["DOCUMENT_ROOT"], like this, you would think it would work.
            $dir = '/assets/images/';
            

            But it doesn’t. The above code makes file_exists return false.

            So it’s safe to say that I finally got my if file_exists statement working correctly. The problem now lies in the variable $filename and passing [*alias*].jpg to it correctly.
              • 22303 MODX Staff
              • 10,725 Posts
              Tags are not parsed in php strings within a snippet unless you return it as the content from that snippet. The $modx->documentObject[’alias’] that doze suggested you use will solve that issue.

              And, also as doze suggested, use $modx->config[’base_path’] to get the full path to the file on the server so file_exists can find it properly.
              if (file_exists($modx->config['base_path'] . $filename)) {...

              where $filename == ’assets/images/’ as base_path already includes the trailing slash
                • 24724
                • 6 Posts
                THANKS GUYS! GOT IT! smiley

                Either this
                $filename = $modx->documentObject['alias'].'.jpg';
                $dir = $modx->config['base_path'].'assets/images/';
                


                or this
                $filename = $modx->documentObject['alias'].'.jpg';
                $dir = $_SERVER["DOCUMENT_ROOT"].'/assets/images/';
                

                works!

                Which of the above is suggested? Doesn’t $modx->config[’base_path’] dip into the database causing slightly more overhead and a decrease in speed. (I know I’m being picky and splitting hairs now. But just so I understand and know how to write better more efficient code in the future).

                Thanks Again!
                  • 22303 MODX Staff
                  • 10,725 Posts
                  Quote from: redonion at Oct 09, 2006, 08:36 PM

                  Which of the above is suggested? Doesn’t $modx->config[’base_path’] dip into the database causing slightly more overhead and a decrease in speed. (I know I’m being picky and splitting hairs now. But just so I understand and know how to write better more efficient code in the future).
                  I suggest using the base_path configuration; it is always loaded (no db hit) and available. Plus, I believe on some configurations, you cannot depend on the document root server setting; this alleviates that altogether.
                    • 28042 ☆ A M B ☆
                    • 24,524 Posts
                    No, using $modx->documentObject[’whatever’] will not cause an extra database hit. The parser fills its documentObject array from the database when it starts parsing anyway, so you always have the document’s values available. Using it instead of [*whatever*] inside of a snippet will avoid the extra parsing of the tags, whether you "echo" or "return", though.
                      Studying MODX in the desert - http://sottwell.com
                      Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
                      Join the Slack Community - http://modx.org
                      • 7923
                      • 4,213 Posts
                      So the code I posted would probably work if you remove extra / before assets/images...

                      I would suggest also to use

                      echo ’<img src="’.$modx->config["base_url"].$filename.’" alt="[*alias*] car pic">’;

                      to print out the image src, if you are going to be using friendly alias paths..


                        "He can have a lollipop any time he wants to. That's what it means to be a programmer."