Getting all files from a folder and opening them onclick - php

I am reading a folder with glob() function in php
foreach (glob("folder/*.*") as $filename) {
echo $filename."<br />"
}
My folder contains three kind of files pdf, image, videos. What I need here is to make a link for each file and open them on click.
How can I achieve this, any ideas?

This should work for you:
(This creates you a list of all files which you can click on it and you get it opened in the new tab)
$files = glob("folder/*.*");
foreach($files as $file)
echo "<a href='" . $file . "' target='_blank'>" . $file . "</a><br />";

Related

PHP: File cannot be downloaded ("404 Not Found" message)

I am working on a website of a client for which I didn't write the code. I have troubles making files downloadable.
It is about a subdomain where users can download course files.
The website files are contained in the folder "courses" (on the root level).
The file for displaying the downloadable course files is contained in
"courses/displayfiles.php".
The downloadable files are contained in a folder in "courses/downloadfolder". Inside this folder, each user has his own
files folder which as its name has the user id.
displayfiles.php: The following code successfully displays all files that can be downloaded by the logged-in user:
$path = "downloadfolder/" . $_SESSION['userId'] . "/";
$files = array();
$output = #opendir($path) or die("$path could not be found");
while ($file = readdir($output)) {
if (($file != "..") and ($file != ".")) {
array_push($files, $file);
}
}
closedir($output);
sort($files);
foreach ($files as $file) {
echo '<a class="imtext" href="downloadfolder/' . $_SESSION['userId'] . '/' . $file . '/">' . $file . '</a><br/>';
}
So what does not work about this code: When a user clicks on a file, I get a "404 Not Found" message that the file was not found. How can this be?
Why does displaying the files totally works fine, but at the same time I get a 404 error when clicking a file? The files path ($path) must be correct, or not? What further investigations do I need to take in order to solve this problem?
* UPDATE *
I decided to modify the files loop as followed (changing the href):
foreach ($files as $file) {
echo '<a class="imtext" href="http://'.$_SERVER['HTTP_HOST']. '/downloadfolder/' . $_SESSION['courseId'] . '/' . $file . '/">' . $file . '</a><br/>';
}
Still, when I click on a file, I get a 404 Not Found error. How can this be?
You have to look where the webroot of your page is, where the php file generating the list is located and wherer the files are.
Your generated link is relative to the php file generating the link, which might not be corresponding to the URL in the browser. I'd try to make this link relative to the webroot (note the leading slash!)
echo '<a class="imtext" href="/courses/downloadfolder/' . $_SESSION['userId'] . '/' . $file . '/">' . $file . '</a><br/>';
If that guessed solution doesn't work please provide the current URL of the page where this links are generated and one generated link, so we can help you better.

rename images and move the renamed images in newly created directory

Here i want to create a new directory called c:/xampp/htdocs/haha/tour/ and in the directory i want to move my renamed images .Here ,i managed to create the new directory but can't move and rename my images.How can i solve this problem??
$dir='c:/xampp/htdocs/practice/haha';
$i=1;
if(is_dir($dir)){
echo dirname($dir).'</br>';
$file=opendir($dir);
while(($data=readdir($file))!==false){
if($data!='.' && $data!='..'){
$info=pathinfo($data,PATHINFO_EXTENSION);
if(!file_exists($dir.'/tour')){
mkdir($dir.'/tour/');
}
rename($dir.$data,$dir.'/tour/'.'image '.$i.'.jpg');
$i++;
}
}
}
You're missing some /:
rename($dir.$data,$dir.'/tour/'.'image '.$i.'.jpg');
^---
$data doesn't contain ANY /, so what you're building is
rename('c:/xampp/htdocs/practice/haha' . 'foo', etc...)
which becomes
rename('c:/xampp/htdocs/practice/hahafoo', etc...)
^^^^^^^---doesn't exist
Try
rename($dir .'/' . $data,$dir.'/tour/'.'image '.$i.'.jpg');
^^^^^^^^
instead.
This should work for you:
Here I just get all images from your directory with glob(). I create the directory if it doesn't exist already with mkdir() and then move all images
with rename().
<?php
$dir = "c:/xampp/htdocs/practice/haha";
$files = glob($dir . "/*.{jpg,png,gif,jepg}", GLOB_BRACE);
//Create directory
if (!file_exists($dir . "/tour")) {
mkdir($dir . "/tour");
}
//Move all images
foreach($files as $key => $file) {
rename($dir . "/" .$data, $dir . "/tour/image" . ($key+1) . ".jpg");
}
?>

PHP: showing content of a folder with icons

I'm using PHP/MySQL.
I have a folder called "docs" with PDF files.
I'd like to know if there exist an easy way, using only PHP, to show the content of the folder with a custom icon.
I mean, something like this:
[icon] File01.pdf
[icon] File02.pdf
[icon] File03.pdf
In order to allow visitors read or download the files.
Many thanks in advance
With glob() you can get the path to all pdf files and then loop through them with a foreach loop.
foreach(glob('*.pdf') as $file) {
echo '<img src="myicon.png"> ' . $file;
}
You can use pathinfo to get the file extention and show and png with the extention
$fileExt = pathinfo($filename, PATHINFO_EXTENSION);
echo '<img src="path-to-icons/"' . strtolower($fileExt) . '.png" />' . $filename . ''
This was the final solution:
<?php
foreach(glob('docs/*.pdf') as $file) {
echo '' . substr($file, 5, -4) . '</br>';
}
?>
I have used #Karl's and Martin's answers to get the result I was looking for, but all answers were really useful.
Many thanks to all

Delete an image after it has been seen by a visitor

I want to show my visitors the images in a folder and after then have seen it, I want all those files deleted!
This is what I tried, but It won't work. I think it's because PHP is generating a html file which tells the browser it must first get an image from a different place but the html file was already removed.
<?php
foreach (glob("files/*.*") as $prevpic) {
echo '<img src="' . $prevpic . '" />';
}
foreach (glob("files/*.*") as $file) {
unlink($file);
}
move_uploaded_file($_FILES["file"]["tmp_name"], "files/" . $_FILES["file"]["name"]);
?>
You can do something like so ...
<?php
foreach (glob("files/*.*") as $file) {
echo '<img src="data:image/' . pathinfo($file, PATHINFO_EXTENSION) . ';base64,' . base64_encode(file_get_contents($file)) . '" />';
unlink($file);
}
?>
... which is basically writing the image data into the html, and then discarding the image.
I would handle this by simply managing your images through a download script (php).
You track sessions and simply don't display the images requested, but fail gracefully with a response, or let your app handle it via session based tracking.
That way no images are deleted 'onview'.

path to image folder on server

i have a wordpress inside Public html folder on server.
i want to dispaly images from the folder Public_html--->Trial-->Wordpress_site-->uploads
below is page.php code
<?php
$directory = dirname(__FILE__).'/uploads';
echo $directory;
try {
// Styling for images
foreach ( new DirectoryIterator("/" . $directory) as $item ) {
if ($item->isFile()) {
echo "<div class=\"expand_image\">";
$path = "/" . $directory . "/" . $item;
echo $path;
echo "<img src=/"". $path . "\" width=861 height=443 />";
echo "</div>";
}
}
}
catch(Exception $e) {
echo 'No images found for this player.<br />';
}
?>
The images arent getting displayed..
anyone knows about the same??
edit1
I think there is problem in this sentence
echo "<img src=/"". $path . "\" width=861 height=443 />";
is it?
edit2
//home/softwar2/public_html/Pradnnya_blog/wordpress_site/wp-content/themes/deep-red/our_results/4thpanelfinal.jpg
is the path that i get when echoed.
__FILE__ gives you the path of the current file on the filesystem; however, when you visit the webpage and you see a link in the tag, you'll try to access that as a URL instead of a file. For this, you might find $_SERVER['PHP_SELF'] useful, or another one of the $_SERVER elements. It might be better to have the URL in a configuration file though, because $_SERVER may sometimes not be set.
Good catch, there's a bit of a syntax error:
echo "<img src=\"". $path . "\" width=861 height=443 />";
You'll want to use the backslash to escape the double quote.

Categories