im looking to make a web player from scratch so I can control my music from my phone. I've got a listing of all files within a folder done, but I need to get it to list the files within the subfolders of the main folder.
So sort of something like \Path\ - Shows all in \Path\ and \Path\subs\ shows the contents of all subfolders.
This is the code that I have written to allow me to search a folder for .mp3 files, but I cannot pin the way to search in subfolders as well.
$.ajax({
url: "music/",
success: function(data){
$(data).find("a:contains(.mp3)").each(function(){
var files = $(this).text().replace(/ /g, '');
files = $(this).text().replace(/.mp3/,'');
$('<p></p>').html(files).appendTo('#displayer');
$('#displayer > p:nth-child(odd)').css('background-color','#DDD');
});
}
});
Many thanks in advance
This is my solution in PHP
<?php
// your mp3 dir
$dir = "dir/";
$result = array();
if(is_dir($dir)){
$iterator = new RecursiveDirectoryIterator($dir);
foreach(new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file){
$ext = pathinfo($file, PATHINFO_EXTENSION);
if("mp3"==$ext){
$result[] = $file->getPathName();
}
}
// you can echo json_encode(yourMp3Path) here.
var_dump($result);
}
Related
I am trying to implement download functionality in PHP. A user can download single or multiple files. If user try to download single file, the file gets downloaded normally. If user tries to download multiple files, all the files will be converted to zip and get downloaded.
But my problem is how to pass the gruop of filenames along with their paths. For a single file I passed it using
window.location = directories_path + "?action=download&files="+download;
download can be an array where I can pass files. But I am unable to pass them. My url appeared alike
localhost/proj/Base?action=download&files=[object Object]
I even tried with AJAX passing file names in json format. But it didn't work.
My JS code for the download process
$("input:checked").each(function(){
if($(this).siblings('a').length > 0)
{
download.push({
name: $(this).siblings('a').text(),
path: $(this).siblings('a').attr('href'),
});
}
});
if( checked == 0 ) {
alert("Please select any file to download");
} else {
window.location = directories_path + "?action=download&files="+download;
}
My php code for downloading single file is
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($file));
header('Content-Disposition: attachment; filename='.$file);
header('Content-Transfer-Encoding: binary');
readfile($file);
My question is Is there any way so that I can pass an array of objects(filename and filepath) in url so that I can download the files correspondingly. Thanks
Thanks #ADyson and remaining all others for help. Finally this is how I implemented it. I am posting it so that it might be useful to someone.
I made an AJAX post request and returned the link. And finally changed the window.location to that specific link for multiple files. But for single file downloads, It may not be possible sometimes. For Eg: If you change the location to PNG image. The browser opens the PNG image instead of downloading it. So, I preferred HTML anchor download tag for single file downloads.
This is my JQuery code:
$(".uploaded_files").on('click', '#download', function(event){
download = [];
$("input:checked").each(function(){
if($(this).siblings('a').length > 0)
{
download.push({
name: $(this).siblings('a').text(),
path: $(this).siblings('a').attr('href'),
});
}
});
if( checked == 0 ) {
alert("Please select any file to download");
} else if( checked == 1) {
$("body").append($(''));
console.log(download);
document.getElementById('download_single').click();
$("a#download_single").remove();
} else {
alert("The download begins in few seconds");
$.post('Base.php', {
action: 'download',
files: download //array of objects of files
}, function(link) {
window.location = link;
});
}
});
This is my PHP code for downloading multiple files
$zip = new ZipArchive();
$zip_file = 'tmp/'.md5("download".rand(1,1000000)."zipfile").".zip";
if( $zip->open($zip_file, ZipArchive::CREATE))
{
foreach($files as $file)
{
$file['path'] = explode('uploads/', $file['path'])[1];
$file['path'] = 'uploads/'.$file['path'];
$zip->addFile($file['path'], $file['name'] );
}
$zip->close();
header('Content-disposition: attachment; filename='.$zip_file.'');
header('Content-type: application/zip');
echo "http://localhost/".$zip_file;
die();
I'm getting really confused here. So here's whats going on in my project. The user clicks download then select directory to save the file, the file will be a zip file. After that I want to extract that zip file in the same directory the users chooses. Is this even possible in one script?
Here is my php code
<?php
require_once('connect.php');
// Get real path for our folder
$rootPath = realpath($_GET['uniq']);
// Name of the zip derive from the database
$zipname = $_GET['name'] . '.zip';
// Initialize archive object
$zip = new ZipArchive();
$zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
?>
If its not possible another question. Is it possible to let user choose a zip file then after that it will be extracted at some client directory ie. C://xamp/extracthere/ using javascript.
Once the user has downloaded the file to their machine, it's beyond your control. You can't force them to unzip it, or do anything else with it for that matter.
Imagine if you could control the files on a user's local disk, it would be a hacker's dream. This is impossible using both PHP and JavaScript, for similar reasons in each case.
Codeigniter how to load all js files from folder, without mentioning name of file.
Example- I want to get all js file from one folder. I know the path up to folder but js files are created dynamically when build is created so do not know exact name of files to load tradional way.
Maybe this solution will going to work
$js_path = rtrim(FCPATH . 'assets/js', '/'); // FCPATH = root folder of your codeigniter project
$js_files = glob("{" . $js_path . "/*.js}", GLOB_BRACE);
for($i = 0; $i < count($js_files); $i++){
echo read_file($js_files[$i]);
}
code not tested but I hope this will solve the problem
I tried following that worked for me
$folderpath = $_SERVER['DOCUMENT_ROOT'].'/resources/common/js/';
$fileName = array();
$fileName = get_filenames($folderpath);
$jsFiles = array();
foreach($fileName as $file){
$url = 'resources/common/js/'.$file;
$jsFiles[]['js'] = base_url($url);
}
$this->load->vars($jsFiles);
Im trying to make a website with users on it, and I'm trying to create a script so that whenever a new user registers it will automatically create a user folder and profile for them but when I try to register it doesn't create the files, could someone please help me with this, Thanks
<?php
include "inc/header.php";
$newfolder = $username;
if (!mkdir($newfolder, 0777, true)) {
die('Failed to create folders...');
}
$pagename = $username;
$newFileName = './u/'.$username.'/'.$pagename.".php";
$newFileContent = '<?php echo "something..."; ?>';
?>
To make a directory/file
if (!file_exists("parent_folder/$username")) {
//Create a file with read write execute PERMISSIONS ENABLED
//Please check : your parent folder also must have 0777 permissions to avoid any kind of read write error
mkdir("parent_folder/$username", 0777);
//now u have to create a FILE with .php
//now this file_put_contents is VERY importnant !
$pagename = $username ;
$newFileName = './parent_folder/$username/'.$pagename.".php";
$newFileContent = '<?php echo "something..."; ?>';
if (file_put_contents($newFileName, $newFileContent) !== false) {
//notify file is created
echo "File created (" . basename($newFileName) . ")";
} else {
//notify u have error
echo "Cannot create file (" . basename($newFileName) . ")";
}
//now create ur .php file in user folder
}
else {
echo "Your parent folder does not exist"
}
Now the possible error and some tips
1) Most of people do fopen("filename_with_PATH", "w")
and expect that file will be generated in PATH folder !
Some times it might fall wrong (depends on version)
fopen is meant to create a file in the directory where your php resides
2) check ur php permission in php.ini if u dont give php permission to write,remote access then u might get some errors (it will be displayed that u have error in my script)
3)For more info and tinkering file_put_contents
Hope this will be helpful for you ..
This is a strange request I suppose, but I have a directory full of txt files. For example:
- david_smith_interview.txt -
- beth_martin_interview.txt -
- sally_smithart_interview.txt
The contents of these text files are a link to their interview in an mp3 format, for example, if you open the file david_smith_interview.txt, it is simply this:
http://www.interviews/employees/david_smith.mp3
All of the other text files follow the same format. They are simply links to their mp3 interview.
I am trying to use something like below to list the text files:
<?php
$directory = "/employees/";
$phpfiles = glob($directory . "*.txt");
foreach($phpfiles as $phpfile)
{
echo $phpfile; // This will list the files by name
// How can I output something to reflect this:
// david_smith_interview
}
?>
So I am asking is it possible that the text file can be "read" and used as the actual link?
Any thoughts?
Replace _interview.txt with .mp3
echo "" . str_replace(".txt", "", $phpfile). "\";
Since those are .txt files you can just read them one by one to a variable and then echo the result in a for-loop.
In pseudo:
$paths fetch_paths()
$urls = array();
foreach($paths as $path)
{
$url=fopen($path);
array_push($urls,fgets(url)); // Assuming there's only one link per file and it is on one line.
}
foreach($urls as $url)
{
echo <Your formatted link here>
}