How to match image name with database record? - php

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

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

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

Deleting contents of all folders

I have a table with the names of all the folders I wish to delete the contents off. Now I have a script which will delete the entire contents of a folder that I set. Now I though I could put that code in a while loop and it would delete the contents of all the folders. However, I get an error. Here is the code, error is at the bottom, what's going wrong and how do I fix this?
$query = "SELECT * FROM gemeentes";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$gemeente1 = str_replace(" ","",$row['gemeente']);
$gemeente2 = strtolower($gemeente1);
$gemeente3 = str_replace("(","-",$gemeente2);
$gemeente4 = str_replace(")","",$gemeente3);
$gemeente5 = str_replace(",","",$gemeente4);
if(isset($_POST['GO'])) {
$directory = "../subdomains/".$gemeente5."/httpdocs/";
echo $directory;
define('PATH', $directory);
function destroy($dir) {
$mydir = opendir($dir);
while(false !== ($file = readdir($mydir))) {
if($file != "." && $file != "..") {
chmod($dir.$file, 0777);
if(is_dir($dir.$file)) {
chdir('.');
destroy($dir.$file.'/');
rmdir($dir.$file) or DIE("couldn't delete $dir$file<br />");
}
else
unlink($dir.$file) or DIE("couldn't delete $dir$file<br />");
}
}
closedir($mydir);
}
destroy(PATH);
echo 'all done.';
}
}
The first delete comes back fine, the second won't do the trick anymore:
../subdomains/aaenhunze/httpdocs/all done.../subdomains/aalburg/httpdocs/
Fatal error: Cannot redeclare destroy() (previously declared in /vhosts/url.nl/httpdocs/deletecontent.php:50) in /vhosts/url.nl/httpdocs/deletecontent.php on line 50
Why are you calling your function as destroy(PATH); with a "define"d constant instead of just the actual underlying variable as: destroy($directory);? Once you take the function out of the loop as Bulk suggested, this should work I'd think...
You are defining the destroy function inside the outermost while loop, so the second time it comes to run the loop the function is already defined. Move the function definition to outside of the while loop to fix this.
Thank you all for the help. I took a look at all your answers and what OzgurH suggested did the trick. The working code:
$query = "SELECT * FROM gemeentes";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$gemeente1 = str_replace(" ","",$row['gemeente']);
$gemeente2 = strtolower($gemeente1);
$gemeente3 = str_replace("(","-",$gemeente2);
$gemeente4 = str_replace(")","",$gemeente3);
$gemeente5 = str_replace(",","",$gemeente4);
if(isset($_POST['GO'])) {
$directory = "../subdomains/".$gemeente5."/httpdocs/";
echo $directory;
destroy($directory);
echo 'all done.';
}
}
function destroy($dir) {
$mydir = opendir($dir);
while(false !== ($file = readdir($mydir))) {
if($file != "." && $file != "..") {
chmod($dir.$file, 0777);
if(is_dir($dir.$file)) {
chdir('.');
destroy($dir.$file.'/');
rmdir($dir.$file) or DIE("couldn't delete $dir$file<br />");
}
else
unlink($dir.$file) or DIE("couldn't delete $dir$file<br />");
}
}
closedir($mydir);
}

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

Categories