PHP - reading folder, all subfolders, and files in subfolders - php

I have a folder named "inspections" which has a number of subfolders named "location 1", "location 2", "location 3", etc. each with around 10-20 .png images in it.
What I am trying to do, is to read the directories of the "inspections" folder, and then read all the image files in each of the folders before returning them as a gallery on my index.php site. The problem is that I get no error message but the script doesnt return anything. I believe the problem is with generating the $files variable for each subfolder as I deploy the same script for reading folder content on another site.
Perhaps someone can point me in the right direction?
<?php
$dir = './inspections/';
if ($handle = opendir($dir))
{
$blacklist = array('.', '..', 'default', 'default.php', 'desc.txt');
while (false !== ($folder = readdir($handle)))
{
if (!in_array($folder, $blacklist))
{
if (file_exists($dir . $folder . '/desc.txt'))
{
while (false !== ($file = readdir($handle)))
{
if (!in_array($file, $blacklist))
{
$chain = file_get_contents($dir . $folder . '/chain.txt');
$website = file_get_contents($dir . $folder . '/website.txt');
$location = file_get_contents($dir . $folder . '/location.txt');
$desc = file_get_contents($dir . $folder . '/desc.txt', NULL, NULL, 0, 250) . '...';
echo "
<!-- Post -->
<div class=\"post\">
<div class=\"user-block\">
<img class=\"img-circle img-bordered-sm\" src=\"../dist/img/logo/logo_".$chain."\" alt=\"\">
<span class=\"username\">
".$folder."
</span>
<span class=\"description\"><i class=\"fa fa-map-pin\"></i> ".$location." - Posted on ". $date . "</span>
</div>
<!-- /.user-block -->
<p>".$desc."</p>
<div class=\"lightBoxGallery\">
<img src=\"".$dir . $folder . "/".$file."\" style=\"height:100px; width:100px;\">
</div>
";
}
}
}
}
}
closedir($handle);
}
?>
EDIT:
following #JazZ suggestion, I have adjusted the code and it works well now, however, assuming that one does not want to display the resized pictures itself, but rather thumbnails stored in a subfolder (eg. ./location1/thumbs/), how would I go about this?
<?php
$dir = './inspections/';
if ($handle = opendir($dir)) {
$blacklist = array('.', '..', 'default', 'default.php', 'desc.txt');
while (false !== ($folder = readdir($handle))) {
if (!in_array($folder, $blacklist)) {
echo "
<!-- Post -->
<div class=\"post\">
<div class=\"user-block\">
<img class=\"img-circle img-bordered-sm\" src=\"../dist/img/logo/gallery_icon_".$chain.".jpg\" alt=\"\">
<span class=\"username\">
".$hotel_name."".$status."
</span>
<span class=\"description\"><i class=\"fa fa-map-pin\"></i> ".$location." - Posted on ".date('jS F, Y - H:m', strtotime($posted_on))."</span>
</div>
<!-- /.user-block -->
<p>".$desc."</p>
<div class=\"lightBoxGallery\">
";
foreach (glob($dir . $folder . "/*.jpg") as $filename) {
echo "
<img src=\"".$filename."\" style=\"height:100px; width:100px;\">";
}
echo "</div>
</div>
<!-- /. POST -->
";
}
}
closedir($handle);
}
?>

I think your issue comes from here :
while (false !== ($file = readdir($handle))) // it reads again the same directory as it did in the first while loop
Try to replace it with
if ($sub_handle = opendir($dir . $folder)) {
while (false !== ($file = readdir($sub_handle))) {
...
}
closedir($sub_handle);
}
Also, in your case, I would use php glob() function
See a working example for your case :
$dir = './inspections/';
if ($handle = opendir($dir)) {
$blacklist = array('.', '..', 'default', 'default.php', 'desc.txt');
while (false !== ($folder = readdir($handle))) {
if (!in_array($folder, $blacklist)) {
foreach (glob($dir . $folder . "/*.png") as $filename) {
echo "$filename was found !";
echo "\r\n";
}
}
}
closedir($handle);
}
Output :
./inspections/location_4/img_1.png was found !
./inspections/location_4/img_2.png was found !
./inspections/location_4/img_3.png was found !
./inspections/location_4/img_4.png was found !
./inspections/location_4/img_5.png was found !
./inspections/location_4/img_6.png was found !
./inspections/location_3/img_1.png was found !
./inspections/location_3/img_2.png was found !
./inspections/location_3/img_3.png was found !
./inspections/location_3/img_4.png was found !
./inspections/location_3/img_5.png was found !
./inspections/location_3/img_6.png was found !
./inspections/location_2/img_1.png was found !
./inspections/location_2/img_2.png was found !
./inspections/location_2/img_3.png was found !
./inspections/location_2/img_4.png was found !
./inspections/location_2/img_5.png was found !
./inspections/location_2/img_6.png was found !
./inspections/location_1/img_1.png was found !
./inspections/location_1/img_2.png was found !
./inspections/location_1/img_3.png was found !
./inspections/location_1/img_4.png was found !
./inspections/location_1/img_5.png was found !
./inspections/location_1/img_6.png was found !
EDIT
To loop in the /inspections/location1/thumbs/ directories, this would work :
foreach (glob($dir . $folder . "/thumbs/*.png") as $filename) {
echo "$filename was found !";
echo "\r\n";
}
RE-EDIT
To glob multiple folders with the glob() function, your code should look like :
foreach (glob($dir.$folder."{/thumbs/*.png,/*.png}", GLOB_BRACE) as $filename) {
echo "$filename was found !";
echo "\r\n";
}

Perhaps the Function below helps. It is also somewhat commented. It scans a directory recursively (in this case, extracting image files from each directory/sub-directory).
<?php
$rootPath = './inspections/';
$regex = "#(\.png$)|(\.jpg$)|(\.jpeg$)|(\.tiff$)|(\.gif$)#";
/**
* #param string $directory => DIRECTORY TO SCAN
* #param string $regex => REGULAR EXPRESSION TO BE USED IN MATCHING FILE-NAMES
* #param string $get => WHAT DO YOU WANT TO GET? 'dir'= DIRECTORIES, 'file'= FILES, 'both'=BOTH FILES+DIRECTORIES
* #param bool $useFullPath => DO YOU WISH TO RETURN THE FULL PATH TO THE FOLDERS/FILES OR JUST THEIR BASE-NAMES?
* #param array $dirs => LEAVE AS IS: USED DURING RECURSIVE TRIPS
* #return array
*/
function scanDirRecursive($directory, $regex=null, $get="file", $useFullPath=false, &$dirs=[], &$files=[]) {
$iterator = new DirectoryIterator ($directory);
foreach($iterator as $info) {
$fileDirName = $info->getFilename();
if ($info->isFile () && !preg_match("#^\..*?#", $fileDirName)) {
if($get == 'file' || $get == 'both'){
if($regex) {
if(preg_match($regex, $fileDirName)) {
if ($useFullPath) {
$files[] = $directory . DIRECTORY_SEPARATOR . $fileDirName;
}
else {
$files[] = $fileDirName;
}
}
}else{
if($useFullPath){
$files[] = $directory . DIRECTORY_SEPARATOR . $fileDirName;
}else{
$files[] = $fileDirName;
}
}
}
}else if ($info->isDir() && !$info->isDot()) {
$fullPathName = $directory . DIRECTORY_SEPARATOR . $fileDirName;
if($get == 'dir' || $get == 'both') {
$dirs[] = ($useFullPath) ? $fullPathName : $fileDirName;
}
scanDirRecursive($fullPathName, $regex, $get, $useFullPath, $dirs, $files);
}
}
if($get == 'dir') {
return $dirs;
}else if($get == 'file'){
return $files;
}
return ['dirs' => $dirs, 'files' => $files];
}
$images = scanDirRecursive($rootPath, $regex, 'file', true);
var_dump($images);

Related

PHP get all images with prefix 1_, 2_, 3_ etc. if they exist in folder

Goal:
get all images with prefix 1_, 2_, 3_ etc. if they exist in folder
Question:
The image names are dynamically added by the db while loop. This returns: 13848. But I need to retrieve: 13848.jpg, 1_13848.jpg, 2_13848.jpg, 3_13848.jpg if they exist.
How to check and return the images that exist with this pattern.
The image name is same as the product_id.
I am getting the name/id part from database query.
My existing images:
folder_name/13848.jpg
folder_name/1_13848.jpg
folder_name/2_13848.jpg
folder_name/3_13848.jpg
My efforts:
function imageExists($image,$dir) {
$i=1; $try=$image;
while(file_exists($dir.$probeer)) {
if($image[1] != "_") {
$try= $i. "_" . $image;
}
else {
$try=$image;
}
$i++;
}
return $try;
}
Using it like so:
while ($r = $q->fetch()) {
$image_folder = "folder_name/";
$image_id = $r['product_id'].".jpg";
$new_imagePath = $image_folder . imageExists($image_id,$image_folder);
echo "<a href='". $imagePath ."'><img class='product' height='' src='". $new_imagePath ."' alt='". $r['product_id'] ."-". str_replace("'", "", $r['product_name']) . "' title='". str_replace("'", "", $r['product_name']) ."' /></a>";
}
Now it returns the images that don't exist:
folder_name/4_13848.jpg
$files = glob('FOLDER_PATH/*.{jpg}',GLOB_BRACE);
function image_exist($files){
foreach($files as $file){ //retrieves all file name in specified folder
if (strpos($file, '_') !== false){ //Checks 1_567898.jpg type file exist
return true;
}
else{
return false;
}
}
}

Load More Button With PHP DirectoryIterator?

I have a number of "image gallery" style pages within my WordPress site. I'm trying to find out whether or not it's possible, using the method that I'm using, to create a 'Load More' button so that only 15 (for example, can be whatever) thumbnails load at a time.
To gather the files that should be displayed I'm using PHP's DirectoryIterator. I use the same custom function for every page, but the function itself is a bit long and messy. Essentially, I need to be able to just drop files into the appropriate directory and have them automatically detected and have the thumbnail shown with a link to the full-size image.
I already have this set up and working. Half of the function also checks for any sub-directories and repeats the process for those so that I can have any number of "galleries", each with any number of images, on a single page simply by creating directories and uploading files.
It's rather long, but for reference I feel like I need to paste the full function when asking this question so that people know what I'm working with. The type of content I'm working with is video game screenshots.
function display_screenshots() {
global $post;
$post_data = get_post($post->post_parent);
$parent_slug = $post_data->post_name;
$img_directory = '/wp-content/uploads/screenshots/' . $parent_slug . '/';
$thumb_directory = '/wp-content/uploads/screenshots/' . $parent_slug . '/thumb/';
$img_list_directory = getcwd() . '/wp-content/uploads/screenshots/' . $parent_slug . '/';
if(is_dir($img_list_directory)) {
$found_shots = array();
echo '<div class="screenshot-thumbs-outer">';
echo '<div class="screenshot-thumbs-inner">';
foreach(new DirectoryIterator($img_list_directory) as $file) {
if ($file->isDot()) continue;
$fileName = $file->getFilename();
$filetypes = array(
"png",
"PNG"
);
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (in_array(strtolower($filetype), $filetypes )) {
$found_shots[] = array(
"fileName" => $fileName
);
}
}
asort($found_shots);
foreach($found_shots as $file) {
$filename = $file['fileName'];
$thumbname = substr($filename, 0, -3).'jpg';
echo '<a href="#" data-featherlight="'.$img_directory.$filename.'" rel="nofollow">';
echo '<img src="'.$thumb_directory.$thumbname.'"/>';
echo '</a>';
}
echo '</div>';
echo '</div>';
}
if(is_dir($img_list_directory)) {
foreach(new DirectoryIterator($img_list_directory) as $dir) {
if($dir->isDir() && $dir != '.' && $dir != '..' && $dir != 'thumb') {
$dir_h2 = substr($post->post_title, 0, -12) . ' - ' . str_replace(array('Hd ', ' Hd ', ' Of ', ' The ', ' A ', ' To '), array('HD ', ' HD ', ' of ', ' the ', ' a ', ' to '), ucwords(str_replace("-", " ", $dir))) . ' Screenshots';
$img_directory = '/wp-content/uploads/screenshots/' . $parent_slug . '/' . $dir . '/';
$thumb_directory = '/wp-content/uploads/screenshots/' . $parent_slug . '/' . $dir . '/thumb/';
$img_list_directory = getcwd() . '/wp-content/uploads/screenshots/' . $parent_slug . '/' . $dir . '/';
$found_shots = array();
echo '<hr />';
echo '<h2>' . $dir_h2 . '</h2>';
echo '<div class="screenshot-thumbs-outer">';
echo '<div class="screenshot-thumbs-inner">';
foreach(new DirectoryIterator($img_list_directory) as $file) {
if ($file->isDot()) continue;
$fileName = $file->getFilename();
$filetypes = array(
"png",
"PNG"
);
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (in_array(strtolower($filetype), $filetypes )) {
$found_shots[] = array(
"fileName" => $fileName
);
}
}
asort($found_shots);
foreach($found_shots as $file) {
$filename = $file['fileName'];
$thumbname = substr($filename, 0, -3).'jpg';
echo '<a href="#" data-featherlight="'.$img_directory.$filename.'" rel="nofollow">';
echo '<img src="'.$thumb_directory.$thumbname.'"/>';
echo '</a>';
}
echo '</div>';
echo '</div>';
}
}
}
}
Again, this function is working as intended, I just want to find some way to add 'Load More' functionality so that if there are 150 images, only 15 will load at a time. I'll also need to duplicate the code for the 'Load More' button in the second half of the function so that it's happening for any additional galleries on the page as well.
I realize that this is a lot for someone else to dive into, but I've put a lot of time into combing answers on this site as well as searching Google and I haven't been able to find a solution that's really relevant to the function I'm using to gather/display these images.
Any help will definitely be appreciated.
Thanks!

How to Load Twig Template Outside of the Theme Folder?

I just learning Twig templating and I am having trouble figuring out how to load a template part that is in a directory outside of the current themes' directory so they can be reused by other themes.
I am starting with just a simple loading of a head.html template part located in the core/tpls/ directory. With the variouse methodes I have tried, I get the following error:
PHP Fatal error: Uncaught exception 'Twig_Error_Loader' with message
'Unable to find template "/home/ubuntu/workspace/core/tpls/head.html"
(looked into: /home/ubuntu/workspace/themes/core) in "base.html" at
line 5.
The file is in the directory and the path is correct despite that the log error says otherwise.
My base.html located in the themes/core/ directory contains the custom Twig function to include the head.html template located outside of the theme directory:
<html lang="en" class="no-js">
<head>
{% include core.head %} // This is line 5 and throws the error and need to work correctly
// {% include core_head %} // This throws the error and should function the same as {% include core_head %}
// {% include tpl.head %} <-- If I use this, my function for grabbing templates from the theme works since I have a copy of the head.html in the theme dir too //
</head>
<body>
<header id="header">
{% include tpl.header %} // This works via the get_tpl() function
</header>
{% include tpl.breadcrumbs %} // This works too
[. . .]
I hate to clutter this with an entire class but it may be helpful for someone to see what I have wrong. The get_core_tpl() function is what I cannot get working where my other get_*() functions work as they should. See my comments there and also, take note to my comments in the befor_rendor() function:
<?php
class Get_TPLs {
private $tpl_name,
$theme = 'core',
$tpl_array = array(
'breadcrumbs',
'content',
'cover',
'footer',
'head',
'header',
'sidebar'
);
public function before_load_content(&$file) {
$this->tpl_name = basename($file, '.md');
}
public function config_loaded(&$settings) {
if (isset($settings['core_tpl']))
$this->core_tpl = $settings['core_tpl'];
if (isset($settings['tpl_array']))
$this->tpl_array = $settings['tpl_array'];
if (isset($settings['theme']))
$this->theme = THEMES_DIR . $settings['theme'];
}
public function file_meta(&$meta) {
$config = $meta;
if (isset($config['slug'])):
$this->tpl_name = strtolower($config['slug']);
endif;
}
public function before_render(&$twig_vars, &$twig) {
//// ==== THIS IS CALLED WITH {% include core.[TEMPLATE_NAME] %} SEE Base.html ==== ////
// core/tpl/file
$twig_vars['core'] = $this->get_core_tpl();
//// === THIS IS A SIMPLIFIED VERSION OF THE ABOVE VAR - IT'S CALLED WITH {% include core_head %} but It throws the same error ==== ////
$twig_vars['core_head'] = CORE_TPL . '/head.html';
// theme/tpl/file
$twig_vars['tpl'] = $this->get_tpl();
// theme/tpl/views/file
$views = $this->get_views();
$twig_vars['views'] = $views;
// theme/content/file
$theme = $this->get_theme_content();
$twig_vars['theme'] = $theme;
//var_dump($twig_vars['theme']);
}
//// ==== THIS IS THE FUNCTION IN QUESTION ==== ////
private function get_core_tpl() {
foreach ($this->tpl_array as $value) {
$pattern = array('/ /', '/_/');
$name = preg_replace($pattern, '_', $value);
$core[$name] = CORE_TPL . $value . '.html';
}
return $core;
}
private function get_tpl() {
foreach ($this->tpl_array as $value) {
$pattern = array('/ /', '/_/');
$name = preg_replace($pattern, '_', $value);
$tpl[$name] = 'tpl/' . $value . '.html';
$page_tpl = $this->theme . '/tpl/' . $this->tpl_name . '-' . $value . '.html';
if (file_exists($page_tpl))
$tpl[$name] = '/tpl/' . $this->tpl_name . '-' . $value . '.html';
}
return $tpl;
}
private function get_theme_content() {
$content = $this->get_files($this->theme . '/content', '.md');
$content_data = array();
if (empty($content))
return;
foreach ($content as $key) {
$file = $this->theme . '/content/' . $key . '.md';
$pattern = array('/ /', '/-/');
$title = preg_replace($pattern, '_', strtolower($key));
$data = file_get_contents($file);
$content_data[$title] = \Michelf\MarkdownExtra::defaultTransform($data);
}
return $content_data;
}
private function get_views() {
$view_dir = $this->theme . '/tpl/views';
$views = $this->get_files($view_dir);
if (empty($views))
return;
$pattern = array('/ /', '/-/');
foreach ($views as $key) {
$name = preg_replace($pattern, '_', $key);
$view[$name] = 'tpl/views/' . $key . '.html';
if (file_exists($this->theme . '/tpl/' . $this->tpl_name . '-' . $key . '.html'))
$view[$name] = 'tpl/views/' . $this->tpl_name . '-' . $key . '.html';
}
if (!isset($view))
return array(0);
return $view;
}
// scrive.php lib
private function get_files($directory, $ext = '.html') {
if (!is_dir($directory))
return false;
$array_items = array();
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
$file = $directory . "/" . $file;
if (!$ext || strstr($file, $ext))
$array_items[] = basename($file, $ext);
}
closedir($handle);
}
return $array_items;
}
} ?>
Any help will be greatly appreciated! Thnx

PHP Run a function for each file in directory

Hello i'm rely stuck here,
Ok i already have a working function to update my database for ONE specified file, in my directory,
now i need a php code to do the same thing for each file on directory and then delete it.
$fileName = "IEDCBR361502201214659.RET";
$cnab240 = RetornoFactory::getRetorno($fileName, "linhaProcessada");
$retorno = new RetornoBanco($cnab240);
$retorno->processar();
the function linhaProcessada is
function linhaProcessada2($self, $numLn, $vlinha) {
if($vlinha["registro"] == $self::DETALHE )
{
if($vlinha["registro"] == $self::DETALHE && $vlinha["segmento"] == "T" ) {
//define a variavel do nosso numero como outra usavel
$query ="SELECT * FROM jos_cobra_boletos WHERE nosso_numero = ".$vlinha['nosso_numero']."";
echo "Boleto de numero: ".$vlinha['nosso_numero']." Atualizado com sucesso!<hr>";
$testResult = mysql_query($query) or die('Error, query failed');
if(mysql_fetch_array($testResult) == NULL){
}else{
$query = "UPDATE jos_cobra_boletos
SET status_pagamento='Pago'
WHERE nosso_numero=".$vlinha['nosso_numero']."";
$result = mysql_query($query) or die('Erro T');
}
}
}
}
Really need help on this one
PHP's opendir() ought to do the trick. More info here: http://php.net/manual/en/function.opendir.php
<?php
// Set Directory
$dir = '/abs/path/with/trailing/slash/';
if ($handle = opendir( $dir )) { // Scan directory
while (false !== ($file = readdir($handle))) { // Loop each file
$fileName = $dir . $file;
// Run code on file
$cnab240 = RetornoFactory::getRetorno($fileName, "linhaProcessada");
$retorno = new RetornoBanco($cnab240);
$retorno->processar();
// Delete file
unlink( $fileName );
}
closedir( $handle );
}
<? //PHP 5.4+
foreach(
new \GlobIterator(
__DIR__ . '/*.RET', //Or other directory where these files are
\FilesystemIterator::SKIP_DOTS |
\FilesystemIterator::CURRENT_AS_PATHNAME
)
as $pathname
){
(new RetornoBanca(
RetornoFactory::getRetorno($pathname, 'linhaProcessada')
))
->processar();
\unlink($pathname);
}
?>

Downloading Files from FTP server - Ftp_fget Warning No such file or directory

Ok, Recently I have been working on code for my website to enable users that have logged in to download files that are on the server. I have got the users logging in fine. My problem is getting the ftp_fget() function to work. I have not only tried ftp_fget() but also ftp_get() amd ftp_nb_get().
How I have got it set up at the moment is on one page all the files in a certain directory are being displayed. I then added this
<input type="image" src="images/dl_icon.png" width="41" height="41"/>
When clicked it takes the user to the ftp_download.php page which is meant to download the chosen file.
Here is what I have got for the ftp_download page.
<?=
$conn_id = ftp_connect("thomassawkins.hostoi.com","21") or die("could not connect");
$ftp_login = ftp_login($conn_id,"USERNAME", "PASSWORD");
$remote_file = $_GET['file'];
$local_file = fopen("$remote_file",'w');
ftp_pasv($conn_id, true);
if(!$ftp_login)
{
echo "could not login";
}
else
{
if (ftp_fget($conn_id, $local_file, $remote_file, FTP_BINARY)){
echo "Successfully written to $local_file\n";
} else {
echo "There was a problem\n";
}
}
ftp_close($conn);
?>
When I click on the download button for the file I get this error after being directed to the download page
Warning: ftp_fget() [function.ftp-fget]: Can't open sc2 test - 2.txt: No such file or directory in /home/a5015247/public_html/Replays/sc2_replays/ftp_download.php on line 15
sc2 test - 2.txt is the test file I am trying to download. It is saved in the directory /home/a5015247/public_html/Replays/sc2_replays/
What I am trying to achieve overall is for the user to click on the desired file to download and then have it prompt the user where they are wanting to save the file on their machine.
Any help the solves my problems will be greatly appreciated.
Regards,
Thomas
--edit--
This is the code that displays all the files in the specified directory.
<?php
$startdir = 'Replays/sc2_replays';
$showthumbnails = false;
$showdirs = true;
$forcedownloads = false;
$hide = array(
'dlf',
'public_html',
'index.php',
'Thumbs',
'.htaccess',
'.htpasswd'
);
$displayindex = false;
$allowuploads = false;
$overwrite = false;
$indexfiles = array (
'index.html',
'index.htm',
'default.htm',
'default.html'
);
$filetypes = array (
'png' => 'jpg.gif',
'jpeg' => 'jpg.gif',
'bmp' => 'jpg.gif',
'jpg' => 'jpg.gif',
'gif' => 'gif.gif',
'zip' => 'archive.png',
'rar' => 'archive.png',
'exe' => 'exe.gif',
'setup' => 'setup.gif',
'txt' => 'text.png',
'htm' => 'html.gif',
'html' => 'html.gif',
'php' => 'php.gif',
'fla' => 'fla.gif',
'swf' => 'swf.gif',
'xls' => 'xls.gif',
'doc' => 'doc.gif',
'sig' => 'sig.gif',
'fh10' => 'fh10.gif',
'pdf' => 'pdf.gif',
'psd' => 'psd.gif',
'rm' => 'real.gif',
'mpg' => 'video.gif',
'mpeg' => 'video.gif',
'mov' => 'video2.gif',
'avi' => 'video.gif',
'eps' => 'eps.gif',
'gz' => 'archive.png',
'asc' => 'sig.gif',
);
error_reporting(0);
if(!function_exists('imagecreatetruecolor')) $showthumbnails = false;
$leadon = $startdir;
if($leadon=='Replays/sc2_replays') $leadon = '';
if((substr($leadon, -1, 1)!='/') && $leadon!='') $leadon = $leadon . '/';
$startdir = $leadon;
if($_GET['dir']) {
//check this is okay.
if(substr($_GET['dir'], -1, 1)!='/') {
$_GET['dir'] = $_GET['dir'] . '/';
}
$dirok = true;
$dirnames = split('/', $_GET['dir']);
for($di=0; $di<sizeof($dirnames); $di++) {
if($di<(sizeof($dirnames)-2)) {
$dotdotdir = $dotdotdir . $dirnames[$di] . '/';
}
if($dirnames[$di] == '..') {
$dirok = false;
}
}
if(substr($_GET['dir'], 0, 1)=='/') {
$dirok = false;
}
if($dirok) {
$leadon = $leadon . $_GET['dir'];
}
}
$opendir = $leadon;
if(!$leadon) $opendir = 'Replays/sc2_replays/';
if(!file_exists($opendir)) {
$opendir = 'Replays/sc2_replays/';
$leadon = $startdir;
}
clearstatcache();
if ($handle = opendir($opendir)) {
while (false !== ($file = readdir($handle))) {
//first see if this file is required in the listing
if ($file == "." || $file == "..") continue;
$discard = false;
for($hi=0;$hi<sizeof($hide);$hi++) {
if(strpos($file, $hide[$hi])!==false) {
$discard = true;
}
}
if($discard) continue;
if (#filetype($leadon.$file) == "dir") {
if(!$showdirs) continue;
$n++;
if($_GET['sort']=="date") {
$key = #filemtime($leadon.$file) . ".$n";
}
else {
$key = $n;
}
$dirs[$key] = $file . "/";
}
else {
$n++;
if($_GET['sort']=="date") {
$key = #filemtime($leadon.$file) . ".$n";
}
elseif($_GET['sort']=="size") {
$key = #filesize($leadon.$file) . ".$n";
}
else {
$key = $n;
}
$files[$key] = $file;
if($displayindex) {
if(in_array(strtolower($file), $indexfiles)) {
header("Location: $file");
die();
}
}
}
}
closedir($handle);
}
//sort our files
if($_GET['sort']=="date") {
#ksort($dirs, SORT_NUMERIC);
#ksort($files, SORT_NUMERIC);
}
elseif($_GET['sort']=="size") {
#natcasesort($dirs);
#ksort($files, SORT_NUMERIC);
}
else {
#natcasesort($dirs);
#natcasesort($files);
}
//order correctly
if($_GET['order']=="desc" && $_GET['sort']!="size") {$dirs = #array_reverse($dirs);}
if($_GET['order']=="desc") {$files = #array_reverse($files);}
$dirs = #array_values($dirs); $files = #array_values($files);
?>
<div id="listingcontainer">
<div id="listingheader">
<div id="headerfile"></div>
<div id="headersize"></div>
<div id="headermodified"></div>
</div>
<div id="listing">
<?
$class = 'b';
if($dirok) {
?>
<div><img src="http://www.000webhost.com/images/index/dirup.png" alt="Folder" /><strong>..</strong> <em>-</em> <?=date ("M d Y h:i:s A", filemtime($dotdotdir));?></div>
<?
if($class=='b') $class='w';
else $class = 'b';
}
$arsize = sizeof($dirs);
for($i=0;$i<$arsize;$i++) {
?>
<div><img src="http://www.000webhost.com/images/index/folder.png" alt="<?=$dirs[$i];?>" /><strong><?=$dirs[$i];?></strong> <em>-</em> <?=date ("M d Y h:i:s A", filemtime($leadon.$dirs[$i]));?></div>
<?
if($class=='b') $class='w';
else $class = 'b';
}
$arsize = sizeof($files);
for($i=0;$i<$arsize;$i++) {
$icon = 'unknown.png';
$ext = strtolower(substr($files[$i], strrpos($files[$i], '.')+1));
$supportedimages = array('gif', 'png', 'jpeg', 'jpg');
$thumb = '';
if($filetypes[$ext]) {
$icon = $filetypes[$ext];
}
$filename = $files[$i];
if(strlen($filename)>43) {
$filename = substr($files[$i], 0, 40) . '...';
}
$fileurl = $leadon . $files[$i];
?>
<div>
<table width="574" border="0.5" align="center">
<tr>
<th width="59" align="center" valign="middle" scope="col"> </th>
<th width="136" align="center" valign="middle" scope="col"><img src="http://www.000webhost.com/images/index/<?=$icon;?>" alt="<?=$files[$i];?>" /><strong><?=$filename;?></strong>
</a></th>
<th width="101" align="center" valign="middle" scope="col"><em>
<?=round(filesize($leadon.$files[$i])/1024);?>
KB</em></a></th>
<th width="186" align="center" valign="middle" scope="col">
<?=date ("M d Y h:i:s A", filemtime($leadon.$files[$i]));?>
</a></th>
<th width="70" align="right" valign="middle" scope="col">
<input type="image" src="images/dl_icon.png" width="41" height="41"/>
</a></th>
</tr>
</table>
</div>
<?
if($class=='b') $class='w';
else $class = 'b';
}
?></div>
What happens is when the user clicks the icon here
<input type="image" src="images/dl_icon.png" width="41" height="41"/>
They are then redirected to download.php which handles the download part of it. At the moment I am not even able to successfully change the directory using chdir for some reason. the error that I get is
Warning: ftp_chdir() [function.ftp-chdir]: Can't change directory to /Replays/sc2_replays/: No such file or directory in /home/a5015247/public_html/ftp_download.php on line 15
the file dumby file that I am trying to download is in the directory public_html/Replays/sc2_replay/dumby.txt.
I also user ftp_pwd to find out what directory I am currently in when i get this error and it outputs "/". Im not sure what that means
ftp_chdir($conn_id, "/Replays/sc2_replays/");
echo ftp_pwd($conn_id);
Regards,
Thomas
Path name is wrong. If you don't specify a path after connecting, it's going to look in the base directory. You can either use ftp_chdir to change in to the directory, or you can prepend the path to the file you're trying to download (i.e. './folder/subfolder/file.jpg');
Also, just from looking at your script, depending on how you've configure it, there's potentially a huge security flaw. You're trusting the user to input $_GET['file'] safely, which isn't the smartest thing to do. You'll probably want to limit the files to certain directories (unless you're connecting to a file server and really do want them to be able to download anything).

Categories