Check if Image file name exists php loop - php

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";
}
?>

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>";
}

How to match image name with database record?

I've got the following problem:
I have some images in a folder and a sql database record.I have to fetch all images from folder and we have to match that image name with having the field in the database. If these are same then we have to rename that image with the another name. How would I do that?
<?php
$query = "Select ITCFields.ImageID,UDFields.Zoho_ID from ITCFields,UDFields where
ITCFields.ImageID='1234899'";
$resa = odbc_exec($conn,$query);
echo "<table border='1'>
<tr>
<th>ZohoID</th>
<th>Image</th>
<th>Full_Name</th>
</tr>";
while( $row = odbc_fetch_array($resa) ) {
echo "<tr>";
$zoho_id=$row['Zoho_ID'];
$image_id=$row['ImageID'];
echo "<td>" .$zoho_id."</td>";
echo "<td>" .$image_id."</td>";
$full_name=$zoho_id.'_'.$image_id.'.jpg';
echo "<td>" .$full_name."</td>";
echo "</tr>";
}
odbc_close($conn);
?>
<?php
define("BASE_IMAGE_PATH","D:\\");
define("IMAGE_FOLDER_NAME","2014finalfour\\");
define("IMAGE_FOLDER_NAME_MODIFIED","modified\\");
define("IMAGE_File_Path",BASE_IMAGE_PATH.IMAGE_FOLDER_NAME);
define("IMAGE_File_Path_Modified",BASE_IMAGE_PATH.IMAGE_FOLDER_NAME.IMAGE_FOLDER_NAME_MODIFIED);
$srcdir=constant("IMAGE_File_Path");
$destdir=constant("IMAGE_File_Path_Modified");
if (!file_exists(IMAGE_File_Path_Modified)) {
mkdir(IMAGE_File_Path_Modified, 0777, true);
}
$srcdire=opendir($srcdir);
while($readFile = readdir($srcdire))
{
if($readFile != '.' && $readFile != '..')
{
if (!file_exists($readFile))
{
if(copy($srcdir . $readFile, $destdir . $readFile ))
{
echo "Copy file";
}
else
{
echo "Canot Copy file";
}
}
}
}
closedir($srcdir);
?>
<?php
$directory=constant("IMAGE_File_Path_Modified");
if ($dir = opendir($directory) )
{
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
}
}
closedir($dir);
}
foreach($images as $image) {
echo $image."</br>";
}
?>
Please Help me to sought out it.
Is image name very important in your code logic?
Usually the problem of having duplicate images is solved by hashing the image name to a unique name (for example with the unix date time value) when it is uploaded and using that name for all further logic. So the unique name for the name becomes the hashed name and you can still use the original name to display if required as another field in the table.
So the problem essentially becomes that of giving each image a unique name then to track if it is unique.
Below is the code of uploading the image.
function uploadImage($image,$path,$thumbpath)
{
if($image!=''){
$explode=explode('.',$_FILES[$image]['name']);
$file=time().'.'.$explode[1];
$file_tempname=$_FILES[$image]['tmp_name'];
move_uploaded_file($file_tempname,$path.$file);
createThumb($path.$file,$thumbpath.$file, 80, 80);
}
return $file;
}
first of all fetch all the folder images name than match with your db images name.
$dir = "/images/";
$img_name = scandir($dir);
while( $row = odbc_fetch_array($resa) ) { echo "";
$zoho_id=$row['Zoho_ID'];
$image_id=$row['ImageID'];
echo "" .$zoho_id."";
echo "" .$image_id."";
$full_name=$zoho_id.'_'.$image_id.'.jpg';
if(in_array($full_name,$img_name)){
//do your chanes
}
echo "" .$full_name."";
}

Check if an image exists

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;
}

PHP Directory Tree - Deleting Folders

I have found a script that lists all directories and files in them, and allows for the deletion of files.
I have two problems:
1) How do I add the function to delete a folder (With all the contents in it)
2) How do I make the script not to allow a user to browse up a directory? (For e.g. a user's folder is ./files/$userid/. I want it so that a user won't be able to go to or make any changes to ./files/ or a folder other then ./files/$userid/
$script = basename(__FILE__); // the name of this script
$path = !empty($_REQUEST['path']) ? $_REQUEST['path'] : dirname('./files/' . (string)$userid . '/'); // the path the script should access
$unlink = $_REQUEST['unlink'];
if(!empty($unlink)){
$unlink = realpath("$path/$unlink");
if(is_writable($unlink) && !unlink($unlink)){
echo "<div class=\"error\">Unable to delete file: $unlink</div>";
}
}
echo "<p>Browsing Location: {$path}</p>";
$directories = array();
$files = array();
// Check we are focused on a dir
if (is_dir($path)){
chdir($path); // Focus on the dir
if ($handle = opendir('.')){
while (($item = readdir($handle)) !== false) {
// Loop through current directory and divide files and directorys
if(is_dir($item)){
array_push($directories, realpath($item));
}
else{
array_push($files, ($item));
}
}
closedir($handle); // Close the directory handle
}
else {
echo "<p class=\"error\">Directory handle could not be obtained.</p>";
}
}
else{
echo "<p class=\"error\">Path is not a directory</p>";
}
// List the directories as browsable navigation
echo "<h2>Navigation</h2>";
echo "<ul>";
foreach($directories as $directory){
$delete = is_writable($file) ? "<a class=\"unlink\" href=\"{$script}?path={$path}&unlink={$directory}\">delete</a>" : '';
echo ($directory != $path) ? "<li>{$directory}</li>" : "";
}
echo "</ul>";
echo "<h2>Files</h2>";
echo "<ul>";
foreach($files as $file){
// Comment the next line out if you wish see hidden files while browsing
if(preg_match("/^\./", $file) || $file == $script){continue;} // This line will hide all invisible files.
$delete = is_writable($file) ? "<a class=\"unlink\" href=\"{$script}?path={$path}&unlink={$file}\">delete</a>" : '';
echo '<li>' . $file . " $delete</li>";
}
echo "</ul>";
1) Try use this function to delete folder recursively (see manual, User contributed notes section http://php.net/manual/en/function.rmdir.php):
function delTree($dir) {
$files = array_diff(scandir($dir), array('.','..'));
foreach ($files as $file) {
(is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}
2) Better develop some filemanager to allow users browse certain folders. Or see some ready solutions: http://www.jquery4u.com/plugins/10-jquery-file-manager-plugins/

How to retrieve files on a directory in list using PHP

How may i able to retrieve different file extensions in a certain directory. Let say i have a folder named "downloads/", where inside that folder are different types of files like PDFs, JPEGs, DOC files etc. So in my PHP code i wanted those files be retrieved and listed with there file names and file extensions. Example: Inside "downloads/" folder are different files
downloads/
- My Poem.doc
- My Photographs.jpg
- My Research.pdf
So i wanted to view those files where i can get there file names, file extensions, and file directories. So in view will be something like this
Title: My Poem
Type: Document
Link: [url here]
Title: My Photographs
Type: Image
Link: [url here]
Title: My Research
Type: PDF
Link: [url here]
Anyone knows how to do it in php? Thanks a lot!
It's pretty simple. To be honest i don't know why didn't you searched on a php.net. They got whole lots of examples for this. Check it in here: click
Example:
<?php
function process_dir($dir,$recursive = FALSE) {
if (is_dir($dir)) {
for ($list = array(),$handle = opendir($dir); (FALSE !== ($file = readdir($handle)));) {
if (($file != '.' && $file != '..') && (file_exists($path = $dir.'/'.$file))) {
if (is_dir($path) && ($recursive)) {
$list = array_merge($list, process_dir($path, TRUE));
} else {
$entry = array('filename' => $file, 'dirpath' => $dir);
//---------------------------------------------------------//
// - SECTION 1 - //
// Actions to be performed on ALL ITEMS //
//----------------- Begin Editable ------------------//
$entry['modtime'] = filemtime($path);
//----------------- End Editable ------------------//
do if (!is_dir($path)) {
//---------------------------------------------------------//
// - SECTION 2 - //
// Actions to be performed on FILES ONLY //
//----------------- Begin Editable ------------------//
$entry['size'] = filesize($path);
if (strstr(pathinfo($path,PATHINFO_BASENAME),'log')) {
if (!$entry['handle'] = fopen($path,r)) $entry['handle'] = "FAIL";
}
//----------------- End Editable ------------------//
break;
} else {
//---------------------------------------------------------//
// - SECTION 3 - //
// Actions to be performed on DIRECTORIES ONLY //
//----------------- Begin Editable ------------------//
//----------------- End Editable ------------------//
break;
} while (FALSE);
$list[] = $entry;
}
}
}
closedir($handle);
return $list;
} else return FALSE;
}
$result = process_dir('C:/webserver/Apache2/httpdocs/processdir',TRUE);
// Output each opened file and then close
foreach ($result as $file) {
if (is_resource($file['handle'])) {
echo "\n\nFILE (" . $file['dirpath'].'/'.$file['filename'] . "):\n\n" . fread($file['handle'], filesize($file['dirpath'].'/'.$file['filename']));
fclose($file['handle']);
}
}
?>
You could use glob & pathinfo:
<?php
foreach (glob(__DIR__.'/*') as $filename) {
print_r(pathinfo($filename));
}
?>
You will try this code :
$Name = array();
$ext = array();
$downloadlink = array();
$dir = 'downloads'
while ($file= readdir($dir))
{
if ($file!= "." && $file!= "..")
{
$temp = explode(".",$file);
if (count($temp) > 1)
{
$Name[count($Name)] = $temp[0];
swich($ext)
{
case "doc" :
{
$ext[count($ext)] = "Document";
break;
}
[...]
default :
{
$ext[count($ext)] = "Error";
break;
}
}
$downloadlink[count($downloadlink)] = "http://yourdomain.com/".$dir."/".$file;
}
}
}
closedir($dir);
for($aux = 0; $aux < count($Name); $aux++)
{
echo "Name = " . $Name[$aux]."<br />
Type = " . $ext[$aux]."<br/>
Link = " . $downloadlink[$aux]."<br/>
";
}

Categories