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(...)
Related
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)
I have an HTML form and one of the inputs creates a folder. The folder name is chosen by the website visitor. Every visitor creates his own folder on my website so they are randomly generated. They are created using PHP Code.
Now I would like to write a PHP code to copy a file to all of the child directories regardless the quantity of directories being generated.
I do not wish to stay writing a PHP line for every directory that is created - i.e. inserting the filename name manually (e.g. folder01, xyzfolder, folderabc, etc...) but rather automatically.
I Googled but I was unsuccessful. Is this possible? If yes, how can I go about it?
Kindly ignore security, etc... I am testing it internally prior to rolling out on a larger scale.
Thank you
It is sad I cannot comment so go on...
//get the new folder name
$newfolder = $_POST['newfoldername'];
//create it if not exist
if(!is_dir("./$newfolder")) {
mkdir("./$newfolder", 0777, true);
}
//list all folder
$dirname = './';
$dir = opendir($dirname);
while($file = readdir($dir)) {
if(($file != '.' OR $file != '..') AND is_dir($dirname.$file))
{
//generate a randomname
$str = 'yourmotherisveryniceABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$randomname = str_shuffle($str);
$actualdir = $dirname.$file;
//copy of the file
copy($uploadedfile['tmp_name'], $actualdir.$randomname);
}
}
closedir($dir);
I just want to say, you seem to be lazy by looking for what you want to do. because when I read "I would like to write a PHP code to copy" the answer is in your sentence: copy PHP and list of folders regarless how many? Then just simply list it !
Maybe you need to learn how to use google... If you search "I would like to write a PHP code to copy a file to all of the child directories regardless the quantity of directories being generated" Sure you will never find.
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.
I made one site... where i am storing user uploaded files in separate directories like
user_id = 1
so
img/upload_docs/1/1324026061_1.txt
img/upload_docs/1/1324026056_1.txt
Same way if
user_id = 2
so
img/upload_docs/2/1324026061_2.txt
img/upload_docs/2/1324026056_2.txt
...
n
So now if in future if I will get 100000 users then in my upload_docs folder I will have 100000 folders.
And there is no restriction on user upload so it can be 1000 files for 1 user or 10 files any number of files...
so is this proper way?
Or if not then can anyone suggest me how to store this files in this kind of structure???
What I would do is name the images UUIDs and create subfolders based on the names of the files. You can do this pretty easily with chunk_split. For example, if you create a folder every 4 characters you would end up with a structure like this:
img/upload_docs/1/1324/0260/61_1.txt
img/upload_docs/1/1324/0260/56_1.txt
By storing the image name 1324026056_1.txt you could then very easily determine where it belongs or where to fetch it using chunk_split.
This is a similar method to how git stores objects.
As code, it could look something like this.
// pass filename ('123456789.txt' from db)
function get_path_from_filename($filename) {
$path = 'img/upload_docs';
list($filename, $ext) = explode('.', $filename); //remove extension
$folders = chunk_split($filename, 4, '/'); // becomes 1234/5678/9
// now we store it here
$newpath = $path.'/'.$folders.'/'.$ext;
return $newpath;
}
Now when you search for the file to deliver it to the user, use a function using these steps to recreate where the file is (based on the filename which is still stored as '123456789.txt' in the DB).
Now to deliver or store the file, use get_path_from_filename.
img/upload_docs/1/0/10000/1324026056_2.txt
img/upload_docs/9/7/97555/1324026056_2.txt
img/upload_docs/2/3/23/1324026056_2.txt
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.