Welcome to the Question2Answer Q&A. There's also a demo if you just want to try it out.
+1 vote
1.2k views
in Q2A Core by
Hello to everyone, I'm going to share with you a scenario that I have, because maybe you can help me.

I'm building a code for to do something if it find an image and to do another thing if it not find it.

I'm using the rooturl parameter of the qa-theme class to get the relative path to my site, then I join it with the additional path where the image should be located.

After, I need to check if the image exists, but I'm using the file_exists function of PHP and it always retunrs false, maybe because it not recognize the relative path of the site.

Now, I think that I must to use an q2a function that it whether recognize the relative path and it return true when the image exists.

Thank you so much for your support!
Q2A version: 1.7.3
by
Can you give an example of what you're passing to file_exists? Have you checked that you have the correct path?
by
The code is like this:

//The next line is to get the postid of the question
$postid_num = $most_sectionquery[1]['postid'];

//The next line is to complete the image's path           
$imgpath = $context->rooturl . 'images/' . $postid_num . '.jpg';
               
//This code is to set an image background for questions if the img file exist, else set a plain color background for questions
$imgexist = file_exists($imgpath);
if ($imgexist) {
    $context->output('
        <!-- Now, set the image path as source of the img element -->
        <div class="thumb"><img alt="img" src="' . $imgpath . '"></div>');
}
else {
    $context->output('
        <!-- In this case just apply the style to the question background  -->
        <div class="thumb"></div>');
}

Then the $imgexist variable always get false from file_exist function, then never do what I need to do in the code within if condition.

But when I use the next code it whether works and I don't see what is the difference...

<div class="thumb"><img alt="img" src="' . $context->rooturl . 'images/photo_name.jpg"></div>

The relative path is like this: "../qa-theme/advanced_theme_name/"

1 Answer

+3 votes
by
selected by
 
Best answer
OK I see the problem - you are passing the "front end" path into file_exists. You should be passing a server path.

The front end path is what the browser sees and is relative to the domain. So "../qa-theme/etc" tells the browser to look for the URL "http://example.com/qa-theme/etc"

The server path is the full file system path on your server, for example "/var/www/yoursite/qa-theme/etc". You can get the server path to your theme directory using: __DIR__

For example: file_exists(__DIR__.'/images/'.$post_num.'.jpg');

Keep your $imgpath for using in the <img> tag.
by
Hello Scott, thank you for your fast and correct answer and I'm sorry for my late comment about it. This was the best answer to my issue and I want to thank you again because you help me a lot!
...