As it stands I am having real trouble figuring out just how to get the functions delete, move/copy, rename into an array via click of an image or text, and then making the function correspond to the correct row in the table and the correct file on the row in the array.
This is a very hard question to word to be honest but the array currently populates a table with files in a folder, file name, size and date modified, I'm trying to add in small images on each row for delete file, rename file ect. so that these images are linked with functions so when pressed it will delete the corresponding file or rename it if that makes sense. anyway the array code is below, and I understand if its difficult to answer just figured I would ask.
Also $cellOptions is the cell im trying to populate it currently just gives me back the logged in user
http://pastebin.com/dkeUAk50
function listFiles($dir)
{
$output = ''; $outRows = ''; $files = array();
if (is_dir($dir)) {
if ($dirHandle = opendir($dir)) {
$files = array_diff(scandir($dir), array('.', '..', '.htaccess'));
$totalSize = (int) 0;
foreach($files as $file) {
$fileTime = #date("d-M-Y", filectime($dir . '/' . $file)) . ' ' . #date("h:i", filemtime($dir . '/' . $file));
$totalSize += filesize($dir . '/' . $file);
$fileSize = #byte_convert(filesize($dir . '/' . $file));
$cellLink = '<td class="list_files_table_file_link">' . $file . '</td>';
$cellTime = '<td>' . $fileTime . '</td>';
$cellOptions = '<td>'. $_SESSION['Username'] .'<td>';
$cellSize = '<td>' . $fileSize . '</td>';
$outRows .= '<tr>' . "\n " . $cellLink . "\n " . $cellTime . "\n " . $cellSize . "\n" . $cellOptions . '</tr>' . "\n";
}
closedir($dirHandle);
}
}
$output = '<table class="list_files_table" width="100%" align="center" cellpadding="3" cellspacing="1" border="0">' . "\n";
$output .= '<thead><tr><td><b>Name</b></td><td><b>Date Modified</b></td><td><b>Size</b></td></tr></thead>' . "\n";
$output .= '<tfoot><tr><td colspan="2">' . count($files) . ' files.</td><td>' . #byte_convert($totalSize) . '</td></tr></tfoot>' . "\n";
$output .= '<tbody>' . "\n";
$output .= $outRows;
$output .= '</body>' . "\n";
$output .= '</table>';
return $output;
}
function byte_convert($bytes)
{
$symbol = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$exp = (int) 0;
$converted_value = (int) 0;
if ($bytes > 0) {
$exp = floor(log($bytes)/log(1024));
$converted_value = ($bytes/pow(1024,floor($exp)));
}
return sprintf('%.2f ' . $symbol[$exp], $converted_value);
}
session_start();
echo listFiles($_SESSION['UserFolder']);
Add an element that contains the following in your loop:
A form that submits to the same page with a method of POST
An hidden input element that contains the filename
A submit button to submit the form.
This is what it would look like:
$cellSize = '<td>' . $fileSize . '</td>';
$deleteCell = '<td><form action="/" method="POST"><input type="hidden" value="'.$file.'" ame="fileToDelete"/><input type="submit" value="Delete" name="deleteButton"/></form></td>';
Create a function to delete:
function deleteFile($dir, $fileToDelete){
if (is_dir($dir)) {
if ($dirHandle = opendir($dir)) {
$files = array_diff(scandir($dir), array('.', '..', '.htaccess'));
if($files){
foreach($files as $file){
if($file === $fileToDelete) {
unlink($fileToDelete);
$output = 'Successfully deleted file: '.$fileToDelete;
}
}
}
}
}
return $output;
}
Check if a form was submitted, and if so, delete the file in question:
if(isset($_POST)){
echo deleteFile($_SESSION['UserFolder'], $_POST['fileToDelete']);
}
Related
I have the following attempt at my function, but it's just printing out everything in the contacts.txt file on one line...
function contactsTable(){
$file = fopen("contacts.txt", "r") or die("Unable to open file!");
echo "<tr><th>";
while (!feof($file)){
echo "<tr><th>";
$data = fgets($file);
echo "<tr><td>" . str_replace(',','</td><td>',$data) . '</td></tr>';
}
echo "<tr><th>";
echo '</table>';
fclose($file);
}
contacts.txt example like this;
Row 1 is headers ---> [value1, value2, value3, value4]
Row 2 is data ---> [value5, value6, value7, value8]
Is it possible to change my function so that Row 1 is using <th> tags so they are formatted as headers and the rest of the rows go into <td> tags for table data? I've tried to amend the logic but can't seem to get it.
TIA
Here is your contactsTable() function that prints the first contacts.txt line as table header and some basic HTML formatting for easy reading/debugging.
function contactsTable() {
$file = fopen('contacts.txt', 'r') or die('Unable to open file!');
$row = 0;
echo '<table>' . PHP_EOL;
while (!feof($file)) {
$row++;
$data = fgets($file);
if ($row === 1) {
echo '<tr>' . PHP_EOL;
echo '<th>' . str_replace(',', '</th><th>', $data) . '</th>' . PHP_EOL;
echo '</tr>' . PHP_EOL;
} else {
echo '<tr>' . PHP_EOL;
echo '<td>' . str_replace(',', '</td><td>', $data) . '</td>' . PHP_EOL;
echo '</tr>' . PHP_EOL;
}
}
echo '</table>' . PHP_EOL;
fclose($file);
}
Trying to display filename but code is resulting in full file url displaying
if (trim($s) == "") continue;
$arrfilename = explode("\/", $s);
$shortfilename = $arrfilename[count($arrfilename)-1];
$path_parts = pathinfo($s);
$dir = $path_parts['dirname'];
$basename = $path_parts['basename'];
$ext = $path_parts['extension'];
$fn = $path_parts['filename'];
$sliderimage = $dir . '/' . $fn . '.' . $ext;
if (!file_exists($sliderimage) && !file_exists('../' . $sliderimage)) $sliderimage = $s;
$output .= '[setslideshowlinkattributes ssrs="' . $s . '"]<img src="/' . $sliderimage . '" alt="' .$shortfilename . '" /></a>';
}
$output .= '</div>';
$output .= ' <div id="htmlcaption" style="display: inline;">' . $this->options->slideshowcaption . '</div>';
$output .= '</div>';
I have one little question, this is my code to list all files from a folder and subfolders;
if ($handle = opendir($dir)) {
$allFiles = array();
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if (is_dir($dir . "/" . $entry)){
$allFiles[] = "D: " . $dir . "/" . $entry;
}else{
$extension = strtoupper(pathinfo($entry, PATHINFO_EXTENSION));
$fileNoExten = pathinfo($entry, PATHINFO_FILENAME);
$directory = substr(str_replace('/', ' > ', $dir), $rootLenOnce + 3);
$listagem .= '<tr>';
$listagem .= "<td><a href='../" . $dir . "/" . $entry . "' ' target='_blank'>" . $entry . "</a></td>";
//$listagem .= "<td><small>" . $directory . "</small></td>";
$listagem .= "<td>" . $extension . "</td>";
$listagem .= "<td><a class='download-cell' href='../".$dir ."/". $entry."' ' download> <i class='fa fa-download' ></i></a></td>";
$listagem .= "<td class='display-none'>" . $fileNoExten . "</td>";
$allFiles[] = "F: " . $dir . "/" . $entry;
$listagem .= '</tr>';
echo "<pre>"; print_r(glob("*.pdf")); echo "</pre>";
}
}
}
closedir($handle);
foreach($allFiles as $value){
$displayName = substr($value, $rootLen + 4);
$fileName = substr($value, 3);
$linkName = str_replace(" ", "%20", substr($value, $pathLen + 3));
if (is_dir($fileName)) {
myScanDirPdf($fileName, $level + 1, strlen($fileName),$rootLenOnce);
}
}
}
return $listagem;
}
what i need is to filtrate the search, to search only .pdf files.
Someone can help me plz!
Thks!
i try with the glob function, but not with great results.
Thks!
When you are looping through each file, you can use
if(stripos($fileName, ".pdf"))
Hope this will help
I have one more suggestion in listing all the files and subfolders.
You can use Recursive Iterator
$folderName = $_POST['folderName'];
$dir = new RecursiveDirectoryIterator($folderName);
$it = new RecursiveIteratorIterator($dir);
foreach ($it as $fileinfo) {
if ($fileinfo->isDir()) {
}elseif ($fileinfo->isFile()) {
$fileName = $fileinfo->getFileName();
if(stripos($fileName, ".pdf")) {
//do what you need to do
}
}
}
The following code counts the number of files inside a folder.
<?php
function folderlist(){
$directoryist = array();
$startdir = './';
//get all image files with a .jpg extension.
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
if (is_dir($startdir)){
if ($dh = opendir($startdir)){
while (($folder = readdir($dh)) !== false){
if (!(array_search($folder,$ignoredDirectory) > -1)){
if (filetype($startdir . $folder) == "dir"){
$directorylist[$startdir . $folder]['name'] = $folder;
$directorylist[$startdir . $folder]['path'] = $startdir;
}
}
}
closedir($dh);
}
}
return($directorylist);
}
$folders = folderlist();
$total_files = 0;
foreach ($folders as $folder){
$path = $folder['path'];
$name = $folder['name'];
$count = iterator_count(new DirectoryIterator($path . $name));
$total_files += $count;
echo '<li>';
echo '<a href="' .$path .'index.php?album=' .$name . '" class="style1">';
echo '<strong>' . $name . '</strong>';
echo ' (' . $count . ' files found)';
echo '</a>';
echo '</li>';
}
echo "Total Files:". $total_files;
?>
However for some reason the count is off by 2. I have a folder with 13 files but this code returns count as 15. For an empty folder, this returns a count of 2.
Can someone point to me the issue with the above snippet?
I'm doing it with DirectoryIterator
$files_in_directory = new DirectoryIterator($path_to_folder);
$c = 0;
foreach($files_in_directory as $file)
{
// We want only files
if($file->isDot()) continue;
if($file->isDir()) continue;
$c++;
}
var_dump($c);
For use as function :
function folderlist($directories = array(), $extensions = array())
{
if(empty($directories))
return false;
$result = array();
$total_count = 0;
foreach($directories as $directory)
{
$files_in_directory = new DirectoryIterator($directory);
$c = 0;
foreach($files_in_directory as $file)
{
// We want only files
if($file->isDot()) continue;
if($file->isDir()) continue;
// This is for php < 5.3.6
$file_extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION);
// If you have php >= 5.3.6 you can use following instead
// $file_extension = $fileinfo->getExtension()
if(in_array($file_extension, $extensions)){
$c++;
$result['directories'][$directory]['files'][$c]['name'] = $file->getFilename();
$result['directories'][$directory]['files'][$c]['path'] = $file->getPath();
$result['directories'][$directory]['count'] = $c;
}
}
$total_count += $c;
}
$result['total_count'] = $total_count;
return $result;
}
Displaying results based on GET superglobal:
if(isset($_GET['album']) && !empty($_GET['album']) && !isset($_GET['listfiles']))
{
// We are in directory view mode
$album = $_GET['album'];
// View all directories and their file count for specified album
$view_directory = folderlist(array($album), array('jpeg', 'jpg', 'log'));
// Loop the folders and display them with file count
foreach ($view_directory['directories'] as $folder_name => $folder_files){
$count = $folder_files['count'];
echo '<li>';
echo '<a href="files.php?album=' . $folder_name . '&listfiles=1" class="style1">';
echo '<strong>' . basename($folder_name) . '</strong>';
echo ' (' . $count . ' files found)';
echo '</a>';
echo '</li>';
}
echo "Total Files:". $get_dir_info['total_count'];
}
elseif(isset($_GET['album'], $_GET['listfiles']) && !empty($_GET['album']))
{
// We are in file view mode for folder
$album = $_GET['album'];
// View all files in directory
$view_files = folderlist(array($album), array('jpeg', 'jpg', 'log'));
echo 'Showing folder content of: <b>'.basename($album).'</b>';
foreach($view_files['directories'][$album]['files'] as $file)
{
$path = $file['path'];
$name = $file['name'];
echo '<li>';
echo '<a href="files.php?file=' . $name . '&path=' . $path . '" class="style1">';
echo '<strong>' . $name . '</strong>';
echo '</a>';
echo '</li>';
}
}
This line is still returning the '.' and '..' vars.
if (!(array_search($folder,$ignoredDirectory) > -1))
see: http://php.net/manual/en/language.types.boolean.php
Try
if (!array_search($folder,$ignoredDirectory))
EDIT:
Also change this:
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
to
$ignoredDirectory = array( '.', '..' );
how can i get image path on server using "browse" button in a html form, select the file (double clicking the file returning its full path), and put the result image path into variable $img_path?
let's say the image dir in my server is /images, i'd like to get path of "foo.jpg", the full image path should be "/images/foo.jpg"
so, all i have to do is :
1. create form which contain "browse" button or something like that - that allow me to explore "images" directory at my server
2. exploring "images" dir, all files listed and clickable, locate "foo.jpg", select it, and voila, i get the image path "/images/foo.jpg"
any lil' help would be appreciated..
Thanks
#CodeCaster thanks for your respond.. but this is all i want (at least closer) :
<?php
$dir = '/images';
if (!isset($_POST['submit'])) {
if ($dp = opendir($dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
} else {
exit('Directory not opened.');
}
if ($files) {
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">';
foreach ($files as $file) {
echo '<input type="checkbox" name="files[]" value="' . $file . '" /> ' .
$file . '<br />';
}
echo '<input type="submit" name="submit" value="submit" />' .
'</form>';
} else {
exit('No files found.');
}
} else {
if (isset($_POST['files'])) {
foreach ($_POST['files'] as $value) {
echo $dir . $value . '<br />';
}
} else {
exit('No files selected');
}
}
?>
using "dir" you can achieve your goal.
<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();
?>
You could use dir:
echo "<ul>";
$d = dir("images");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo "<li>" . $entry . "</li>";
}
$d->close();
echo "</ul>";