Check if an image exists - php

I have foreach loop that looks like this:
foreach($wdata->query->pages->$wpageid->images as $iimages)
{
$name = $iimages->title;
$filename = str_replace(" ", "_",$name);
$filename = str_replace("File:","",$filename);
$digest = md5($filename);
$folder = $digest[0].'/'.$digest[0].$digest[1].'/'. $filename;
$url = 'http://upload.wikimedia.org/wikipedia/commons/'.$folder;
echo "<img style='height:100px;' src='$url'>";
}
It displayes images from a returned json array ($wdata)
However, some images have been moved, or don't exist anymore, and I get cracked images, does anyone know how to check if an image is real, exists and can be viewed before it is echoed

Use the file_get_cotents() function to check if it's there
if (file_get_contents("http://....") !== false) { //display image }

It is a remote file and file_exists() does not work for this circumstance. So I suggest you to use getimagesize() function which returns an array if the image exists.
<?php
$imageSize=getimagesize($url);
if(!is_array($imageSize))
{
echo "<img style='height:100px;' src='$url'>";
}
else
{
echo "no image";
}
?>
Another solution:
if (true === file_get_contents($url,0,null,0,1))
{
echo "<img style='height:100px;' src='$url'>";
}
This is faster because it tries to read only one byte of the file if exists.

Use a function as below and pass your url for test
if (image_exist($url)) {
echo "<img ...";
}
function image_exist($url) {
$file_headers = #get_headers($url);
if($file_headers[0] == 'HTTP/1.1 200 Found') {
return true;
}
return false;
}

Related

PHP Is there a way to display my list from the foreach separately?

I want to display the links separately. One list would include all the .html links and the other all the .jpg links.
right now it displays this and I understand why it is doing it, but when i do another foreach outside or even right before the echo, its like nothing is passing into it.
.jpg
.html
.jpg
.html
I need it to display like this
HTML-Backup HTML
.jpg .html
.jpg .html
php Code
$array = array();
$html= "";
$htmlBackup= "";
if(file_exists("uploads/" . $_POST["prefix"] .'/'))
{
$dir = 'uploads/' . $_POST["prefix"] . '/';
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir));
$prefixDir = scandir($dir);
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.jpg") !== false)
{
echo''.$lastDir.' </br>';
//variable to store list of dir
$html=$lastDir;
} else if(strpos($lastDir, "HTML5.html") !== false )
{
echo''.$lastDir.' </br>';
//variable to store the list of dir
$htmlBackup=$lastDir;
}
}
}
}
}
Don't put <br> at the end of each echo. Do it after the inner loop so all links from the same directory will be on the same line.
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.jpg") !== false)
{
echo''.$lastDir.'';
//variable to store list of dir
$html=$lastDir;
} else if(strpos($lastDir, "HTML5.html") !== false )
{
echo''.$lastDir.'';
//variable to store the list of dir
$htmlBackup=$lastDir;
}
}
echo "<br>";
}
}
I found a solution by including arrays.
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.html") !== false || strpos($lastDir, "H5.html") !== false)
{
//variable to store the list of dir
array_push($html_array, $lastDir);
array_push($html_dir,$secondDir.'/'.$lastDir);
}
else if(strpos($lastDir, "HTML5.jpg") !== false || strpos($lastDir, "H5.jpg")!== false )
{
//variable to store list of dir
array_push($html_backup_array, $lastDir);
array_push($html_backup_dir,$secondDir.'/'.$lastDir);
}
}
}
}
and then display them under in another foreach as I want
if(!empty($html_array))
{
echo "<p>";
echo ("<p><span class='heading'>HTML5 Units</span></p>");
foreach (array_combine($html_dir, $html_array) as $html_dirr => $html_arrays)
{
echo (''.$html_arrays.'');
echo "<br>";
}
echo "</p>";
}

Check if Image file name exists php loop

I have multiple images on my root folder /images/filename.here. Image filenames are like this (email): me#yahoo.jpg, me#yahoo_1.jpg, me#yahoo_2.jpg, you#gmail.jpg.
My code on showing only one image of user if exist me#yahoo.jpg and you#gmail.jpg:
<?
$email= $data['payment']['email'];
$receipts = "images/".$email;
if (file_exists($receipts)) { ?>
<img src="<?=($receipts)?>" width:"100px" height="50px"/>
<? } else {
echo "no receipt";
} ?>
this only show the "without _x" filename. How can I show other images of a user(e.g me#yahoo) using loop _1 ,_2, _3... It should display all images that belong to a user.
I would create a helper function get_image to return the path of the image by email and index, and use a while loop to build the list of images:
<?php
function get_image($email, $i) {
$path = "images/receipts/".$email;
if ($i > 0) $path .= '_' . $i;
$path .= '.jpg';
if (file_exists($path)) return $path;
return null;
}
$i = 0;
while ($path = get_image($email, $i)) {
echo "<img src=\"$path\" width:\"100px\" height=\"50px\"/>";
$i++;
}
if ($i == 0) {
echo "no receipt";
}
?>

Passing $_FILES as variable, returns both result and error.

Trying to execute file upload through external function. It gives "Missing argument..." error but also returns the result correctly. What might be wrong?
This is form page:
<?php include '--formprocess.php'; ?>
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$upload = $_FILES['upload'];
if(formprocess($upload)) {
echo formprocess();
} else {
echo 'ERROR!';
}
}
?>
and process file:
<?php
function formprocess($upload) {
$name = $_FILES['upload']['tmp_name'];
return $name;
}
echo formprocess();
^---your missing argument
formprocess takes one argument, the first time you call it you passed an argument, the second time you did not.
$value = formprocess($upload);
if($value) {
echo $value;
}

PHP glob() regex pattern

I have a folder that contains logos for sponsors. In my website, a user can belong to a sponsor and the sponsor_id is set in session when the user logs in.
Here is my code:
function sponsor_logos($sponsor_id) {
$logos = glob("resources/content/sites/{$sponsor_id}*");
foreach($logos as $logo) {
if(file_exists("{$logo}"))
echo "<img src='/{$logo}' />";
}
}
The above works, but a sponsor can have multiple logos. So the multiple logos are saved like so: sponsor_id.jpg, sponsor_id_2.jpg, sponsor_id_3.jpg
I am not the strongest at regex, so any help is greatly appreciated! thanks!
You better open directory and check all files in it (if there are not so much files). You could do it like that:
function sponsor_logos($sponsor_id) {
if ($dh = opendir('resources/content/sites/')) {
while (($file = readdir($dh)) !== false) {
if(strpos($file, $sponsor_id . '.') === 0) {
$sponsor_files[] = $file;
}
else if(strpos($file, $sponsor_id . '_') === 0) {
$sponsor_files[] = $file;
}
}
closedir($dh);
}
foreach($sponsor_files as $logo) {
echo "<img src='resources/content/sites/" . $logo . "' />";
}
}
But best solution is to have normal naming scheme.
use this regex sponsor_id(_\d+)?\.jpg

move_uploaded_file file not work when it will call two time

i have a function to upload file in php Like:
function upload_file($folder,$name)
{
$dest = "../product/". $folder."/". $name;
$src = $_FILES['image']['tmp_name'];
if (move_uploaded_file($src, $dest)) {
} else {
echo "<script> alert('" . $src . "');
window.history.go(-1); </script>\n";
exit();
}
}
whene i call function only one time like upload_file('small','abc.jpg') it works fine but
i have call two time like:
upload_file('small','abc.jpg')
upload_file('big','abc.jpg')
it not work on second folder 'big'
any solution for that ?
move_uploaded_file has moved to the first destination.
So, the solution is get the first destination path, and copy with it for the other.
It will be a lot of solutions. One of them, change the param into array and iterate it.
<?php
$filesDes = array(
array('folder'=>'small','name'=>'abc.jpg'),
array('folder'=>'big','name'=>'abc.jpg'));
function upload_file($arrayfile)
{
$firstfile = null;
foreach($arrayfile as $val)
{
$dest = "../product/". $val['folder']."/". $val['name'];
if(!isset($firstfile))
{
$firstfile = $dest;
$src = $_FILES['image']['tmp_name'];
if (!move_uploaded_file($src, $dest)) {
echo "<script> alert('" . $src . "');
window.history.go(-1); </script>\n";
exit();
}
}
}
else
{
if(!copy ( $firstfile , $dest ))
{
echo "<script> alert('" . $dest . "');
window.history.go(-1); </script>\n";
exit();
}
}
}
upload_file($filesDes)

Categories