My script is not displaying links properly - php

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)

Related

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

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

Pagination for my situation?

I have a pretty complicated script that doesn't fully work with MySQL, it does partially though. Let me try to explain...
The results of my page are purely image names from a specific folder, means I use this function to get my results:
function get_all_images($dir)
{
$dir = opendir($dir);
$dirArray = array();
while($entryName = readdir($dir))
{
if(($entryName != ".") && ($entryName != "..") && ($entryName != ".svn") && ($entryName != ".htaccess"))
{
$dirArray[] = $entryName;
}
}
closedir($dir);
(sizeof($dirArray)) ? arsort($dirArray) : '';
return (is_array($dirArray)) ? $dirArray : '';
}
This is how I basically get results in my page:
<?php
include('includes/header.php');
$images = get_all_images('i');
$url = str_replace('www.', '', generate_site_url());
$flag = false;
$count = 0;
if (empty($images))
{
echo '<h2>There are no uploaded images</h2><br>';
}
foreach ($images as $image)
{
$filename = $image_name = $image;
$image_link = $url . IMAGES_PATH . $filename;
$user_id = fetch_user_id($image_link);
$delete_link = (isset($_POST['delete_link'])) ? $_POST['delete_link'] : '';
$delete_image = (isset($_POST['delete_image'])) ? $_POST['delete_image'] : '';
if ($delete_admin_submit)
{
unlink('./t/' . $delete_image);
unlink('./t/big' . $delete_image);
adminDelete('./i/' . $delete_image, $delete_link);
header('Location: ' . $imgit_action);
exit();
}
echo '<div class="' . ($count++ % 2 ? "odd-color" : "even-color") . '">';
echo '<table>';
echo '<tr><td class="fullwidth"><a class="preview_img" href="' . $image_link . '"><img src="' . $image_link . '" title="Click to enlarge" width="300" class="thumb" /></a></td></tr>';
echo '<tr><td><span class="default">Direct link:</span> ';
echo '<input type="text" readonly="readonly" class="link-area" onmouseover="this.select();" value="' . $image_link . '" />';
echo '<form method="post" action="" onsubmit="return confirmSingleDeletion();" style="display: inline;"> ';
echo '<input type="submit" class="icon_delete" name="delete_link" value="' . $image_link . '" title="Delete this image" />';
echo '<input type="hidden" name="delete_image" value="' . $image_name . '" />';
echo '</form>';
echo '</td></tr>';
echo ($flag) ? '<hr /><br>' : '';
echo '</table>';
if (!empty($user_id))
{
echo '<br><strong class="normal">Uploader ID:</strong> ';
echo '<em class="normal">' . $user_id . '</em><br>';
}
echo '<br>';
$flag = true;
}
?>
<span class="button-sub">« Back to Index</span>
<?php echo '</div>'; ?>
<?php include('includes/footer_alt.php'); ?>
Now I have not ANY simple clue how to start breaking my results into pages. I'm working here with over 12000 results and it takes a lot for the page to load, I need help to break this big result into pages.
Anyone willing to help me? At least give me a clue how to start? I would be really grateful.
Thanks a lot for reading.
Consider your array as you collect up the file names but after you have sorted them:
$imgs = array(
0 => 'image1.jpg',
1 => 'image2.jpg',
2 => 'image3.jpg',
3 => 'image4.jpg',
4 => 'image5.jpg',
5 => 'image6.jpg',
6 => 'image7.jpg',
7 => 'image8.jpg',
);
// create some vars which you can use in your pagination
$perpage = 3 ;
$page=2;
$range_end = ($perpage*$page)-1;
$range_start = ($perpage*($page-1));
$display=range($range_start,$range_end);
// loop through results
foreach($display as $show){
echo $imgs[$show];
}
Does that get you a start?
Thanks for trying to answer me Cups and Umair Khan, but I found the working solution here:
http://tiffanybbrown.com/2008/12/14/simple-pagination-for-arrays-with-php-5/

In PHP is it possible to inspect content of a Zip file without extracting its content first?

I have seen the ZipArchive class in PHP which lets you read zip files. But I'm wondering if there is a way to iterate though its content without extracting the file first
As found as a comment on http://www.php.net/ziparchive:
The following code can be used to get a list of all the file names in
a zip file.
<?php
$za = new ZipArchive();
$za->open('theZip.zip');
for( $i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
print_r( basename( $stat['name'] ) . PHP_EOL );
}
?>
http://www.php.net/manual/en/function.zip-entry-read.php
<?php
$zip = zip_open("test.zip");
if (is_resource($zip))
{
while ($zip_entry = zip_read($zip))
{
echo "<p>";
echo "Name: " . zip_entry_name($zip_entry) . "<br />";
if (zip_entry_open($zip, $zip_entry))
{
echo "File Contents:<br/>";
$contents = zip_entry_read($zip_entry);
echo "$contents<br />";
zip_entry_close($zip_entry);
}
echo "</p>";
}
zip_close($zip);
}
?>
I solved the problem like this.
$zip = new \ZipArchive();
$zip->open(storage_path('app/'.$request->vrfile));
$name = '';
//looped through the zip files and got each index name of the files
//since I only wanted the first name which is the folder name I break the loop
//after updating the variable $name with the index name and that's it
for( $i = 0; $i < $zip->numFiles; $i++ ){
$filename = $zip->getNameIndex($i);
var_dump($filename);
$name = $filename;
if ($i == 1){
break;
}
}
var_dump($name);
Repeated Question. Search before posting.
PHP library that can list contents of zip / rar files
<?php
$rar_file = rar_open('example.rar') or die("Can't open Rar archive");
$entries = rar_list($rar_file);
foreach ($entries as $entry) {
echo 'Filename: ' . $entry->getName() . "\n";
echo 'Packed size: ' . $entry->getPackedSize() . "\n";
echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n";
$entry->extract('/dir/extract/to/');
}
rar_close($rar_file);
?>

php - get full image path from server

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

Categories