php echo selected folder as input to another php function - php

I am creating a webpage that has two components
A list all the folders.
A list all the images within each folder.
My folder structure is as follows:
directory - resources
subdirectories -> location1,location2,location3
images - in each location i have -> image1,image2,image3
The php code to list all folders and print all images works fine. However I want the functionality where when the user selects a folder from the first php i want the images to be rendered through the second php.
directories.php
PHP Code to list folders (This works fine):
<?php
$direc = "";
if($handle = opendir('resources/')){
while (false !== ($file = readdir($handle)))
{
if (($file != ".") && ($file != ".."))
{
$direc .= '<li name="fold">'.$file.'</li>';
$nam = $_POST['fold'];
echo $nam; //This is not echoing
}
}
closedir($handle);
}
?>
<form method="POST" action="images.php">
<ul>
<?php echo $direc; ?>
</ul>
</form>
images.php
PHP CODE to list all images: This code also works fine
<div>
<?php
$files = glob("resources/location1/*.jpg");
for ($i=1; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'" height = "200" width = "180" id="thumbNails"/>'."<br /><br />";
$filname = basename($num, ".jpg");
$filnam = substr($filname, -5);
print $filnam."<br />";
}
?>
</div>
Not sure how to adapt this line in the second php:
$files = glob($nam/"*.jpg");

You may want to use Recursive instead which is much easier. Try this:
Whole Code
$root = __DIR__;
$selected_folder = $_POST['fold'];
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);
$folder_paths = array($root);
$image_paths = array();
foreach ($iter as $path => $dir) {
if ($dir->isDir()) {
$folder_paths[] = $path;
if(!empty(glob($path .'/*.jpg'))){
$image_paths[] = glob($path .'/*.jpg');
}
}
}
$display_images = array();
foreach($image_paths as $folders){
foreach($folders as $folder){
if(strpos($folder, $selected_folder) !== false){
$display_images[] = $path;
}
}
}
print_r($display_images);

Ok, I resolved this. The following is the code:
directories.php
<html>
<head>
<title></title>
</head>
<body>
<div>
<form action="test1.php" method="get">
<select id="dirs" name="myname">
<option value="" selected="selected">SELECT A PROJECT</option>
<?php
$dirs = glob("/var/www/html/yourdirectory/*", GLOB_ONLYDIR);
foreach($dirs as $val){
echo '<option value="'.$val.'">'.basename($val)."</option>\n";
}
?>
</select>
<input type="submit" name="submit" value="click">
</form>
</div>
</body>
</html>
subdirectories.php
<html>
<head>
<title></title>
</head>
<body>
<?php
$var = $_GET['myname'];
$direc = "";
if($handle = opendir($var)){
while (false !== ($file = readdir($handle)))
{
if (($file != ".") && ($file != ".."))
{
$direc .= '<li>'.$file.'</li>';
}
}
closedir($handle);
}
?>
<div>
<h5>LIST OF DIRECTORIES</h5>
<ul>
<form action="footer.php" method="post">
<p name="filesel"><?php echo $direc ?></p>
</form>
</ul>
</div>
</body>
</html>

Related

Why can't i change the root directory?

i'm building a directory browser and while i was looking for info i found this question, to my surprise the code is quite easier than i expected and i'm able to understand it, so i'm using it on my project(i'm quite new to php, and i never use code that i don't understand). It works fine and i've made a few aesthetic changes. Now here comes the problem, for some reason i cannot change the root directory, i have this:
<?php
session_start();
if(!isset($_SESSION['username'])){
header("Location: ./test.php");
}
?>
<!doctype html>
<html>
<head>
<title>CoroCloud</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./js/material.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.pink-indigo.min.css" />
</head>
<html>
<body>
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class="mdl-layout__header">
<div class="mdl-layout__header-row">
<!-- Title -->
<span class="mdl-layout-title">Cloud</span>
<!-- Add spacer, to align navigation to the right -->
<div class="mdl-layout-spacer"></div>
<!-- Navigation. We hide it in small screens. -->
<nav class="mdl-navigation mdl-layout--large-screen-only">
<?php
echo "<a class=\"mdl-navigation__link\" href=\"\">{$_SESSION['username']}</a>";
?>
</nav>
</div>
</header>
<div class="mdl-layout__drawer">
<span class="mdl-layout-title">CATEGORIES</span>
<nav class="mdl-navigation">
<a class="mdl-navigation__link" href="">File</a>
<a class="mdl-navigation__link" href="">Images</a>
<a class="mdl-navigation__link" href="">Music</a>
<a class="mdl-navigation__link" href="">Films</a>
</nav>
</div>
<main class="mdl-layout__content" style="background-color: white; background-image: url('https://i.warosu.org/data/tg/img/0357/97/1414469732022.gif'); background-size: auto 100%; background-repeat: no-repeat; background-position: center;">
<center>
<div class="page-content" style="padding: 24px; flex: none; align-items: center; justify-content: center;">
<?php
// Snippet from PHP Share: http://www.phpshare.org
function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824)
{
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
}
elseif ($bytes >= 1048576)
{
$bytes = number_format($bytes / 1048576, 2) . ' MB';
}
elseif ($bytes >= 1024)
{
$bytes = number_format($bytes / 1024, 2) . ' kB';
}
elseif ($bytes > 1)
{
$bytes = $bytes . ' bytes';
}
elseif ($bytes == 1)
{
$bytes = $bytes . ' byte';
}
else
{
$bytes = '0 bytes';
}
return $bytes;
}
$root = dirname("path");
function is_in_dir($file, $directory, $recursive = true, $limit = 1000) {
$directory = realpath($directory);
$parent = realpath($file);
$i = 0;
while ($parent) {
if ($directory == $parent) return true;
if ($parent == dirname($parent) || !$recursive) break;
$parent = dirname($parent);
}
return false;
}
$path = null;
if (isset($_GET['file'])) {
$path = $_GET['file'];
if (!is_in_dir($_GET['file'], $root)) {
$path = null;
} else {
$path = '/'.$path;
}
}
if (is_file($root.$path)) {
readfile($root.$path);
return;
}
echo "<div>\n";
echo "<table class=\"mdl-data-table mdl-js-data-table mdl-shadow--2dp\" style=\"min-width:300px\"\n";
echo " <thead>\n";
echo " <tr>\n";
echo " <th class=\"mdl-data-table__cell--non-numeric\">File</th>\n";
echo " <th>Size</th>\n";
echo " </tr>\n";
echo " </thead>\n";
echo " <tbody>";
if ($path) echo '<tr><td colspan="2" style="text-align:center">..</td></tr><br />';
foreach (glob($root.$path.'/*') as $file) {
$file = realpath($file);
$link = substr($file, strlen($root) + 1);
if (is_dir($file)){
echo '<tr><td style="text-align:center; vertical-align:middle"><i class="material-icons" style="vertical-align:middle">folder</i></td><td style="text-align:center; vertical-align:middle"><span style="vertical-align:middle">'.basename($file).'</span></td></tr><br />';
}
else {
$size = formatSizeUnits(filesize($file));
echo '<tr><td><a href="?file='.urlencode($link).'" download>'.basename($file).'</a></td><td>'.$size.'</td></tr><br />';
}
}
?>
</tbody>
</table>
</div>
</center>
</main>
</div>
</body>
</html>
What i'm doing is changing the value of $root, but the result is not what i expected, instead of allow me to browse the contents it stays in root directory even if i click another folder. In some of the tests i've done (with different paths and permissions) sometimes it didn't even show anything.
Can anybody tell me why is this happening AND how to solve this?
(Please don't answer with just a solution, i'd like to know what's is what I missunderstood and learn)
I think the issue lies within retrieving the $root path. Your whole script is based on working with absolute paths, therefore I've changed the $root path to also get its absolute path and voilĂ  it worked.
Make sure that argument given to dirname does exist, as it looks like it's not intended to be just the string "path". More at php.net
$root = realpath(dirname("path"));
By the way:
While testing your script I found an issue regarding downloading files. When clicking a file it allows me to download it, but the downloaded file contains the HTML code of your script up to the point where the file is being sent. So make sure to move your code to the beginning of the file in order to fix it.
if (is_file($root.$path)) {
readfile($root.$path);
return;
}
Edit:
I found another issue regarding the function is_in_dir, it's not capable of working with relative paths when the root directory is not the exact same as the scripts directory. To let it work the function needs to look for the specified $file within the root directory $directory like the following:
function is_in_dir($file, $directory, $recursive = true, $limit = 1000) {
$directory = realpath($directory);
// new:
$parent = realpath($directory . DIRECTORY_SEPARATOR . $file);
$i = 0;

PHP session_start() usage

When I use session_start() in my code i have the session setup properly and when I run the code and log in it keeps me logged in and everything works properly, but when I add HTML underneath the PHP code located at the top of the page and refresh it (while logged in) it logged me out?
My Code Without HTML
Core file
ob_start();
session_start();
function loggedin() {
if(isset($_SESSION['user_id'])&&!empty($_SESSION['user_id'])) {
return true;
} else {
return false;
}
}
require 'connect.inc.php';
require 'core.php';
include 'main_login.inc.php';
if (loggedin()) {
$dir = $user_name;
if($handle = #opendir($dir)) {
if($handle2 = #opendir($dir.'/docs')){
//If Logged In And Users File Exists: Load Page
}
} else {
// If Users File Does Not Exist: Create User File
#mkdir($user_name, 0755, true);
// Create Docs
#mkdir($user_name.'/docs', 0755, true);
}
} else {
// If User Is Not Logged: Redirect To Jamie Co Home
#header('Location: http://www.jamieco.ca');
}
?>
My code with HTML (Non-working code)
<?php
require_once 'connect.inc.php';
require_once 'core.php';
include 'main_login.inc.php';
if (loggedin()) {
$dir = $user_name;
if($handle = #opendir($dir)) {
if($handle2 = #opendir($dir.'/docs')){
//If Logged In And Users File Exists: Load Page
}
} else {
// If Users File Does Not Exist: Create User File
#mkdir($user_name, 0755, true);
// Create Docs
#mkdir($user_name.'/docs', 0755, true);
}
} else {
// If User Is Not Logged: Redirect To Jamie Co Home
#header('Location: #');
}
?>
<!DOCTYPE html>
<html>
<body>
<header>
<nav>
<ul>
<li>Home</li>
<li>Clients</li>
<li>Sign In</li>
<li>Contact</li>
</ul>
</nav>
</header>
<div id = "clear" />
<div id = "big_wrapper">
<div id = "wrapper">
<br><br>
<!-- Logged In Stuff Goes Here -->
<div id = "user_options">
<ul>
<li><?php echo 'Welcome, '.$first_name.' '.$last_name.'<br><br>'; ?></li>
<li>Logout</li>
</ul>
</div>
<?php echo 'Welcome Back '.$first_name; ?>
<br><br>
<table border = "1" cellspacing = "5" id = "files">
<tr><td colspan = "7">File Handling</td></tr>
<tr>
<td>File Name:</td>
<td>File Size:</td>
<td>File Type:</td>
<td>Security Level:</td>
<td colspan = "3">Actions:</td>
</tr>
<?php
$dir = $user_name.'/docs/';
if($handle = #opendir($dir)) {
while($file = #readdir($handle)) {
if($file!='.'&&$file!='..') {
echo '<tr><td>'.$file.'</td>';
$name = $dir.$file;
$size = filesize($dir.$file);
$type = substr($name, strrpos($name, '.')+1);
echo '<td>'.$size.' Bytes'.'</td>';
echo '<td>'.$type.'</td>';
echo '<td>'.$file_grade.'</td>';
echo '<td>'.'Download'.'</td>';
echo '<td>'.'Rename'.'</td>';
echo '<td>'.'Delete'.'</td>';
}
}
}
?>
</tr>
</table>
<br><br>
<!-- Stuff Here -->
<br><br>
</div>
</div>
</body>
</html>
Problem Solved. I changed the session to a token, not sure why this works but it does!

Unable to display file content-php

I am not able to display the content of the text file within the same webpage.The code is below (called display.php file)
<html>
<head>
<link rel="icon" type="image/png" href="logo.png">
<body>
<?php
$selectedfile = #$_POST['file_to_be_displayed'];
$content = file($selectedfile);
$data = implode("<br>",$content);
echo $data;
?>
<?php
$dirname = "<directory to be scanned for files>";
$dir = opendir($dirname);
echo '<form name="displayfile" action="output.php" method="POST">';
echo '<select name="file_to_be_displayed">';
echo '<option value="">Select File</option>';
while(false != ($file = readdir($dir)))
{
if((($file != ".") and ($file != "..") and (($file != "store_show_commands_switches.tcl" and $file != "switches.txt"))and (($file != "store_show_commands_routers.tcl" and $file != "routers.txt"))and (($file != "store_show_commands_firewalls.tcl" and $file != "firewalls.txt"))))
{
echo "<option value=".$file.">$file</option>";
}
}
echo '</select>';
echo '<input type="submit" value="display content of file" />';
echo '</form>';
?>
</body>
</html>
output.php
<html>
<body>
<?php
$myFile =$_POST['file_to_be_displayed'];
$file = file_get_contents ("$myFile");
Echo $file;
?>
</body>
</html>
The display.php will scan the txt files within the directory and display them within a dropdown menu with a button next to it to display file selected. However, once I click the button I get a blank page with no result(it should display the content of the txt file)
Is there a way to fix this or -even better- is there a way to display the content of the file within the same display.php (I think it can be done with ajax but not sure how)
Thanks
Pantelis

AJAX is not working on the first click, needs to be clicked twice

update :
The problem now is after using firebug I found out that the first element gets the title attribute and other elements don't and after hovering on any link the title attribute of the first link disappears any ideas?
I have a which page opens when I click on a link like this:
<a class="pictures" href="#" onClick="MM_openBrWindow('content_image.php','images','menubar=yes,scrollbars=yes,resizable=yes,width=650,height=700')" title="Images"></a>
This page has images stored in a folder:
$open = opendir($path);
while($images = readdir($open)){
if ($images != "." && $images != "..") {
$allimages[] = $images;
}
}
foreach($allimages as $val){
?>
<div class="uploaded_image"><img src="../content_img/<?php echo $val; ?>" align='middle' width='150px' height='100px'>
<form><img src="images/delete.gif"/> <textarea name='text_area' rows=1 cols=20 >../content_img/<?php echo $val; ?></textarea> <input type='button' value='select path' onClick='javascript:this.form.text_area.focus();this.form.text_area.select();'> Copy path and paste in image path field </form></div>
<?php
}
closedir($open);
?>
I am trying to delete images using a regular link with href to the page with the following attributes:
?do=delete&img=<?php echo $val; ?>
and then unlink() the image. However, the image is deleted as soon as I hover on the link without clicking. I don't know why.
I tried to do it using AJAX:
$(document).ready(function(e) {
$("div.uploaded_image").on("click","a.del_img",function(e){
e.preventDefault();
var img = $(this).attr("title");
var qst = "?img="+img+"&path=content_img";
var ajax = false;
ajax = new XMLHttpRequest();
ajax.open("post","del_image.php"+qst);
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
}
}
ajax.send(null);
setTimeout(ref,1500);
});
});
function ref(){
window.location = "content_image.php"
}
and this PHP code work uses AJAX to delete:
$img = $_REQUEST['img'];
$path = $_REQUEST['path'];
unlink("../".$path."/".$img);
When I click on the delete link for the first time it doesn't work. I have to click again to delete the image. Any help please?
$open = opendir($path);
while($images = readdir($open)){
if ($images != "." && $images != "..") {
$allimages[] = $images;
}
}
foreach($allimages as $val){
?>
<div class="uploaded_image"><img src="../content_img/<?php echo $val; ?>" align='middle' width='150px' height='100px'>
<form><img src="images/delete.gif"/> <textarea name='text_area' rows=1 cols=20 >../content_img/<?php echo $val; ?></textarea> <input type='button' value='select path' onClick='javascript:this.form.text_area.focus();this.form.text_area.select();'> Copy path and paste in image path field </form></div>
<?php
}
closedir($open);
?>
replace code with this code
change
$("div.uploaded_image").on("click","a.del_img",function(e){
e.preventDefault();
to
$("div.uploaded_image a").click(function(e){
e.preventDefault();
...

PHP File Name and File Size Output

How can i add a file size beside my file names using PHP???
Currently Using This:
<?php
# Configuration
$show_path = 0; # Show local path.
$show_dotdirs = 1; # Show '.' and '..'.
$path = substr($_SERVER['SCRIPT_FILENAME'], 0,
strrpos($_SERVER['SCRIPT_FILENAME'], '/') + 1);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div id="menu">
<div id="menualign"><img src="images/home.png" onmouseover="src='images/homed.png'" onmouseout="src='images/home.png'"/><img src="images/moviesa.png"/><img src="images/tv.png" onmouseover="src='images/tvd.png'" onmouseout="src='images/tv.png'"/></div>
</div>
<div id="container">
<div id="fleft">
<table cellspacing="1">
<tr>
<th><?php if ($show_path == 1) { echo $path; } else { echo 'Current Movies'; } ?></th>
</tr>
<tr>
<td align="left"><?php
$dirs = array();
$files = array();
$dir = dir('../Movies/');
while ($entry = $dir->read()) {
if (($entry != '.') and (substr($entry, -4) != '.php')) {
if (is_dir($entry)) {
if (($entry != '..') or $show_dotdirs){
$dirs[] = $entry;
}
} else {
$files[] = $entry;
}
}
}
$dir->close();
sort($dirs);
foreach ($dirs as $dir) {
printf('<strong><</strong> %s <strong>></strong><br />' . "\n", $dir, $dir);
}
sort($files);
foreach ($files as $file) {
printf('<hr />%s<br />' . "\n", $file, $file);
}
?></td>
</tr>
</table>
</div>
<div id="fright">TEST
</div>
</div>
</body>
</html>
Which outputs as this: http://downunderpctech.com/output.png
I Would like to Add a section for Filesize
Probably using the same code but to collect filesize info as the Filename but in a new beside it
I am not too concerned about the Filesize output, but would prefer only to output KB
Thanks, Adam
You should use the function filesize on your $file variable.
And then you can output a human readable size with this little function:
function file_size($size)
{
$filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 Bytes';
}
You define the function before the # Configuration and then you call it in your foreach:
echo file_size(filesize('../Movies/'.$file));
You can write the file, then use the filesize function to get the file size and rename the file with the size in the file name.
http://php.net/manual/en/function.filesize.php
You can add this to your foreach
echo '<span>'.round(filesize ('../Movies/'.$file)/1024, 1).' Kb</span>';

Categories