Detecting if a file exists in wordpress theme? - php

I am creating a wordpress template.
I am displaying one out of a directory of videos, as in
<video controls preload="auto" autoplay loop poster="<?= item_image; ?>">
<source src="<?= $item_video_mp4; ?>" type='video/mp4' />
<source src="<?= $item_video_webm; ?>" type='video/webm' />
</video>
However, in some cases, there is no video file for the item. In that case, I'd just like to display alternate content.
I was trying to use php's file_exists() but I read that it only works with local paths, not urls. So I was trying to use a local relative path to to files.
My url to the videos is calculated from the post title:
$item_path = '/wp-content/uploads/item_media/';
$item_name = get_the_title();
$item_video_mp4 = $item_path . $item_name .'.mp4';
This works, it displays the video and poster frame if they exist. The problem is, I need to detect if the video does not exist.
Since the php template is in /wp-content/themes/mytheme as typical I was trying to use
$filepath = '../../uploads/item_media/'. $item_name .'.mp4';
if (file_exists($filepath)) {
echo "The file $filepath exists";
} else {
echo "The file $filepath does not exist";
}
But the text always returns false.
Any ideas?
UPDATE
I have also tried this for the path:
$filepath = WP_CONTENT_URL . '/uploads/item_media/'. $item_name .'.mp4'
Which echoes
"http://des.dev/wp-content/uploads/item_media/4595DW.mp4 does not exist"
Even though it does.

This seems to work, not sure if it's the best way:
$filepath = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/item_media/'. $ring .'.mp4'

You should try using this instead:
$filepath = WP_CONTENT_URL . '/uploads/item_media/'. $item_name .'.mp4';
if (file_exists($_SERVER['DOCUMENT_ROOT'] . $filepath)) {
...
The problem is that PHP's file_exists function takes a relative or an absolute path, and it doesn't look like either one is matching up with your filesystem structure. The $_SERVER['DOCUMENT_ROOT'] . section above will prepend your Apache DocumentRoot setting to the path you are checking for, making the parameter to file_exists be an absolute path.

Related

How to display an image from a folder using PHP variable in a HTML tag?

I just want to display an image from a directory using PHP. But I could not. I have tried all the below ways.
<?php
/* Getting file name */
$document_root = $_SERVER['DOCUMENT_ROOT'];
$replace = str_replace('/',"\\",$document_root);
$filename = "/excel.png";
//$image_path = $replace."\imagesupload\uploads".$filename;
$image_path = $document_root."/imagesupload/uploads".$filename;
echo $image_path;
//echo '<img src="../admin/upload/' . $display_img . '" width="' . $width . 'px" height="120px"/>';
?>
<html>
<body>
<img src="<?php echo $image_path; ?>" />
</body>
</html>
The above code gives the following output. But the path I gave was correct.
I think this one will help you
<img src="uploads/<?php echo $file.png;?>" />
you are providing a path to file which belongs to server-side and not accessible by the browser , if imageuploads is the root of your application you can do something like this:
<?php
$filename = "excel.png";
?>
<html>
<body>
<img src="/uploads/<?php echo $filename?>" />
</body>
</html>
this should work:
$filename = "/excel.png";
$image_path = "/imagesupload/uploads".$filename;
echo '<img src="' . $image_path. ' "/>';
The DOCUMENT ROOT variable gives the absolute path of the folder in the server machine
DOCUMENT_ROOT=/var/www/example
DOCUMENT_ROOT=C:/wamp/httpdocs
What you're looking for is the relative path on the domain, so you should be using HTTP HOST
HTTP_HOST=www.example.com
That way you can build up your image url using the website absolute path and not your computer's absolute path.
Of course you can always just build a relative path to the folder you're in:
Assuming the script is in the www folder:
<img src='./<?=$filename;?>' />

How to display storage image in laravel blade?

I have stored my image with following code
if (isset($image)) {
// make unique name for image
$currentDate = Carbon::now()->toDateString();
$imagename = $slug . '-' . $currentDate . '-' . uniqid() . '.' . $image->getClientOriginalExtension();
// check category dir is exists
if (!Storage::disk('public')->exists('category')) {
Storage::disk('public')->makeDirectory('category');
}
// resize image for category and upload
$category = Image::make($image)->resize(1600,479)->stream();
Storage::disk('public')->put('category/'.$imagename,$category);
// check category slider dir is exists
if (!Storage::disk('public')->exists('category/slider')) {
Storage::disk('public')->makeDirectory('category/slider');
}
// resize image for category slider and upload
$slider = Image::make($image)->resize(500,333)->stream();
Storage::disk('public')->put('category/slider/'.$imagename,$slider);
} else {
$imagename = "default.png";
}
try with this code
<img src="images/icons8-team-355979.jpg" alt="Profile Image">
Failed to load resource: the server responded with a status of 404 (Not Found)
this is the error
Try this
<img src="{{url('category/slider')}}/{{ $category->image }}" alt="{{$category->name}}">
The url function will go to '/public' folder. So, you may need to edit your '/config/filesystem.php' so that the uploaded photo is saved inside the '/public' directory.
For more information on this please check this document.
When you want to serve files from the public disk directly, you need to create a symlink to these files. This is described in the documentation here: https://laravel.com/docs/5.7/filesystem#the-public-disk.
When you have done this, you can link to the assets using the asset() function.
echo asset('category/slider/icons8-team-355979.jpg');

use file_exists() to check wordpress uploads folder

I have created a directory in Wordpress uploads folder for end user to bulk upload photos via ftp. Images are numbered 1.jpg, 2.jpg... etc. I've generated the image urls successfully, but now I want to test for empty urls - i.e. if "8.jpg" doesn't exist, show a placeholder image from the theme's images folder instead.
I'm trying to use file_exists(), but this returns false every time and always displays the placeholder image. Any suggestions would be appreciated.
<?php while ( have_posts() ) : the_post();
// create url to image in wordpress 'uploads/catalogue_images/$sale' folder
$upload_dir = wp_upload_dir();
$sub_dir = $wp_query->queried_object;
$image = get_field('file_number');
$image_url = $upload_dir['baseurl'] . "/catalogue_images/" . $sub_dir->name . "/" . $image . ".JPG"; ?>
<?php if(file_exists($image_url)){
echo '<img src="' . $image_url . '" alt="" />';
} else {
//placeholder
echo '<img src="' . get_bloginfo("template_url") . '/images/photo_unavailable.jpg" alt="" />';
} ?>
<?php endwhile; ?>
The PHP file_exists function mainly expects an internal server path to the file to be tested. This is made obvious with the example.
Fortunately, we see that wp_upload_dir() gives us several useful values:
'path' - base directory and sub directory or full path to upload directory.
'url' - base url and sub directory or absolute URL to upload directory.
'subdir' - sub directory if uploads use year/month folders option is on.
'basedir' - path without subdir.
'baseurl' - URL path without subdir.
'error' - set to false.
I've bolded what we want to use. Using these two values, you have to generate two variables, one for the external URL and one for the internal file path:
$image_relative_path = "/catalogue_images/" . $sub_dir->name . "/" . $image . ".JPG";
$image_path = $upload_dir['basedir'] . $image_relative_path;
$image_url = $upload_dir['baseurl'] . $image_relative_path;
Then use file_exists($image_path) instead of file_exists($image_url).
Note
As with the PHP notes on PHP >= 5.0.0, you can indeed use file_exists with some URLs, however the http:// protocol is not supported for the stat() function (which is what file_exists uses.)
You have to use an internal path for checking if a file exists.
So use $upload_dir['path'] instead $upload_dir['baseurl']
[path] - base directory and sub directory or full path to upload
directory.
http://codex.wordpress.org/Function_Reference/wp_upload_dir

symlink directory

Can I get an eyeball on my symlink?
I'm trying to download a file from one directory, while the file actually exists in another.
I've got the actual file, and the symlink in seperate subdirectories, but both reside in the public html(both are web accessible).
I've verified the file and file location on my (shared Linux) server by going to the file directly.
The link is being created (I've used readlink, is_link, and linkinfo), and I can see it when I FTP in.
I believe I am probably just having a misunderstanding of the directory structure.
I put the file here: ./testdownload/
I put the symlink here: ./testDelivery/
<?php
$fileName = "testfiledownload.zip";//Name of File
$fileRepository = "./testdownload/";//Where the actual file lives
$downloadDirectory = "./testDelivery/";//Where the symlink lives
unlink($downloadDirectory . $fileName); // Deletes any previously exsisting symlink (required)
symlink($fileRepository . $fileName, $downloadDirectory . $fileName);
$checkLink = ($downloadDirectory . $fileName);
if (is_link($checkLink))
{
echo ("<br>Symlink reads: " .readlink($checkLink) . "<br>");
echo ("<br>LinkeInfo reads: " . linkinfo($checkLink));
}
?>
<p><a href="<?php echo ("/testDelivery/" . $fileName); ?>"</a>SymLink</p>
<p><a href="<?php echo ("/testdownload/" . $fileName); ?>"</a>regular link</p>
Everything looks right to me....but the link won't work.
Help?
Ultimately, I will put the source data outside the public area...this is just for testing.
(I'm trying to find a better solution for download than chunking out fread which fails for poor connections. (200-400MB files))
My problem (appears) to be not providing the absolute path for the symlink.
I've added the absolute path below to the same code above, to give a working copy:
<?php
$absolutepath = ( $_SERVER['DOCUMENT_ROOT']);
$fileName = "testfiledownload.zip";//Name of File
$fileRepository = "/testdownload/";//Where the actual file lives
$downloadDirectory = "/testDelivery/";//Where the symlink lives
unlink($absolutepath .$downloadDirectory . $fileName); // Deletes any previously exsisting symlink (required)
symlink($absolutepath . $fileRepository . $fileName, $absolutepath. $downloadDirectory . $fileName);
$checkLink = ($absolutepath . $downloadDirectory . $fileName);
if (is_link($checkLink))
{
echo ("<br>Symlink reads: " .readlink($checkLink) . "<br>");
echo ("<br>LinkeInfo reads: " . linkinfo($checkLink));
}
?>
<p><a href="<?php echo ("/testDelivery/" . $fileName); ?>"</a>SymLink</p>
<p><a href="<?php echo ("/testdownload/" . $fileName); ?>"</a>regular link</p>
This original post, is a duplicate (though I didn't see it until now)
Create a valid symlink for PHP file
(Most of the answers given for that question were wrong however--but the original poster figured it out, and it worked for me too)

Trouble getting PHP file_exists to work

I'm trying to get a thumbnail to link to a PDF of the same name if the PDF exists, but to not link to anything if the PDF doesn't exist. Here's the code I have:
<?php
if ( function_exists('has_post_thumbnail') && has_post_thumbnail() ) {
$full_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full') ;
$pdf = substr_replace($full_image_url , 'pdf', strrpos($full_image_url[0] , '.') +1);
$filename = $pdf[0];
if (file_exists($filename)) {
echo '<a href="' . $pdf[0] . '" title="' . the_title_attribute('echo=0') . '" . target="_blank" >';
the_post_thumbnail('Full Size');
echo '</a>';
}
else {
echo "The file $filename exists";
}
}
?>
Currently, the else statement is just to prove whether or not it's finding the file. Which it seems to, as it displays The file http://localhost/AWAD/wp-content/uploads/2012/03/+D.pdf exists. And if I get rid of the conditional, the post thumbnail displays with a link to the PDF. I just can't get the conditional to work.
Can anyone spot why it's not working?
You should pass a path on your FS to file_exists, you are passing an URL now
I'm pretty sure file_exists wants a full file path, not a URL. So, you'll probably want to use the WordPress wp_uploads_dir function to get the base path to your uploads directory and then append the rest of the path to the end of that and then pass that string to file_exists. Hopefully that makes sense.

Categories