Download link over random php image - php

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') . "' />";

Related

Search for pdf files

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
}
}
}

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

Creating XML code using image source from SlideshowPro Album using PHP

I used the code from this website http://wiki.slideshowpro.net/PlayerWithoutDirector/PWDSCRIPTS-PHPXMLBuilderScript with a copy of the code below called images.php with audio but I don't really need audio. This PHP script just retrieves the image source of photos in a directory of a folder to an XML file. Instead, I'd like to write an XML file that would get the image source directly from a SlideshowPro Album. The first code below lists the images from an album directly from SlideShowPro. How do I combine the two scripts?
// gallery.php
<?php
include('classes/DirectorPHP.php');
$director = new Director('api', 'key');
$album = $director->album->get(440);
echo $album->name . '<br /><br />';
// Loop through album content
$contents = $album->contents[0];
foreach($contents as $content) {
echo $content->src . '<br />';
}
?>
// images.php
<?php
/**************************************************************************
XML Generator for SlideShowPro
Brad Daily - slideshowpro.net
For instructions, see the wiki:
http://wiki.slideshowpro.net/SSPExtras/PhpXmlBuilder
This script is governed by the following license:
http://creativecommons.org/licenses/by-nc-sa/3.0/us/
**************************************************************************/
/*
CONFIGURATION
*/
// Name of the folder in each album's folder that contains the full size imagery
$large_folder = 'lg';
// Name of the folder in each album's folder that contains the thumbnails
$thumb_folder = 'tn';
// Name of your album preview image. placed at the root of each album's folder (optional)
$album_preview_name = 'albumPreview.jpg';
/* Audio addition
$audio_folder = 'audio';
*/
/*
END CONFIGURATION
(DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING)
*/
// Set up paths
define('DS', DIRECTORY_SEPARATOR);
$dir = dirname(__FILE__);
$server = 'http://' . $_SERVER['HTTP_HOST'];
$rel_path = str_replace('images.php', '', $_SERVER['PHP_SELF']);
$path = $server . $rel_path;
$iptc = is_callable('iptcparse');
/*$width = "thumbnailWidth=auto thumbnailHeight=78"; */
// Find all folders in this directory
$albums = array();
$d = dir($dir);
while (false !== ($folder = $d->read())) {
if ($folder != '.' && $folder != '..' && is_dir($dir . DS . $folder . DS . $large_folder))
{
$albums[] = $folder;
}
}
$d->close();
// Start writing XML
$o = '<?xml version="1.0" encoding="utf-8"?>' . "\n<galleries>\n";
// Cycle through albums
foreach($albums as $album) {
// Path variables
$loc_path = $path . $album . '/';
$full_path = $dir . DS . $album;
// Find images in the large folder
$images = array();
$d2 = dir($full_path . DS . $large_folder);
while (false !== ($image = $d2->read())) {
if (eregi('.jpg|.gif|.png|.swf|.flv|.mov', $image)) {
$images[] = $image;
}
}
$d2->close();
/* Audio addition
// Find audios in the audio folder
$audios = array();
$d2 = dir($full_path . DS . $audio_folder);
while (false !== ($audio = $d2->read())) {
if (eregi('.mp3|.ra|.wav', $audio)) {
$audios[] = $audio;
}
}
$d2->close();
Audio addition */
// Only write the album to XML if there are images
if (!empty($images)) {
natcasesort($images);
// Pretty up the title
$title = ucwords(preg_replace('/_|-/', ' ', $album));
// See if there is an album thumb present, if so add it in
if (file_exists($full_path . DS . $album_preview_name)) {
$atn = ' tn="' . $loc_path . $album_preview_name . '"';
} else {
$atn = '';
}
// Only write tnPath if that folder exists
if (is_dir($full_path . DS . $thumb_folder)) {
$tn = ' tnPath="' . $loc_path . $thumb_folder . '/"';
}
/* Audio addition
$audio = '';
if (0 < count($audios)) {
$audio = sprintf(' audio="%s" audioCaption="%s"',
$loc_path . $audio_folder . '/' . $audios[0],
substr(ucwords(preg_replace('/_|-/', ' ', $audios[0])), 0, -4));
}
Audio addition */
// Album tag
$o .= "\t" . '<imagegroup title="' . $title . '" thumbnailPath="' . $loc_path .
$large_folder . '/"' . $width . $atn . $audio . '>' . "\n";
// Cycle through images, adding tag for each to XML
foreach($images as $i) {
$link = $caption = '';
$title = '';
if ($iptc) {
$file = $full_path . DS . $large_folder . DS . $i;
$path_info = pathinfo($file);
$extensions = array('jpg', 'jpeg', 'gif', 'png');
if (in_array(strtolower($path_info['extension']), $extensions)) {
getimagesize($file, $info);
if (!empty($info['APP13'])) {
$iptc = iptcparse($info['APP13']);
if (isset($iptc['2#005'])) {
$title = $iptc['2#005'];
if (is_array($title)) {
$title = htmlentities($title[0], ENT_COMPAT);
}
}
if (isset($iptc['2#120'])) {
$caption = $iptc['2#120'];
if (is_array($caption)) {
$caption = htmlentities($caption[0], ENT_COMPAT);
}
}
}
}
}
if (isset($_GET['link'])) { $link = $loc_path . $large_folder . '/' . $i; }
$o .= "\t\t" . '<img src="' . $i . '" title="' . $title . '" />' . "\n";
}
// Close the album tag
$o .= "\t</imagegroup>\n";
}
}
// Close gallery tag, set header and output XML
$o .= "</galleries>";
header('Content-type: text/xml');
die($o);
I'd like my result to appear like this:
<galleries>
<imagegroup title="2013 In Review" thumbnailPath="2013Review/thumb.jpg" thumbnailWidth="auto" thumbnailHeight="78">
<img src="2013Review/JLP09509_01_026.jpg" title="Paul Walker by Jeff Lipsky"/>
<img src="2013Review/NAB10003_01_001.jpg" title="Nelson Mandela by Nabil"/>
<img src="2013Review/MMU13110_41_001.jpg" title="Lindsey Vonn by Michael Muller"/>
</imagegroup>
<imagegroup title="Awards Season" thumbnailPath="AwardSeason/thumb.jpg" thumbnailWidth="56" thumbnailHeight="78">
<img src="AwardSeason/GBE07090_04_007.jpg" title="Tom Hanks by Giuliano Bekor - "Captain Phillips""/>
<img src="AwardSeason/DTI12009_02_001.jpg" title="Amy Adams by Darren Tieste - "American Hustle" "/>
<img src="AwardSeason/NPA11013_01_005.jpg" title="Idris Elba by Nigel Parry - "Mandela-Long Walk to Freedom" "/>
</imagegroup>
</galleries>

How to count files inside a folder using PHP?

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( '.', '..' );

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