I am trying to auto populate a set of pages with the content automatically generated by what is contained in a set folder structure.
I have found some code that is most of the way to what I am after however I am trying to modify it so that it is a function that can be called more than once with different folders.
The original code used a simple echo and was not a function.
I have edited it and made it a function but am getting stuck trying to figure out how to have the function return all of the results within the specified folder.
I am using this function:
function getDirContents($dir) {
date_default_timezone_set("Australia/Brisbane");
$hide = ".";
if (!isset($_SERVER['QUERY_STRING']) || $_SERVER['QUERY_STRING'] == "" || substr($_SERVER['QUERY_STRING'],0,2) == ".." || strstr($_SERVER['QUERY_STRING'], "..")) {
$currdir = "$dir";
} else {
$currdir = urldecode($_SERVER['QUERY_STRING']);
}
if ($currdir == "$dir") {
$label = "Root";
} else {
$path = explode('/', $currdir);
$label = $path[count($path)-1];
}
// Opens directory
$myDirectory = opendir($currdir);
// Gets each entry
while ($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// Closes directory
closedir($myDirectory);
// Counts elements in array
$indexCount = count($dirArray);
// Sorts files
//sort($dirArray);
// Loops through the array of files
for ($index = 0; $index < $indexCount; $index++) {
// Decides if hidden files should be displayed, based on query above.
if (substr("$dirArray[$index]", 0, 1) != $hide ) {
// Resets Variables
$favicon = "";
$class = "file";
// Gets File Names
$name = $dirArray[$index];
$namehref = ($currdir == "." ? "" : $currdir . '/') . $dirArray[$index];
$fullname = $currdir . '/' . $dirArray[$index];
// Gets Date Modified
$modtime = date("M j Y g:i A", filemtime($fullname));
$timekey = date("YmdHis", filemtime($fullname));
// Separates directories, and performs operations on those directories
if (is_dir($currdir . '/' . $dirArray[$index])) {
$extn = "<Directory>";
$size = "<Directory>";
$sizekey = "0";
$class = "dir";
// Gets favicon.ico, and displays it, only if it exists.
if (file_exists("$namehref/favicon.ico")) {
$favicon = " style='background-image:url($namehref/favicon.ico);'";
$extn = "<Website>";
}
// Cleans up . and .. directories
if($name=="."){$name=". (Current Directory)"; $extn="<System Dir>"; $favicon=" style='background-image:url($namehref/.favicon.ico);'";}
if($name==".."){$name=".. (Parent Directory)"; $extn="<System Dir>";}
if ($currdir == "." && $dirArray[$index] == "..")
$namehref = "";
elseif ($dirArray[$index] == "..") {
$dirs = explode('/', $currdir);
unset($dirs[count($dirs) - 1]);
$prevdir = implode('/', $dirs);
$namehref = '?' . $prevdir;
}
else
$namehref = '?' . $namehref;
}
// File-only operations
else {
// Gets file extension
$extn = pathinfo($dirArray[$index], PATHINFO_EXTENSION);
// Prettifies file type
switch ($extn){
case "png": $extn="PNG Image"; break;
case "jpg": $extn="JPEG Image"; break;
case "jpeg": $extn="JPEG Image"; break;
case "svg": $extn="SVG Image"; break;
case "gif": $extn="GIF Image"; break;
case "ico": $extn="Windows Icon"; break;
case "txt": $extn="Text File"; break;
case "log": $extn="Log File"; break;
case "htm": $extn="HTML File"; break;
//case "html": $extn="HTML File"; break;
case "xhtml": $extn="HTML File"; break;
case "shtml": $extn="HTML File"; break;
case "php": $extn="PHP Script"; break;
case "js": $extn="Javascript File"; break;
case "css": $extn="Stylesheet"; break;
case "pdf": $extn="PDF Document"; break;
case "xls": $extn="Spreadsheet"; break;
case "xlsx": $extn="Spreadsheet"; break;
case "doc": $extn="Microsoft Word Document"; break;
case "docx": $extn="Microsoft Word Document"; break;
//case "zip": $extn="ZIP Archive"; break;
case "htaccess": $extn="Apache Config File"; break;
case "exe": $extn="Windows Executable"; break;
default: if($extn!=""){$extn=strtoupper($extn);} else{$extn="Unknown";} break;
}
// Gets and cleans up file size
$size = pretty_filesize($fullname);
$sizekey = filesize($fullname);
}
$row = "<td><a href='$namehref'>$name ($extn, $size)</a> </td>";
return $row;
}
}
}
And then calling it with a variable like so
$Term1 = getDirContents('myFolder/Structure/');
echo $term1;
This prints out the first file in the folder however I can not for the life of me figure out how to get it to list them all.
My understanding is that when you use return in a function it stops the function, shouldn't the for loop it is within re-run however?
I feel like there is something really basic I am missing here so your help is much appreciated.
A very simple fix for this would be to change how you assign the table row strings to append the next row to the holding variable $row (with .=), and then move the return outside the loop.
I'm not going to copy the whole of your code, but the final few lines would look like this;
$row .= "<td><a href='$namehref'>$name ($extn, $size)</a> </td>";
// deleted 'return $row;' and moved to below
}
}
return $row;
}
Hope this helps.
PS: As we are appending strings to $row, it is good practice to initialize it at the top of your function in order to ensure there isn't a value for $row already in memory. To do this, simply write $row = ''; (ie, set it to a blank string).
Related
So I am trying to create a file server,
Basicaly the way it should work is you have lots of folders that contain files and when you click on a file you will download it, if it is a folder you can open it and see the content inside it.
My question is how can I create such system ? I have been trying to use FilesystemIterator but I do not know how to proceed further.
this is my PHP code that I am using, this code is set inside of div element
<?php
$filesInFolder = array();
$directory = "src";
$iterator = new FilesystemIterator($directory);
foreach($iterator as $entry){
$filesInFolder[] = $entry->getFilename();
}
foreach($filesInFolder as $file){
echo "<a href='/$file'> $file </a>";
}
?>
And this is my file structure
file structure
I know that it is possible to create this, I just don't know how to create it.
I've refactored your code a bit:
$filesInFolder = array();
$baseDir = "/var/www/html/test";
$currentDir = !empty($_GET['dir']) ? $_GET['dir'] : $baseDir;
$currentDir = rtrim($currentDir, '/');
if (isset($_GET['download'])) {
//you could provide another logic to present requested file
readfile($_GET['download']);
exit;
}
$iterator = new FilesystemIterator($currentDir);
echo "<h3>" . $iterator->getPath() . "</h3>";
foreach ($iterator as $entry) {
$name = $entry->getBasename();
if (is_dir($currentDir . '/' . $name)) {
echo "D: <a href='?dir=" . $currentDir . "/" . $name . "'>" . $name . "</a><br />";
} elseif (is_file($currentDir . '/' . $name)) {
echo "F: <a href='?download=" . $currentDir . '/' . $name . "' download='" . $name . "'> " . $name . " </a><br />";
}
}
You have to be very careful because an attacker could easily change the query to ?dir=../../ and get access to your filesystem.
So you have to prevent this by yourself.
Edit: It's not working 100% but I'm trying to provide a correct answer soon
Edit2: Code refactored to working
So here is how you would do it.
First you create a FileReader.php file like so ( I have also added Icons and file size, you will need to create icons folders where all your icons will be located)
<?php
/**
* File reader, reads directory and outputs it in an array
*/
class FileReader {
public function __construct(
public string $root
) {}
/**
* #param string $path
*/
public function removeRootFromPath( $path) {
$path = preg_replace('/' . preg_quote($this->root, '/') . '/', '', $path);
$path = $this->cleanPath($path);
return DIRECTORY_SEPARATOR . ltrim($path, DIRECTORY_SEPARATOR);
}
/**
* #param string $path
*/
public function addRootToPath( $path) {
$path = $this->removeRootFromPath($path);
$path = ltrim($path, DIRECTORY_SEPARATOR);
$root = rtrim($this->root, DIRECTORY_SEPARATOR);
return $root . DIRECTORY_SEPARATOR . $path;
}
/**
* #param string $dir Directory to load
*/
public function cleanPath( $dir) {
$sep = preg_quote(DIRECTORY_SEPARATOR, '/');
return preg_replace('/\.\.' . $sep . '|\.' . $sep . '/', '', $dir);
}
/**
* #param string $dir Directory to load
* #return FilesystemIterator|null
*/
public function readDirectory( $dir) {
$dir = $this->addRootToPath($dir);
try {
return new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
} catch (UnexpectedValueException $exception) {
return null;
}
}
/**
* #param string $size File size in bytes
* #param int $precision File size conversion precision
* #return string round($size, $precision).$units[$i]
*/
public function humanFilesize($size, $precision = 1) {
$units = array(' B',' kB',' MB',' GB',' TB',' PB',' EB',' ZB',' YB');
$step = 1024;
$i = 0;
while (($size / $step) > 0.9) {
$size = $size / $step;
$i++;
}
return round($size, $precision).$units[$i];
}
/**
* #param string $file File to load
* #return string $type <- File type
* #return string $image <- File image
*/
public function returnFileExtensionAndImage($file) {
$val = strtolower($file);
switch($val) {
case "avi":
$type = "Video file";
$image = "avi.png";
break;
case "bat":
$type = "Batch file";
$image = "bat.png";
break;
case "css":
$type = "Cascading Style Sheet";
$image = "txt.png";
break;
case "exe":
$type = "Executable file";
$image = "exe.png";
break;
case "fla":
$type = "Flash file";
$image = "fla.png";
break;
case "gif":
$type = "GIF Image";
$image = "gif.png";
break;
case "html":
$type = "HTML file";
$image = "html.png";
break;
case "htm":
$type = "HTM file";
$image = "html.png";
break;
case "jpg":
$type = "JPEG Image";
$image = "jpg.png";
break;
case "mp3":
$type = "Music File";
$image = "mp3.png";
break;
case "msg":
$type = "Email message";
$image = "msg.png";
break;
case "pdf":
$type = "PDF file";
$image = "pdf.png";
break;
case "psd":
$type = "Photoshop file";
$image = "psd.png";
break;
case "php":
$type = "PHP file";
$image = "php.png";
break;
case "ppt":
$type = "PowerPoint presentation";
$image = "ppt.png";
break;
case "pptx":
$type = "PowerPoint presentation";
$image = "ppt.png";
break;
case "swf":
$type = "SWF Flash file";
$image = "swf.png";
break;
case "txt":
$type = "Text file";
$image = "txt.png";
break;
case "csv":
$type = "CSV file";
$image = "txt.png";
break;
case "wma":
$type = "Windows Media Audio";
$image = "wma.png";
break;
case "xls":
$type = "Excel file";
$image = "xls.jpg";
break;
case "xlsx":
$type = "Excel file";
$image = "xls.jpg";
break;
case "zip":
$type = "Zip file";
$image = "zip.png";
break;
case "7zip":
$type = "Zip file";
$image = "zip.png";
break;
case "zip":
$type = "Zip file";
$image = "zip.png";
case "7z":
$type = "7Zip file";
$image = "rar.png";
break;
case "doc":
$type = "Word document";
$image = "doc.png";
break;
case "docx":
$type = "Word document";
$image = "doc.png";
break;
case "docs":
$type = "Word document";
$image = "doc.png";
case "rar":
$type = "Rar file";
$image = "rar.png";
//--- New Here---//
default:
$type = "Unknown file";
$image = "unknown.jpg";
}
return $type . "?" . $image;
}
}
?>
Then you Create FileTable.php in which all of your files and folders will be displayed and you will be able to access them and download selected files (Only files not folders) + (I have added simple filtering)
<?php
$cleanPath = $target;
/**
* CURRENT DIRECTORY LOCATION DISPLAY FIX
*/
switch (strlen($cleanPath)) {
case 1:
$cleanPath[0] = " ";
break;
case 2:
if($cleanPath[0] == "\\" && $cleanPath[1] == "/"){
$cleanPath[0] = " ";
$cleanPath[1] = " ";
$cleanPath[2] = " ";
break;
}else {
$cleanPath[0] = " ";
break;
}
default:
$cleanPath[0] = " ";
break;
}
/**
* HERE WRITE ALL FILES YOU WANT FileReader TO IGNORE
* - WRITE file + its extension
* - FOR DIRECTORY WRITE THE NAME OF THE DIRECTORY TO IGNORE
*/
$filesToIgnore = [
'index.php',
'index.css',
'index.html',
'Restricted',
'PUT YOUR FILES HERE.txt'
];
?>
<?php if(strlen($target) != 0): ?>
<p class="CurrentFolderLocation"><?= $cleanPath; ?></p>
<?php else: ?>
<p class="CurrentFolderLocation"></p>
<?php endif ?>
<table class="FileTable">
<div class="InputArea">
<input type="text" id="filterInput" onkeyup="filterTable()" placeholder="Name of the file to search for...">
</div>
<thead class="TableHead">
<tr>
<th>
<a class="ReturnImg" href="?path=<?= urlencode($reader->removeRootFromPath(dirname($target))); ?>">
<img src= "../Components/icons/levelup.png" alt="level up"/>
</a>
</th>
<th>File name</th>
<th>File size</th>
<th>File type</th>
<th>Last file modification date</th>
</tr>
</thead>
<tbody id="tableBody" class="TableBody">
<?php if ($results = $reader->readDirectory($target)): ?>
<?php foreach($results as $result): ?>
<?php
$currentFileToCheck = explode("\\",$result);
$currentFileToCheck = $currentFileToCheck[array_key_last($currentFileToCheck)];
?>
<?php if(!in_array($currentFileToCheck,$filesToIgnore)): ?>
<tr>
<?php
// Make the full path user friendly by removing the root directory.
$user_friendly = $reader->removeRootFromPath($result->getFileInfo());
//File information
$fileName = pathinfo($result,PATHINFO_BASENAME);
$fileInfo = explode("?",($reader->returnFileExtensionAndImage(pathinfo($result,PATHINFO_EXTENSION))),2);
$fileExtension = $fileInfo[0];
$fileIcon = $iconsPath . $fileInfo[1];
$fileDateModified = explode(" ",date("F d.Y - H:i:s",filemtime($result)),4);
$fileDateModified = implode(" ",$fileDateModified);
$type = $result->getType();
if($type !== 'dir'){
$fileSize = $reader->humanFilesize(filesize($result));
}
?>
<?php if($type === 'dir'): ?>
<td><img class="FileImage" src="../Components/icons/folder.jpg"></td>
<td>
<?= $fileName; ?>
</td>
<td></td>
<td></td>
<td></td>
<?php else: ?>
<td><img class="FileImage" src=<?= $fileIcon; ?> alt="Ikonka souboru"></td>
<?php if(pathinfo($result,PATHINFO_EXTENSION) == "pdf"): ?>
<td><a target="_blank" href="./<?= $user_friendly; ?>"><?= $fileName; ?></a></td>
<?php else: ?>
<td><a download href="./<?= $directoryToScan . "/" . $user_friendly; ?>"><?= $fileName; ?></a></td>
<?php endif ?>
<td><?= $fileSize; ?></td>
<td><?= $fileExtension; ?></td>
<td><?= $fileDateModified; ?></td>
<?php endif ?>
</tr>
<?php endif ?>
<?php endforeach ?>
<?php else: ?>
<tr>
<td></td>
<td>Directory/File doesn't exist</td>
<td></td>
<td></td>
<td></td>
</tr>
<?php endif ?>
</tbody>
</table>
<script>
function filterTable() {
// Declare variables
let input = document.getElementById("filterInput"),
filter = input.value.toUpperCase(),
table = document.getElementById("tableBody"),
tr = table.getElementsByTagName("tr"),
td,
i,
txtValue;
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
And at last you will create index.php where you will connect this together
<?php
$path = $_SERVER['DOCUMENT_ROOT']; // Get Root path of your file system
$componentPath = $path . "/Components/";
$componentFileReader = $componentPath . "FileReader.php";
$componentFileTable = $componentPath . "FileTable.php";
$iconsPath = "/Components/icons/";
$cssStyle = "./Components/index.css";
include($componentFileReader);
$directoryToScan = 'src'; // Relative to current file. Change to your path!
$reader = new FileReader(__DIR__ . DIRECTORY_SEPARATOR . $directoryToScan);
$target = $reader->removeRootFromPath(!empty($_GET['path']) ? $_GET['path'] : '/');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href=<?=$cssStyle; ?>>
<title>File browser</title>
</head>
<body>
<main class="PageBody flex-column">
<?php include($componentFileTable) ?>
</main>
</body>
</html>
Should you need it -> CODE HERE <- Here is my code on Github with some CSS styling and some icons -> Simply download it and put it in your htdocs folder if you are using Apache
I'm having a hard time implemeting the php code will ensure that all uploaded photos will be oriented correctly upon upload.
here is my upload.php function ...
function process_image_upload($field)
{
if(!isset($_FILES[$field]['tmp_name']) || ! $_FILES[$field]['name'])
{
return 'empty';
}
$temp_image_path = $_FILES[$field]['tmp_name'];
$temp_image_name = $_FILES[$field]['name'];
list($iwidth, $iheight, $temp_image_type) =
getimagesize($temp_image_path);
if ($temp_image_type === NULL) {
return false;
}
elseif( $iwidth < 400 )
return 'size';
switch ($temp_image_type) {
case IMAGETYPE_GIF:
break;
case IMAGETYPE_JPEG:
break;
case IMAGETYPE_PNG:
break;
default:
return false;
}
$uploaded_image_path = UPLOADED_IMAGE_DESTINATION . $temp_image_name;
move_uploaded_file($temp_image_path, $uploaded_image_path);
$thumbnail_image_path = THUMBNAIL_IMAGE_DESTINATION .
preg_replace('{\\.[^\\.]+$}', '.jpg', $temp_image_name);
$main_image_path = MAIN_IMAGE_DESTINATION . preg_replace('{\\.[^\\.]+$}', '.jpg', $temp_image_name);
$result =
generate_image_thumbnail($uploaded_image_path,
$thumbnail_image_path,150,150
); if( $result )
$result =
generate_image_thumbnail($uploaded_image_path,$main_image_path,400,400,
true);
return $result ? array($uploaded_image_path, $thumbnail_image_path) :
false;
}
if(isset($_POST['upload'])):
$result = process_image_upload('image');
if ($result === false) {
update_option('meme_message','<div class="error" style="margin-
left:0;"><p>An error occurred while processing upload</p></div>');
} else if( $result === 'empty')
{
update_option('meme_message','<div class="error" style="margin-
left:0;"><p>Please select a Image file</p></div>');
}
elseif( $result === 'size')
{
update_option('meme_message','<div class="error" style="margin-
left:0;"><p>Image width must be greater than 400px;</p></div>');
}
else {
update_option('meme_message','<div style="margin-left:0;"
class="updated"><p>Image uploaded successfully</p></div>');
$guploaderr = false;
$count = intval(get_option('meme_image_count'));
update_option('meme_image_count', $count+1);
}
endif;
and here is some php that I know will work to rotate... but I don't know how to implement.
<?php
$image =
imagecreatefromstring(file_get_contents($_FILES['image_upload']
['tmp_name']));
$exif = exif_read_data($_FILES['image_upload']['tmp_name']);
if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
case 8:
$image = imagerotate($image,90,0);
break;
case 3:
$image = imagerotate($image,180,0);
break;
case 6:
$image = imagerotate($image,-90,0);
break;
}
}
// $image now contains a resource with the image oriented correctly
?>
I'm looking to add a force download function to the file exploere script below. I need to force the user to download the file when he click on the $namehref, instead of opening the file in the broswer.
How do i add that to the code?
<?php
// Adds pretty filesizes
function pretty_filesize($file) {
$size = filesize($file);
if ($size < 1024) {
$size = $size . " Bytes";
} elseif (($size < 1048576) && ($size > 1023)) {
$size = round($size / 1024, 1) . " KB";
} elseif (($size < 1073741824) && ($size > 1048575)) {
$size = round($size / 1048576, 1) . " MB";
} else {
$size = round($size / 1073741824, 1) . " GB";
}
return $size;
}
date_default_timezone_set("Europe/Rome");
// Checks to see if veiwing hidden files is enabled
/*
if ($_SERVER['QUERY_STRING'] == "hidden") {
$hide = "";
$ahref = "./";
$atext = "Hide";
} else {
$hide = ".";
$ahref = "./?hidden";
$atext = "Show";
}
*/
$hide = ".";
if (!isset($_SERVER['QUERY_STRING']) || $_SERVER['QUERY_STRING'] == "" || substr($_SERVER['QUERY_STRING'],0,2) == ".." || strstr($_SERVER['QUERY_STRING'], "..")) {
$currdir = ".";
} else {
$currdir = urldecode($_SERVER['QUERY_STRING']);
}
if ($currdir == ".")
$label = "Root";
else {
$path = explode('/', $currdir);
$label = $path[count($path)-1];
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" href="./favicon.ico">
<link rel="stylesheet" href="favicon.ico">
<title>DPP</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="sorttable.js"></script>
</head>
<body>
<div id="container" style="margin-top:-50px">
<table class="sortable">
<thead>
<tr>
<th bgcolor="#003399">Filename</th>
<th bgcolor="#003399">Type</th>
</tr>
</thead>
<tbody><?php
error_reporting(0);
// Opens directory
$myDirectory = opendir($currdir);
// Set Forbidden Files
$forbiddenExts = array("php", "ico", "html", "LCK", "js", "css");
// Gets Each Entry
while($entryName = readdir($myDirectory)) {
$exts = explode(".", $entryName);
if(!in_array($exts[1],$forbiddenExts)) {
$dirArray[] = $entryName;
}
}
// Closes directory
closedir($myDirectory);
// Counts elements in array
$indexCount = count($dirArray);
// Sorts files
//sort($dirArray);
// Loops through the array of files
for ($index = 0; $index < $indexCount; $index++) {
// Decides if hidden files should be displayed, based on query above.
if (substr("$dirArray[$index]", 0, 1) != $hide || ($currdir != '.' && $dirArray[$index] == "..")) {
// Resets Variables
$favicon = "";
$class = "file";
// Gets File Names
$name = $dirArray[$index];
$namehref = ($currdir == "." ? "" : $currdir . '/') . $dirArray[$index];
$fullname = $currdir . '/' . $dirArray[$index];
// Gets Date Modified
$modtime = date("M j Y g:i A", filemtime($fullname));
$timekey = date("YmdHis", filemtime($fullname));
// Separates directories, and performs operations on those directories
if (is_dir($currdir . '/' . $dirArray[$index])) {
$extn = "<Folder>";
$size = "<Folder>";
$sizekey = "0";
$class = "dir";
// Gets favicon.ico, and displays it, only if it exists.
if (file_exists("$namehref/favicon.ico")) {
$favicon = " style='background-image:url($namehref/favicon.ico);'";
$extn = "<Website>";
}
// Cleans up . and .. directories
if ($name == ".") {
$name = ". (Current Directory)";
$extn = "<System Dir>";
$favicon = " style='background-image:url($namehref/.favicon.ico);'";
}
if ($name == "..") {
$name = ".. (Return to Parent Folder)";
$extn = "<System Dir>";
}
if ($currdir == "." && $dirArray[$index] == "..")
$namehref = "";
elseif ($dirArray[$index] == "..") {
$dirs = explode('/', $currdir);
unset($dirs[count($dirs) - 1]);
$prevdir = implode('/', $dirs);
$namehref = '?' . $prevdir;
}
else
$namehref = '?' . $namehref;
}
// File-only operations
else {
// Gets file extension
$extn = pathinfo($dirArray[$index], PATHINFO_EXTENSION);
// Prettifies file type
switch ($extn) {
case "png": $extn = "PNG Image";
break;
case "jpg": $extn = "JPEG Image";
break;
case "ppsx": $extn = "Microsoft Power Point";
break;
case "jpeg": $extn = "JPEG Image";
break;
case "svg": $extn = "SVG Image";
break;
case "gif": $extn = "GIF Image";
break;
case "ico": $extn = "Windows Icon";
break;
case "txt": $extn = "Text File";
break;
case "log": $extn = "Log File";
break;
case "htm": $extn = "HTML File";
break;
case "html": $extn = "HTML File";
break;
case "xhtml": $extn = "HTML File";
break;
case "shtml": $extn = "HTML File";
break;
case "ppt": $extn = "Microsoft Power Point";
break;
case "js": $extn = "Javascript File";
break;
case "css": $extn = "Stylesheet";
break;
case "pdf": $extn = "PDF Document";
break;
case "xls": $extn = "Spreadsheet";
break;
case "xlsx": $extn = "Spreadsheet";
break;
case "doc": $extn = "Microsoft Word Document";
break;
case "docx": $extn = "Microsoft Word Document";
break;
case "zip": $extn = "ZIP Archive";
break;
case "htaccess": $extn = "Apache Config File";
break;
case "exe": $extn = "Windows Executable";
break;
default: if ($extn != "") {
$extn = strtoupper($extn) . " File";
} else {
$extn = "Sconosciuto";
} break;
}
// Gets and cleans up file size
$size = pretty_filesize($fullname);
$sizekey = filesize($fullname);
}
// Output
echo("
<tr class='$class'>
<td><a href='$namehref'$favicon class='name'>$name</a></td>
<td><a href='$namehref'>$extn</a></td>
</tr>");
}
}
?>
</tbody>
</table>
</div>
</body>
</html>
use this line:
header("Content-Disposition: attachment;Filename={FILE_NAME}");
since it modifies header information, it should be placed above all echos
header('Content-type: application/ms-excel'); // file type
header('Content-Description: File Transfer');
header("Content-Disposition: attachment; filename=\"" .$filename . "\"");
header("Cache-control: private");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: no-cache');
function getFileExtension($fileType)
{
switch($fileType)
{
case "image/png":
return "png";
return true;
break;
case "image/png":
return "x-png";
return true;
break;
case "mage/pjpeg":
return "jpg";
return true;
break;
case "image/jpeg":
return "jpg";
return true;
break;
default:
return false;
}
}
2nd return statement will never be executed. If you want to return 2 values, return an array containing the 2 values..
function getFileExtension($fileType)
{
$results = array();
switch($fileType)
{
case "image/png":
$results['type'] = "png";
$results['status'] = true;
break;
case "image/png":
$results['type'] = "x-png";
$results['status'] = true;
break;
case "mage/pjpeg":
$results['type'] = "jpg";
$results['status'] = true;
break;
case "image/jpeg":
$results['type'] = "jpg";
$results['status'] = true;
break;
default:
$results['type'] = "";
$results['status'] = false;
}
return $results;
}
i am working on php function that would put watermark on image. I´ve got it working but i need to scale this watermark so the height of the watermark will be 1/3 of the original image. I can do that, but when i put it into my code it just doesnt work, because the parameter of imagecopymerge must be resource, which i dont know what means.
define('WATERMARK_OVERLAY_IMAGE', 'watermark.png');
define('WATERMARK_OVERLAY_OPACITY', 100);
define('WATERMARK_OUTPUT_QUALITY', 100);
function create_watermark($source_file_path, $output_file_path)
{
list($source_width, $source_height, $source_type) = getimagesize($source_file_path);
if ($source_type === NULL) {
return false;
}
switch ($source_type) {
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif($source_file_path);
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg($source_file_path);
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng($source_file_path);
break;
default:
return false;
}
$overlay_gd_image = imagecreatefrompng(WATERMARK_OVERLAY_IMAGE);
$overlay_width = imagesx($overlay_gd_image);
$overlay_height = imagesy($overlay_gd_image);
//THIS PART IS WHAT SHOULD RESIZE THE WATERMARK
$source_width = imagesx($source_gd_image);
$source_height = imagesy($source_gd_image);
$percent = $source_height/3/$overlay_height;
// Get new sizes
$new_overlay_width = $overlay_width * $percent;
$new_overlay_height = $overlay_height * $percent;
// Load
$overlay_gd_image_resized = imagecreatetruecolor($new_overlay_width, $new_overlay_height);
// Resize
$overlay_gd_image_complet = imagecopyresized($overlay_gd_image_resized, $overlay_gd_image, 0, 0, 0, 0, $new_overlay_width, $new_overlay_height, $overlay_width, $overlay_height);
//ALIGN BOTTOM, RIGHT
if (isset($_POST['kde']) && $_POST['kde'] == 'pravo') {
imagecopymerge(
$source_gd_image,
$overlay_gd_image_complet,
$source_width - $new_overlay_width,
$source_height - $new_overlay_height,
0,
0,
$new_overlay_width,
$new_overlay_height,
WATERMARK_OVERLAY_OPACITY
);
}
if (isset($_POST['kde']) && $_POST['kde'] == 'levo') {
//ALIGN BOTTOM, LEFT
imagecopymerge(
$source_gd_image,
$overlay_gd_image,
0,
$source_height - $overlay_height,
0,
0,
$overlay_width,
$overlay_height,
WATERMARK_OVERLAY_OPACITY
);
}
imagejpeg($source_gd_image, $output_file_path, WATERMARK_OUTPUT_QUALITY);
imagedestroy($source_gd_image);
imagedestroy($overlay_gd_image);
imagedestroy($overlay_gd_image_resized);
}
/*
* Uploaded file processing function
*/
define('UPLOADED_IMAGE_DESTINATION', 'originals/');
define('PROCESSED_IMAGE_DESTINATION', 'images/');
function process_image_upload($Field)
{
$temp_file_path = $_FILES[$Field]['tmp_name'];
/*$temp_file_name = $_FILES[$Field]['name'];*/
$temp_file_name = md5(uniqid(rand(), true)) . '.jpg';
list(, , $temp_type) = getimagesize($temp_file_path);
if ($temp_type === NULL) {
return false;
}
switch ($temp_type) {
case IMAGETYPE_GIF:
break;
case IMAGETYPE_JPEG:
break;
case IMAGETYPE_PNG:
break;
default:
return false;
}
$uploaded_file_path = UPLOADED_IMAGE_DESTINATION . $temp_file_name;
$processed_file_path = PROCESSED_IMAGE_DESTINATION . preg_replace('/\\.[^\\.]+$/', '.jpg', $temp_file_name);
move_uploaded_file($temp_file_path, $uploaded_file_path);
$result = create_watermark($uploaded_file_path, $processed_file_path);
if ($result === false) {
return false;
} else {
return array($uploaded_file_path, $processed_file_path);
}
}
$result = process_image_upload('File1');
if ($result === false) {
echo '<br>An error occurred during file processing.';
} else {
/*echo '<br>Original image saved as ' . $result[0] . '';*/
echo '<br>Odkaz na obrazek je zde';
echo '<br><img src="' . $result[1] . '" width="500px">';
echo '<br><div class="fb-share-button" data-href="' . $result[1] . '" data-type="button"></div>';
}