PHP Deleting images - php

I have an admin system which adds profile pages dynamically - and part of that adds images to a directory. When I add the images they all have the name format like 12_1.jpg, 12_2.jpg, 32_1.jpg, 32_9.jpg where the number before the underscore is the id $cid and the number after the underscore is the image number.
I'm trying to find a way to list the images on the edit-images.php page with an option to delete them (maybe a link next to the image name, or another way that is better).
Here is the code to find the images I need to have the option of deleting:
if ($handle = opendir('../images/company')) {
while (false !== ($entry = readdir($handle))) {
if (substr(basename($entry), 0, 2) == $cid) {
echo $entry . "<br>";
}
}
closedir($handle);
}
How would I go about deleting specified images from here? Any help would be appreciated.

In php you use the unlink function to delete files. Just echo a link to a page that calls a function do to that and pass the image name. Only be sure to check the user input before actually perform deletion.

Why are you scanning the directory for the file? You can check if the file exists and delete it instead. For example:
$files = glob("../images/company/$cid_*.jpg");
foreach($files as $file) {
if(file_exists($file)) unlink($file);
}
This will unlink all files in ../images/company with the name starting with 123_ for example and ending in .jpg (you can provide more extensions by using GLOB_BRACE parameter)

Related

Displaying a recently uploaded file with an image and a link to the file

I currently have 5 images on my site and each of these is linked to a file, I have recently added an option to upload a file to the directory "uploads", but I would like for these to be echoed on the site with an image (I have a folder of images named numerically).
Is it possible to create a loop to check if file has been added to a specific directory, e.g. "folder/file.doc"?
I don't have any code for this and I don't expect anyone to code it for me, but if you could please point me in the right direction as to how to make this.
Maybe this could help? You just need to read the folder and iterate over all the content while echoing all files with name, link and tag:
if ($handle = opendir('/path/to/your/files')) {
while (false !== ($entry = readdir($handle))) {
echo "<img src='$entry'/><br/>";
}
closedir($handle);
}
And this is the corresponding link:
http://php.net/manual/de/function.readdir.php#example-2478

php echo file url using title tag

I have a php script that will echo a list of files from a folder and display them randomly on my page.
At the moment it displays the url of the file for example: what-can-cause-tooth-decay.php
i would like it to display the page title <title>What can cause tooth decay</title>.
Current code:
<?php
if ($handle = opendir('health')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach($fileTab as $file) {
$thelist .= '<p>'.$file.'</p>';
}
}
?>
<?=$thelist?>
Many thanks
I see a couple of possible approaches:
You could parse the files. Should be possible by running a regex over the results of file_get_contents.
Place some text file somewhere, which maps file names to titles. Load it into memory and use it to populate an array which you can use to map the file names. Let it have file_name.html Title on each line, or something like that.
Use a naming convention, so the titles can be inferred from the filenames. Something like "capizalize first letter, turn '_' into space"
Downsides of the 2nd and 3rd approach: You'd have to keep it consistent with the actual title-elements in the files. Problem with the first approach: You have to read every file into memory - could be a performance problem with many/big files. To solve this, I could imagine writing a script which looks through all the files and generates the lookup text file. Whenever you change a title in a file, or add/remove files, you'd just need to rerun that script.

What is the best method to read a folder sub directory and files in those sub directory?

I have a image folder which contains sub directory for each album of images like
Images
Images/Album1
Images/Album2
in PHP file
I create a link for each album using a thumbnail for the album using GLOB to read all folders under Images
$dir=glob('images/*');
$dir_listing=array();
foreach($dir as $list)
{
if(is_dir($list))
$dir_listing[]= (basename($list));
}
$thumbs=glob('images/thumbnails/*');
$count=0;
foreach($thumbs as $th )
{
echo" $dir_listing <br/>";
echo"<a href='$dir_listing[$count]' ><img src='$th' /> </a>";
$count++;
}
I use Glob on each page load to get list of directories and images.
I want to know if there is a better way of doing this.
I also want to get list of all files and folder based on there Last Modified time in descending Order {Latest files and Folders first}.
Is using Glob correct or should we save the sub-directories and files in text file and read from it?
I can't tell you for sure if there is a better way of doing this, but your code should definitely work.
Using glob() is the right approach only if you have a relatively low number of files in the directory (<10,000), because if yoy have a lot of files then you could get a "Allowed memory size of XYZ bytes exhausted ..." error. In this case, it is best to use opendir();
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
// do something with the file
// note that '.' and '..' is returned even
}
closedir($handle);
Finally, use the flag GLOB_NOSORT on glob() so the end result is just like its listed on the directory in case that may be used to give you results based on last modified date.
Hope this helps.

How to use database to generate multiple folder content page?

Scenario :I am trying to build a Mobile Entertainment Portal. It will enable users to download Music & Movies to their Cell Phones...
Problem Exp : Suppose I upload 100 folders of Songs, each folder is for one Album. I want a way to generate a page with all the folders name (Album Name) in it. If user click on the page, they should be taken to a page where they get list of all songs in the album. Clicking on any song name will let them download it. Can it be done anyway or will I have to manually design each of the 3 pages for each album. If I do that, its time consuming and also will be difficult to change anything like footer, header...
First of all, this is a weighted question. But I will try to answer some of your questions to get you started.
You can scan for directories using scandir() in PHP.
$path = '/path/to/music';
$dir = scandir($path);
if (is_array($dir)) {
foreach ($dir as $directory) {
if (is_dir("{$path}/{$directory}")) {
// validate that it's among the directories you want
}
}
}
So, now that you know how to do that, perhaps instead of trying to create a separate page for each album folder you could use one script and based on the GET vars, display the appropriate content. e.g.
domain.com/index.php?album=Album+Name
Now let's see how that might work with the above example:
// assume your album folder names use underscores
$album = (isset($_GET['album']))
? str_replace('+', '_', $_GET['album'])
: null;
$path = '/path/to/music';
$dir = scandir($path);
if (is_array($dir)) {
foreach ($dir as $directory) {
if (is_dir("{$path}/{$directory}") && $album == $directory) {
// now, scan for files
}
}
}
Then to get the files, when you're looping through the directories, instead of checking if it is a directory, check that it's not a directory and that will give you your files. (e.g. if (!is_dir(...)

Web, SQL: display random images despite file name, load images from folder

I want a web page to display several random images on load. I've thought of several solutions but I would really like to be able to dump images into a folder without renaming them, and the web page will choose from those images in the folder and display them
I can imagine a PHP solution that will display random images from a folder, but it will need to look for certain names.
So my next step was to have an SQL database where every image got a key, and 10 keys would be chosen random by a query - the images associated with them would then be passed into an array that the document will load the elements of.
But now I guess I need to know how to automatically populate an SQL database by having it read a folder?
Insight appreciated, if I don't have to reinvent the wheel the better
Glob works like on the filesystem, e.g. supports wildcards
$files = glob('/path/to/files/*.jpg');
$yourRandomFile = array_rand($files);
This will return a random JPG file, based on it's extension.
This should do it :
function your_dir ($directory)
{
$results = array();
$handler = opendir($directory);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$results[] = $file;
//or sql query for each file
$sql = mysql_query("SELECT * FROM your_table WHERE your_file = '".$file."'");
if(mysql_num_rows !== 0){
//your query...
}
//
}
}
closedir($handler);
return $results;
}
$directory = '/path/to/your/directory';
your_dir($directory);
Would probably be better to select existing files from db first put them into an array and exclude them rather than checking for each one.
You can do as below.
1. read complete dir from where you want the page to load the image
2. store the image names in array
3. now generate a number using random function from 1 to size of the array
4. consider the generated number as key for the array and use that image name to put the image.

Categories