php - get full image path from server - php

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>";

Related

PHP - Displaying directory folders in random order

The code works perfectly. Just don't know how to get it to display the content randomly without using Jquery.
Got it to display a random image from the current directory, but not sure how to get the directory to display randomly.
$dir = 'img/series_thumbnail/';
$dh = opendir($dir);
while (($fileName = readdir($dh)) !== false) {
if (!in_array($fileName, array('.', '..'))) {
$images = glob($dir . $fileName . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$imgMax = count($images)-1;
$imgNum = rand(0, $imgMax);
$imgUrl = $images[$imgNum];
echo '<li>';
echo '<img src="' . $imgUrl . '"/>';
echo '<div class="info"><p>' . $fileName . '</p></div>';
echo '</li>';
}
}
Thank you.
EDIT
Figured it out! Thanks for your help everyone.
$dir = glob("img/series_thumbnail/*", GLOB_ONLYDIR);
shuffle($dir);
foreach ($dir as $folder) {
if (!in_array($folder, array(".", ".."))) {
$folderName = basename($folder).PHP_EOL;
$images = glob($folder . "/*.{jpg,jpeg,png,gif}", GLOB_BRACE);
shuffle($images);
echo "<li>";
echo '<img src="' . $images[0] . '"/>';
echo "<div class='info'><p>" . $folderName . "</p></div>";
echo "</li>";
}
}
If you want to display a single random image from each directory, with the directories in random order, you can use this code:
$dir = 'img/series_thumbnail/';
$directories = glob("$dir*", GLOB_ONLYDIR);
shuffle($directories);
foreach ($directories as $directory) {
$images = glob($dir . $directory. '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$imgMax = count($images)-1;
$imgNum = rand(0, $imgMax);
$imgUrl = $images[$imgNum];
echo '<li>';
echo '<img src="' . $imgUrl . '"/>';
echo '<div class="info"><p>' . $fileName . '</p></div>';
echo '</li>';
}

Download link over random php image

I am displaying a number of random images from a folder, however I'm not very good with PHP (Code sourced from the internet), how would I go about having a "download" link display on top of the image?
Display random image from folder using PHP:
function random_image($directory)
{
$leading = substr($directory, 0, 1);
$trailing = substr($directory, -1, 1);
if($leading == '/')
{
$directory = substr($directory, 1);
}
if($trailing != '/')
{
$directory = $directory . '/';
}
if(empty($directory) or !is_dir($directory))
{
die('Directory: ' . $directory . ' not found.');
}
$files = scandir($directory, 1);
$make_array = array();
foreach($files AS $id => $file)
{
$info = pathinfo($dir . $file);
$image_extensions = array('jpg', 'jpeg', 'gif', 'png', 'ico');
if(!in_array($info['extension'], $image_extensions))
{
unset($file);
}
else
{
$file = str_replace(' ', '%20', $file);
$temp = array($id => $file);
array_push($make_array, $temp);
}
}
if(sizeof($make_array) == 0)
{
die('No images in ' . $directory . ' Directory');
}
$total = count($make_array) - 1;
$random_image = rand(0, $total);
return $directory . $make_array[$random_image][$random_image];
}
Markup:
echo "<img src=" . random_image('css/images/avatars') . " />";
I've tried looking around google for an answer but I can't find anything, any help would be appreciated
You should save the image location in a variable then use it to create a link, plus display it.
$imageUrl = random_image('css/images/avatars');
echo "<a href=" . $imageUrl . ">";
echo "<img src=" . $imageUrl . " />";
echo "</a>";
or if you want to show the text link above, seperately then
$imageUrl = random_image('css/images/avatars');
echo "Click Here<br />";
echo "<img src=" . $imageUrl . " />";
you could use simple javascript to do so, like onclick event for example :
just add this to img tag onclick='window.open('". random_image('css/images/avatars') ."')'
echo "<img onclick='window.open('". random_image('css/images/avatars') ."')' src='" . random_image('css/images/avatars') . "' />";

Adding functions into an Array in php

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']);
}

How can I get the contents of a file one line at a time?

I have a project where a user uploads a photo with a name and caption, and I am having trouble with displaying the name and caption.
Right now, it's displaying the entire text file with each image, and I am having trouble fixing this.
My code so far:
<?php
$Dir = "files";
$DirEntries = scandir($Dir);
foreach ($DirEntries as $Entry)
{
if((strcmp($Entry, '.') != 0) && (strcmp($Entry, '..') != 0))
{
echo "<p>Name: " . file_get_contents("imagelist.txt") . "</p>";
echo "<a href=\"files/" . $Entry . "\" target=\"_blank\" >" . $Entry . "</a><br />\n";
}
}
closedir($DirOpen);
?>
Any help would be greatly appreciated.
You can use fgets():
$inputFile = fopen("file.txt", "r");
if ($inputFile) {
while (($line = fgets($inputFile)) !== false) {
echo $line."<br>";
// The process read the file line by line
}
} else {
echo "There was an error in the opening file";
}
fclose($inputFile);

My script is not displaying links properly

It's gonna be hard for me to explain the whole situation, but I'll try...
I made a script for my image host that unZips a Zip package with images in it to a certain location, renames the files to a random file name and outputs multiple links to the images. The last part is not working properly! I am unable to output multiple links to the images - It simply outputs one link to the image (the first one) and the rest is in the uploaded folder, but not listed as a link.
Same goes with generating a thumbnail for the just renamed images. Only one thumbnail is generated for the first image, and the rest of the images if being ignored.
This is how my code looks like:
<?php
session_start();
include('includes/imgit.class.php');
$IMGit = new imgit();
/**
* #ignore
*/
if (!defined('IN_IMGIT'))
{
exit;
}
$IMGit->error_report(true);
$IMGit->disable(false);
$IMGit->ieNote(true);
if (isset($_POST['zipsent']) || $_POST['zipsent'] == true && isset($_FILES['archive']))
{
if ($_FILES['archive']['size'] <= MAX_ZIPSIZE)
{
// Main variables
$key = $IMGit->random_key(10);
$move_zip = move_uploaded_file($_FILES['archive']['tmp_name'], ZIP_PATH . $key . $_FILES['archive']['name']);
$zip = ZIP_PATH . $key . $_FILES['archive']['name'];
$extension = substr($zip, -3);
$filename = $IMGit->zipContent($zip); // array
$url = str_replace('www.', '', $IMGit->generate_site_url());
// ZIP limit is 100 images
if (sizeof($filename) <= 100)
{
// Only ZIP archives
if ($extension == 'zip')
{
if ($filename)
{
foreach($filename as $key => $value)
{
// Get extension
$image_extension = substr($value, -3);
$image_extension = (strtoupper($image_extension)) ? strtolower($image_extension) : $image_extension;
$image_extRule = $image_extension == JPG || $image_extension == JPEG || $image_extension == GIF || $image_extension == PNG ||
$image_extension == BMP || $image_extension == ICO;
if ($image_extRule)
{
// Set variables and do some processing
$unZip = $IMGit->unZip($zip, IMAGES_PATH);
$url = str_replace('www.', '', $IMGit->generate_site_url());
$image_name = $IMGit->random_key(7) . $value;
$image_name = (strpos($image_name, ' ') !== false) ? str_replace(' ', '', $image_name) : $image_name;
if (file_exists(IMAGES_PATH . $filename[$key]))
{
// Rename extracted files
$rename = rename(IMAGES_PATH . $filename[$key], IMAGES_PATH . $image_name);
if ($rename && file_exists($zip) && sizeof($image_name))
{
// Delete ZIP
unlink($zip);
// Set URL variables
$image_urls = $url . IMAGES_PATH . $image_name;
$image = IMAGES_PATH . $image_name;
// Generate a thumbnail
$IMGit->generate_thumbnail($image_urls, $image_name, THUMBNAIL_SIZE, THUMBNAIL_SIZE, true, 'file', false, false, THUMBS_PATH);
$thumb_urls = $url . THUMBS_PATH . $image_name;
$filename[] = array('direct' => $image_urls, 'thumb' => $thumb_urls);
}
}
}
}
}
}
}
}
}
else
{
header('Location: index.php');
}
include('includes/header.php');
{
if ($_FILES['archive']['size'] > MAX_ZIPSIZE) { echo '<span id="home-info">The ZIP archive is bigger than 100 MB.</span>'; }
else if ($extension != 'zip') { echo '<span id="home-info">Only ZIP archives are upload ready.</span>'; }
else if (sizeof($filename) > 100) { echo '<span id="home-info">The number of the images inside the archive was more than 100.</span>'; }
else if (!$image_extRule) { echo '<span id="home-info">The extensions inside the ZIP did not match our allowed extension list.</span>'; unlink($zip); } // unlink zip if failed
else { echo '<span id="home-info">Image(s) was/were successfully uploaded!</span>'; }
}
?>
</div>
<br /><br /><br />
<img src="css/images/site-logo.jpg" id="logo" />
<br /><br /><br /><br /><br />
</div>
<div id="box">
<?php
global $filename, $image_urls, $thumb_urls;
echo '<br />';
echo '<div id="links">';
echo '<table>';
echo LINKS_DIRECT;
for($i = 0; $i < sizeof($filename); $i++) { echo $filename[$i]['direct'] . "\n"; }
echo LINKS_CLOSE;
echo LINKS_THUMB;
for($i = 0; $i < sizeof($filename); $i++) { echo $filename[$i]['thumb'] . "\n"; }
echo LINKS_CLOSE;
echo LINKS_BBCODE;
for($i = 0; $i < sizeof($filename); $i++) { echo '[IMG]' . $filename[$i]['direct'] . '[/IMG]' . "\n"; }
echo LINKS_CLOSE;
echo LINKS_HTML;
for($i = 0; $i < sizeof($filename); $i++) { echo '<img src="' . $filename[$i]['thumb'] . '" />' . "\n"; }
echo LINKS_CLOSE;
echo '</table>';
echo '<br />';
echo '<input type="reset" id="resetbtn-remote" class="button-sub" value="« Upload more" />';
echo '<br />';
echo '</div>';
?>
</div>
<?php include('includes/footer.php'); ?>
</div>
</body>
</html>
I guess the problem is inside the foreach loop (it was a for loop a few days ago, but faced the same problems), but I can't seem to fix it. I'll reexplain in a short version:
I upload a Zip archive
Script unZips the archive
Script renames the extracted files
Thumbnail must be generated for all images that were in the Zip (fails)
Multiple links should be outputted matching every image the was in the Zip (fails)
Ideas?
You are re-using a variable ($filename) for two different purposes. At the top, add a line like this:
$file_list = array();
Later in the code, where you do this:
$filename[] = array('direct' => $image_urls, 'thumb' => $thumb_urls);
... change it to this:
$file_list[] = array('direct' => $image_urls, 'thumb' => $thumb_urls);
Later in your code where you loop, use foreach instead:
echo LINKS_DIRECT;
foreach ($file_list as $this_file)
echo $this_file['direct'] . "\n";
echo LINKS_CLOSE;
echo LINKS_THUMB;
foreach ($file_list as $this_file)
echo $this_file['thumb'] . "\n";
echo LINKS_CLOSE;
echo LINKS_BBCODE;
foreach ($file_list as $this_file)
echo '[IMG]' . $this_file['direct'] . '[/IMG]' . "\n";
echo LINKS_CLOSE;
echo LINKS_HTML;
foreach ($file_list as $this_file)
echo '<img src="' . $this_file['thumb'] . '" />' . "\n";
echo LINKS_CLOSE;
You've got a lot of other odd things going on in there, like using constants for HTML fragments. I think you should take another look at your process there and eliminate some of the unnecessary steps and variables. I see several global keywords used... none appear to be necessary.
I fixed this problem just by removing the following code part:
file_exists($zip)

Categories