I found a useful php code which displays the photos in a folder directory as a image preview. The issue is my host provider blocks one of the script commands, "Shell_exec()", so the php code doesn't work.
Any way of getting the code to run without using shell_exec?
<?PHP
// filetypes to display
$imagetypes = array("image/jpeg", "image/gif");
?>
<?PHP
function getImages($dir)
{
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getImages: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
break;
}
}
}
$d->close();
return $retval;
}
?>
<?PHP
// fetch image details
$images = getImages("images");
// display on page
foreach($images as $img) {
echo "<div class=\"photo\">";
echo "<img src=\"{$img['file']}\" {$img['size'][3]} alt=\"\"><br>\n";
// display image file name as link
echo "",basename($img['file']),"<br>\n";
// display image dimenstions
echo "({$img['size'][0]} x {$img['size'][1]} pixels)<br>\n";
// display mime_type
echo $img['size']['mime'];
echo "</div>\n";
}
?>
You can get the mime type of a file using the PHP function mime_content_type(). This way you can get rid of the shell_execute used to detect the mime type in your code.
Related
I am trying to copy an entire folder from one location to another using PHP, but it doesn't seem to work:
$username = "peter" //this is just an example.
$userdir = "../Users/".$username."/";
mkdir($userdir);// create folder
// copy image folder
$source = "templates/template1/images/";//copy image folder -source
$dest = $userdir;
function copyr($source, $dest){
// Simple copy for a file
if (is_file($source)) {
$c = copy($source, $dest);
chmod($dest, 0777);
return $c;
}
// Make destination directory
if (!is_dir($dest)) {
$oldumask = umask(0);
mkdir($dest, 0777);
umask($oldumask);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == "." || $entry == "..") {
continue;
}
}
// Clean up
$dir->close();
return true;
}
I have also tried other solutions I saw online without success. Would appreciate any help possible
I also just tried this script without any luck.
I just tried another script and still no luck :(.
$template_homepage = "templates/template1/index.php";//path to default template homepage
$homepage = file_get_contents($template_homepage);//get default homepage structure
$username = testuser;// folder name for store
if (trim($username) == '') {
die("An error occured.");
} else {
$userdir = "../Users/".$username."/";
mkdir($userdir);// create folder for new website
// copy image folder
$src = 'templates/template1/images';//copy image folder -source
$dst = $userdir;
function rcopy($src, $dst) {
if (file_exists($dst)) rrmdir($dst);
if (is_dir($src)) {
mkdir($dst);
$files = scandir($src);
foreach ($files as $file)
if ($file != "." && $file != "..") rcopy("$src/$file", "$dst/$file");
}
else if (file_exists($src)) copy($src, $dst);
}
$fh = fopen($userdir."index.php", 'w') or die("An error occured. ");// create home page in users folder
// $stringData = $title; //."\n";//
fwrite($fh, $homepage);// write homepage structure into new homepage file.
fclose($fh);// close new homepage file.
$launchpage = "../Users/".$username."/"; // launch new homepage file.
header("Location: $launchpage");
}
Why don't you use exec and use the OS command to copy the folder over?
exec('cp -r sourcedir destdir');
I need to read only pdf files in a directory and then read the filename of every files then I will use the filename to rename some txt files. I have tried using only eregi function. but it seems cannot read all I need. how to read them well?
here's my code :
$savePath ='D:/dir/';
$dir = opendir($savePath);
$filename = array();
while ($filename = readdir($dir)) {
if (eregi("\.pdf",$filename)){
$read = strtok ($filename,"."); //get the filenames
//to rename some txt files using the filenames that I get before
//$testfile is text files that I've read before
$testfile = "$read.txt";
$file = fopen($testfile,"r") or die ('cannot open file');
if (filesize($testfile)==0){}
else{
$text = fread($file,55024);
fclose($file);
echo "</br>"; echo "</br>";
}
}
More elegant:
foreach (glob("D:/dir/*.pdf") as $filename) {
// do something with $filename
}
To get the filename only:
foreach (glob("D:/dir/*.pdf") as $filename) {
$filename = basename($filename);
// do something with $filename
}
You can do this by filter file type.. following is sample code.
<?php
// directory path can be either absolute or relative
$dirPath = '.';
// open the specified directory and check if it's opened successfully
if ($handle = opendir($dirPath)) {
// keep reading the directory entries 'til the end
$i=0;
while (false !== ($file = readdir($handle))) {
$i++;
// just skip the reference to current and parent directory
if (eregi("\.jpg",$file) || eregi("\.gif",$file) || eregi("\.png",$file)){
if (is_dir("$dirPath/$file")) {
// found a directory, do something with it?
echo " [$file]<br>";
} else {
// found an ordinary file
echo $i."- $file<br>";
}
}
}
// ALWAYS remember to close what you opened
closedir($handle);
}
?>
Above is demonstrating for file type related to images you can do the same for .PDF files.
Better explained here
I'm trying to improve the administrator panel of my website. I need to preview the images in the thumbnails folder so that when i'm using thumbnails for news I dont have to upload the image for the second time. I found a great script, but I get failed to read the directory error. Here is the script:
<?php
// filetypes to display
$imagetypes = array("image/jpeg", "image/gif", "image/png");
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function getImages($dir)
{
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getImages: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
break;
}
}
}
$d->close();
return $retval;
}
// fetch image details
$images = getImages("../images/thumbnails");
// display on page
foreach($images as $img) {
echo "<div class=\"photo\">";
echo "<img src=\"{$img['file']}\" {$img['size'][3]} alt=\"\"><br>\n";
// display image file name as link
echo "",basename($img['file']),"<br>\n";
// display image dimenstions
echo "({$img['size'][0]} x {$img['size'][1]} pixels)<br>\n";
// display mime_type
echo $img['size']['mime'];
echo "</div>\n";
}
?>
I really appreciate if someone could help..
EDIT:
<div style=" height: 200px; width: 600px; overflow: auto;">
<?PHP
foreach(glob("../thumbnail/".'*') as $filename){
echo "<div style=\"display:inline-table; font-size:10px; font-family:'Tahoma'; margin:5px;\">";
echo "<img width=\"100px\" height=\"100px\" src=\"../thumbnail/$filename\"/>";
echo "<br>".basename($filename) . "<br>";
echo "</div>";
}
?>
</div>
This method works perfect. No need to use complicated scripts.
Anyway, can somebody please tell me how to check images less than 100px x 100px displayed?
<?PHP
foreach(glob("../thumbnail/".'*') as $filename){
list($width, $height, $type, $attr) = getimagesize("../thumbnail/".$filename);
if($width>=100 || $height >=100) continue;
$rest = substr($filename, 3);
?>
That should do it..
I am trying to make sure that when the user uploads a profile picture, there can only be one image within the dir "profile_pic". I am openning and reading the dir with a while loop but the #unlink is not working. Below is the php code:
$directory = "uploads\\".$id."\images\profile_pic\\";
if (glob($directory . "*.jpg") != false) {
$filecount = count(glob($directory . "*.jpg"));
if ($filecount > 0) {
//delete exiting pics in folder profile_pic
$handle = opendir($directory);
while ($handle && ($file = readdir($handle)) !== false) {
if ( unlink($entry)) {
$msg .= "File Deleted";
}
}
closedir($directory);
}
}
Sorry, where did you define $entry - did you ever assign a value to it? And why do you make exactly the same call to glob() twice instead of catching the result of the first call in a variable? And why bother to opendir() to list files when you have already glob()ed and obtained that list of files? Especially when you don't apply the same *.jpg filter to the files you are deleting...
Just do this:
// Forward slashes work on Windows too (in PHP, at least)
$directory = "uploads/".$id."/images/profile_pic";
if (($existing = glob($directory . "/*.jpg")) !== false) { // Get a list of files...
foreach ($existing as $file) { // ...loop them...
$msg .= (unlink($directory."/".$file)) ? "File $file deleted\n" : "Could not delete $file\n"; // ...and delete them
}
} else $msg .= "Listing directory failed\n";
I want to display images from multi derctories.
I have this main folder ( backgrounds ) and inside this DIR I have 45 folders each folder have between 10-20 images.
I want to display all the images from the directories.
regards
Al3in
Try this one instead:
<?php
// Recursivly search through a directory and sub-directories for all
// image files. The returned result will be an array will all matches
// and their path (relative to the path sent in through the $dir argument)
//
// $dir - Directory to search through
// $filetypes - Array of file extensions to match
//
// Returns: Array() of files that match the $filetypes filter (or standard
// image file extensions by default).
//
function recursiveFileSearch($dir = '.', $filetypes = null)
{
if (!is_dir($dir))
return Array();
// create a regex filter so we only grab image files
if (is_null($filetypes))
$filetypes = Array('jpg','jpeg','gif','png');
$fileFilter = '/\.('.implode('|',$filetypes).')$/i';
// build a results array
$images = Array();
// open the directory and begin searching
if (($dHandle = opendir($dir)) !== false)
{
// iterate all files
while (($file = readdir($dHandle)) !== false)
{
// we don't want the . or .. directory aliases
if ($file == '.' || $file == '..')
continue;
// compile the path for reference
$path = $dir . DIRECTORY_SEPARATOR . $file;
// is it a directory? if so, append the results
if (is_dir($path))
$results = array_merge($results, recursiveFileSearch($path,$filetypes));
// must be a file, see if it matches our patter and add it if necessary
else if (is_file($path) && preg_match($fileFilter,$file))
$results[] = str_replace(DIRECTORY_SEPARATOR,'/',$path);
}
// close the directory when we're through
closedir($dHandle);
}
// return the outcome
return $results;
}
?>
<html><body><?php array_map(create_function('$i','echo "<img src=\"{$i}\" alt=\"{$i}\" /><br />";'),recursiveFileSearch('backgrounds')); ?></body></html>