southafricanrob
southafricanrob

Reputation: 351

PHP check if file exists in Wordpress

I am wanting to check if a video file exists on my server - if it does embed it else play the youtube embed instead.

(Local file and youtube urls are stored in separate Custom Fields, both are absolute paths)

I have the following code which based off other similar questions and the php manual seems to be correct however I always get the local video player embedded regardless of if the local file exists or not - cant for the life of me figure out what is wrong?

   <?php
        $localvideo = get_post_meta($post->ID, 'videoembed', true);
        if ( file_exists($localvideo)) {
            //embed video url stored in custom field 'videoembed'
            echo do_shortcode( '[video src='. $localvideo . ' ]');
        } else {
            //code to embed youtube video instead
            //echo to test if url in variable is correct
            echo $localvideo; 

        }
        clearstatcache();
    ?>

Upvotes: 1

Views: 6369

Answers (2)

southafricanrob
southafricanrob

Reputation: 351

The solution was that the file_exists string needed to be a relative path to the file without the preceding / ie my original file_exist check was effectively

$localvideo = 'http://localhost/wp-content/video/test.flv'

instead of

$localvideo = 'wp-content/video/test.flv'

Upvotes: 1

suresh
suresh

Reputation: 11

change file_exists to is_file() in your code for example: if ( is_file($localvideo)) {

Upvotes: 0

Related Questions