I have a link, that after click the link, user can download image. Right now, after click the link, user only can viewed the image.
How can I make browser to make after user click link, it will force to download the image
Here's the code
<html>
<head>
<title> Download-Images</title>
</head>
<body>
<p> Click the link ! You can download Image </p>
<a download="logo.png" href="https://w3schools.com/images/myw3schoolsimage.jpg" title="Logo title" target="_blank">
link
</a>
</body>
</html>
I've tried added php code from here and here in below my html code, but it's not working.
You can try this. I have tested on my localhost and it worked.
html:
<html>
<head>
<title> Download-Images</title>
</head>
<body>
<p> Click the link ! You can download Image </p>
<a href="download.php?url=https://w3schools.com/images/myw3schoolsimage.jpg" title="Logo title">
link
</a>
</body>
</html>
download.php
<?php
$url = $_GET['url'];
if ($url != '')
{
$filename = end(explode('/', $url));
$fileext = strtolower(end(explode('.', $filename)));
if ($fileext == 'jpg' || $fileext == 'jpeg') { $type = 'image/jpeg'; }
if ($fileext == 'png') { $type = 'image/png'; }
if ($fileext == 'gif') { $type = 'image/gif'; }
//$size = filesize($url);
header("Content-Type: $type");
header("Content-disposition: attachment; filename=\"" . $filename . "\"");
header("Content-Transfer-Encoding: binary");
//header("Content-Length: " . $size);
readfile($url);
}else{
echo 'url is blank';
}
?>
Related
I'm trying to decode base64 image on php but i get blank image with black screen showing that windows doesn't support this type of file.
Here is my code
public function uploadfoto(){
$img = $_POST['foto'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$filedir = "./assets/upload/presensi/mx_" . mktime() . ".jpg";
$filename = "mx_".mktime().".jpg";
$result = file_put_contents($filedir, $data);
}
I get the image from my webcam and here is my view
<form id ="inputfoto">
<div id="my_camera" style="width: 320px; height: 240px;" class="center"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="<?php echo base_url();?>assets/dist/js/webcamjs/webcam.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 100
});
Webcam.attach( '#my_camera' );
</script>
<div id="results" align = "middle" >Hasil akan tampil di sini</div>
<input type="button" value="Take Snapshot" onclick="take_snapshot()" class="center" style="margin-bottom: 5px;">
<input type="button" value="Submit" onClick="saveSnap()" class="center">
</form>
<script language="JavaScript">
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>HASIL</h2>' +
'<img id="foto" src="'+data_uri+'"/>';
} );
}
function saveSnap(){
var file = document.getElementById("foto").src;
var formdata = new FormData();
formdata.append("foto", file);
var ajax = new XMLHttpRequest();
ajax.open("POST", "<?php echo base_url();?>asisten/presensi/uploadfoto");
ajax.send(formdata);
}
</script>
And here is the
Blank Image
What's wrong with my code? Thank you very much for your respond.
This code works for me.Please check it
$image = $this->generateImage($_POST['foto']);
public function generateImage($img)
{
$folderPath = "uploads/";
$image_parts = explode(";base64,", $img);
$image_type_aux = explode("uploads/", $image_parts[0]);
$image_base64 = base64_decode($image_parts[1]);
$name = uniqid() . '.png';
$file = $folderPath . $name;
file_put_contents($file, $image_base64);
return $name;
}
i'm building a directory browser and while i was looking for info i found this question, to my surprise the code is quite easier than i expected and i'm able to understand it, so i'm using it on my project(i'm quite new to php, and i never use code that i don't understand). It works fine and i've made a few aesthetic changes. Now here comes the problem, for some reason i cannot change the root directory, i have this:
<?php
session_start();
if(!isset($_SESSION['username'])){
header("Location: ./test.php");
}
?>
<!doctype html>
<html>
<head>
<title>CoroCloud</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./js/material.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.pink-indigo.min.css" />
</head>
<html>
<body>
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class="mdl-layout__header">
<div class="mdl-layout__header-row">
<!-- Title -->
<span class="mdl-layout-title">Cloud</span>
<!-- Add spacer, to align navigation to the right -->
<div class="mdl-layout-spacer"></div>
<!-- Navigation. We hide it in small screens. -->
<nav class="mdl-navigation mdl-layout--large-screen-only">
<?php
echo "<a class=\"mdl-navigation__link\" href=\"\">{$_SESSION['username']}</a>";
?>
</nav>
</div>
</header>
<div class="mdl-layout__drawer">
<span class="mdl-layout-title">CATEGORIES</span>
<nav class="mdl-navigation">
<a class="mdl-navigation__link" href="">File</a>
<a class="mdl-navigation__link" href="">Images</a>
<a class="mdl-navigation__link" href="">Music</a>
<a class="mdl-navigation__link" href="">Films</a>
</nav>
</div>
<main class="mdl-layout__content" style="background-color: white; background-image: url('https://i.warosu.org/data/tg/img/0357/97/1414469732022.gif'); background-size: auto 100%; background-repeat: no-repeat; background-position: center;">
<center>
<div class="page-content" style="padding: 24px; flex: none; align-items: center; justify-content: center;">
<?php
// Snippet from PHP Share: http://www.phpshare.org
function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824)
{
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
}
elseif ($bytes >= 1048576)
{
$bytes = number_format($bytes / 1048576, 2) . ' MB';
}
elseif ($bytes >= 1024)
{
$bytes = number_format($bytes / 1024, 2) . ' kB';
}
elseif ($bytes > 1)
{
$bytes = $bytes . ' bytes';
}
elseif ($bytes == 1)
{
$bytes = $bytes . ' byte';
}
else
{
$bytes = '0 bytes';
}
return $bytes;
}
$root = dirname("path");
function is_in_dir($file, $directory, $recursive = true, $limit = 1000) {
$directory = realpath($directory);
$parent = realpath($file);
$i = 0;
while ($parent) {
if ($directory == $parent) return true;
if ($parent == dirname($parent) || !$recursive) break;
$parent = dirname($parent);
}
return false;
}
$path = null;
if (isset($_GET['file'])) {
$path = $_GET['file'];
if (!is_in_dir($_GET['file'], $root)) {
$path = null;
} else {
$path = '/'.$path;
}
}
if (is_file($root.$path)) {
readfile($root.$path);
return;
}
echo "<div>\n";
echo "<table class=\"mdl-data-table mdl-js-data-table mdl-shadow--2dp\" style=\"min-width:300px\"\n";
echo " <thead>\n";
echo " <tr>\n";
echo " <th class=\"mdl-data-table__cell--non-numeric\">File</th>\n";
echo " <th>Size</th>\n";
echo " </tr>\n";
echo " </thead>\n";
echo " <tbody>";
if ($path) echo '<tr><td colspan="2" style="text-align:center">..</td></tr><br />';
foreach (glob($root.$path.'/*') as $file) {
$file = realpath($file);
$link = substr($file, strlen($root) + 1);
if (is_dir($file)){
echo '<tr><td style="text-align:center; vertical-align:middle"><i class="material-icons" style="vertical-align:middle">folder</i></td><td style="text-align:center; vertical-align:middle"><span style="vertical-align:middle">'.basename($file).'</span></td></tr><br />';
}
else {
$size = formatSizeUnits(filesize($file));
echo '<tr><td><a href="?file='.urlencode($link).'" download>'.basename($file).'</a></td><td>'.$size.'</td></tr><br />';
}
}
?>
</tbody>
</table>
</div>
</center>
</main>
</div>
</body>
</html>
What i'm doing is changing the value of $root, but the result is not what i expected, instead of allow me to browse the contents it stays in root directory even if i click another folder. In some of the tests i've done (with different paths and permissions) sometimes it didn't even show anything.
Can anybody tell me why is this happening AND how to solve this?
(Please don't answer with just a solution, i'd like to know what's is what I missunderstood and learn)
I think the issue lies within retrieving the $root path. Your whole script is based on working with absolute paths, therefore I've changed the $root path to also get its absolute path and voilà it worked.
Make sure that argument given to dirname does exist, as it looks like it's not intended to be just the string "path". More at php.net
$root = realpath(dirname("path"));
By the way:
While testing your script I found an issue regarding downloading files. When clicking a file it allows me to download it, but the downloaded file contains the HTML code of your script up to the point where the file is being sent. So make sure to move your code to the beginning of the file in order to fix it.
if (is_file($root.$path)) {
readfile($root.$path);
return;
}
Edit:
I found another issue regarding the function is_in_dir, it's not capable of working with relative paths when the root directory is not the exact same as the scripts directory. To let it work the function needs to look for the specified $file within the root directory $directory like the following:
function is_in_dir($file, $directory, $recursive = true, $limit = 1000) {
$directory = realpath($directory);
// new:
$parent = realpath($directory . DIRECTORY_SEPARATOR . $file);
$i = 0;
I have upload and download scripts. Here they are:
Upload
<html>
<head>
<title> Result </title>
</head>
<body>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<link rel="stylesheet" href="stylesheet.css">
<div class="container">
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (!empty($_FILES) && move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File was succesfully uploaded to ".$uploaddir;
} else {
echo "Something went wrong. Attach you file, please. \n";
}
//
//if ($_FILES["userfile"]["size"] > 500000) {
// echo "Sorry, your file is too large.\n";
//}
$filelist = scandir($uploaddir, 1);
?>
<p> Download your files: </p>
<table>
<?php foreach($filelist as $file): ?>
<tr>
<td> <?php echo $file; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php
//debug
// print_r ($filelist);
// print_r($_FILES);
?>
</div>
</body>
</html>
Download
<?php
// block any attempt to the filesystem
if (isset($_GET['file']) && basename($_GET['file']) == $_GET['file']) {
$filename = $_GET['file'];
} else {
$filename = NULL;
}
$error = 'Sorry, the file you are requesting is unavailable for ya.';
if (!$filename) {
// if $filename is NULL or false display the message
echo $error;
} else {
$path = '/var/www/uploads/'.$filename;
if (file_exists($path) && is_readable($path)) {
$size = filesize($path);
header('Content-Type: application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
// display the error messages if the file can´t be opened
$file = # fopen($path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit;
} else {
echo $error;
}
} else {
echo $error;
}
}
Now I can see just the list of the files I uploaded.
Like that
I want to make them links so I can download and delete (using GET and unlink) each file from the directory. I assume I have to use foreach but I still can't figure it out. Thanks in advance.
Just make them links:
<?php foreach($filelist as $file): ?>
<tr>
<td>
<?php echo $file; ?>
</td>
</tr>
<?php endforeach; ?>
I used jquery.form plugin for file upload (downloaded code from http://malsup.com/). It works fine on my local machine but shows blank page after submitting the form on the server. I've set up file permissions 777 for the directory where files are to be uploaded. The "out of the box" code works fine on server. However, I've incorporated it into my jquery mobile setup and added database operations and file-delete forms. While it works as intended locally it displays blank page on the server. There's no error of any kind displayed, files are not getting uploaded, database is not being updated. It appears that the processing code is not executed at all. I have tried to echo something at the start of form processing code and that is not happening either, so it looks like the ajax form does not get submitted.
Here is the code for the form and second for the processing.
<?php
require_once ("lib/required.php");
$_SESSION['login_data'] = get_login_data();
# Login Protected Page - send them back home
if (!$_SESSION['login_data']['user_logged_in']){ # not logged in
$redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
header ( "Location: " . $redirect_url ); # must be logged in - send them to homepage
exit;
} elseif ($_SESSION['login_data']['group_title'] != 'Landlord'){ # logged in but not a Landlord
$redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
header ( "Location: " . $redirect_url ); # id mismatch - send them to homepage
exit;
} elseif (isset($_GET['memid']) && $_GET['memid'] != $_SESSION['login_data']['id']){ # logged in but memid in url is no match (typed in?)
$redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
header ( "Location: " . $redirect_url ); # id mismatch - send them to homepage
exit;
} elseif (isset($_GET['propid'])){
if (!$foo = sql_get_results_array("SELECT * FROM " . DBPREFIX . "tbl_property WHERE property_id = " . $_GET['propid'] . " AND landlord_id = " . $_GET['memid'])){ # logged in but propid in url is no match (typed in?)
$redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
header ( "Location: " . $redirect_url ); # id vs property mismatch - send them to homepage
exit;
}
}
# DO NOT include the code below on PayPalP Pay Subscription Page
# This code MUST BE INCLUDED on every Login Protected Page
# check subscription and send them to PayPal if not valid
if (!valid_subscription($_SESSION['login_data']['id'],$_SESSION['login_data']['membership_expiry'],$_SESSION['login_data']['grace_expiry'],$_SESSION['login_data']['subscription_fee'])){
$_SESSION['popup_msg_id'] = 37; # this is to popup a "final call" message
$redirect_url = "http://" . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . "/" . PAYPAL_PAY_SUBSCRIPTION_PAGE . "?memid=" . $_SESSION['login_data']['id'];
header ( "Location: " . $redirect_url ); # send them to referring page where resulting messages will be displayed
exit;
}
# DO NOT include the code above on PayPalP Pay Subscription Page
# End-of-Housekeeping
if (isset($_GET['memid'])){
$member_id = $_GET['memid']; # get landlord id from url
} else {
$member_id = $_SESSION['login_data']['id']; # get landlord id from login
}
if (isset($_GET['propid'])){ # this is for when coming from property details page with a selected property id in url
$property_id = $_GET['propid']; # get property id from url
$my_post_list['property-list-form-submitted'] = "1"; # fake "list" form submission to force appropriate form contents
$my_post_list['property-list'] = $property_id;
$property_selected = TRUE;
}
if ($_POST['property-list-form-submitted'] == "1") { # form submitted - property selected - copy $_POST to own array
$my_post_list = $_POST;
if ($my_post_list['property-list'] == 0){ # insert new data - redirect to property details page
$redirect_url = "http://" . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . "/" . LANDLORD_PROPERTY_DETAILS_PAGE . "?memid=" . $_SESSION['login_data']['id'] . "&action=addprop";
header ( "Location: " . $redirect_url ); # send them to property details page
exit;
} else {
$property_id = $my_post_list['property-list'];
$property_selected = TRUE;
}
}
$property_list = sql_get_results_array( "SELECT * FROM " . DBPREFIX . "tbl_property WHERE landlord_id = " . $member_id); # get list of all properties & details for this landlord in 2-dimensional associative array
if ($my_post_list['property-list-form-submitted'] == "1") { # form submitted - property selected - display all property details
$property_selected = TRUE;
$property_data = sql_get_results_array( "SELECT * FROM " . DBPREFIX . "tbl_property WHERE landlord_id = " . $member_id . " AND property_id = " . $my_post_list['property-list']);
}
if ($_POST['remove-pic-form-submitted'] == "1"){ # delete saved image that was clicked upon
if (!db("DELETE FROM " . DBPREFIX . "tbl_property_picture WHERE property_id = " . $property_id . " AND landlord_id = '" . $member_id . "' AND picture_path = '" . $_POST['remove-this-path'] . "' AND picture_filename = '" . $_POST['remove-this-file'] . "'")){ # delete didn't work
$_SESSION['popup_msg_id'] = 14; # this is to popup error message if delete fails
} # /if
$propimage = $_POST['remove-this-path'] . $_POST['remove-this-file'];
// See if it exists before attempting deletion on it
if (file_exists($propimage)) {
unlink($propimage); // Delete now
}
// See if it exists again to be sure it was removed
if (file_exists($propimage)) {
echo "Problem deleting " . $propimage;
}
$propthumb = $_POST['remove-this-path'] . "thumb_" . $_POST['remove-this-file'];
// See if it exists before attempting deletion on it
if (file_exists($propthumb)) {
unlink($propthumb); // Delete now
}
// See if it exists again to be sure it was removed
if (file_exists($propthumb)) {
echo "Problem deleting " . $propthumb;
}
} # /if file delete form submitted
?>
<!doctype html>
<html>
<head>
<title><?php echo $page_title ;?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php include("inc/pl_css.inc"); ?>
<link href="css/image-upload.css" rel="stylesheet" type="text/css" />
<?php include("inc/pl_js.inc"); ?>
<script type="text/javascript">
$(document).ready(function() {
//elements
var progressbox = $('#progressbox'); //progress bar wrapper
var progressbar = $('#progressbar'); //progress bar element
var statustxt = $('#statustxt'); //status text element
var submitbutton = $("#SubmitButton"); //submit button
var myform = $("#UploadForm"); //upload form
var output = $("#output"); //ajax result output element
var completed = '0%'; //initial progressbar value
var FileInputsHolder = $('#AddFileInputBox'); //Element where additional file inputs are appended
var MaxFileInputs = 10; //Maximum number of file input boxes
// adding and removing file input box
var i = $("#AddFileInputBox div").size() + 1;
$("#AddMoreFileBox").click(function () {
event.returnValue = false;
if(i < MaxFileInputs)
{
$('<span><input type="file" id="fileInputBox" size="20" name="file[]" class="addedInput" value=""/><img src="img/close_icon.gif" border="0" /></span>').appendTo(FileInputsHolder);
i++;
}
return false;
});
$("body").on("click",".removeclass", function(e){
event.returnValue = false;
if( i > 1 ) {
$(this).parents('span').remove();i--;
}
});
$("#ShowForm").click(function () {
$("#uploaderform").slideToggle(); //Slide Toggle upload form on click
});
$(myform).ajaxForm({
beforeSend: function() { //brfore sending form
submitbutton.attr('disabled', ''); // disable upload button
statustxt.empty();
progressbox.show(); //show progressbar
progressbar.width(completed); //initial value 0% of progressbar
statustxt.html(completed); //set status text
statustxt.css('color','#000'); //initial color of status text
},
uploadProgress: function(event, position, total, percentComplete) { //on progress
progressbar.width(percentComplete + '%') //update progressbar percent complete
statustxt.html(percentComplete + '%'); //update status text
if(percentComplete>50)
{
statustxt.css('color','#fff'); //change status text to white after 50%
}else{
statustxt.css('color','#000');
}
},
complete: function(response) { // on complete
output.html(response.responseText); //update element with received data
myform.resetForm(); // reset form
submitbutton.removeAttr('disabled'); //enable submit button
progressbox.hide(); // hide progressbar
$("#uploaderform").slideUp(); // hide form after upload
}
});
});
</script>
</head>
<body>
<!-- property-images-page -->
<div data-role="page" id="property-details-page" class="globalpage" data-theme="<?php echo $_SESSION['login_data']['data_theme'];?>">
<script type="text/javascript"> function loadPage(url){document.location.href = url;};</script>
<!-- this .inc file contains 5 panels: login/forgot/register/reset/profile - <div>s with data-role="panel" are inside this file -->
<?php include("inc/pl_user_options_panel.inc"); ?>
<!-- /user-options-panel -->
<div data-role="panel" id="menu-panel" data-position="left" data-display="overlay">
<?php include("inc/pl_menu_panel.inc"); ?>
</div><!-- /menu-panel -->
<!-- top header, non-scrolling, shows two action buttons on sides & user data in the middle -->
<div data-role="header" data-position="fixed">
<?php include("inc/pl_data_role_header.inc"); ?>
</div> <!-- /header -->
<div role="main" class="ui-content">
<!-- page load popup handler -->
<?php include("inc/pl_popup_handler.inc"); ?>
<!-- scrolling page header with PeterLandlord logo -->
<?php include("inc/pl_page_header.inc");?>
<div class="formbox">
<?php # property selection form ?>
<form name="property-list-form" class="form" action="<?php echo $_SERVER['PHP_SELF'];?>?memid=<?php echo $member_id;?>" method="post">
<input type="hidden" name="property-list-form-submitted" value="1"/>
<div id="property-list-div" class="ui-field-contain">
<label for="property-list" class="<?php echo $message['msg_class'];?>"><b></label>
<?php
if ($my_post_list['property-list-form-submitted'] != "1" || sizeof($property_data) == 0) { # form not submitted
?>
<select name="property-list" id="property-list" data-native-menu="false" onChange="this.form.submit()">
<option value="choose-one" data-placeholder="true"><?php echo get_contents(600); ?></option>
<option value="0"><?php echo get_contents(601); ?></option>
<?php
} else { # form submitted
?>
<select name="property-list" id="property-list" data-native-menu="false" onChange="this.form.submit()">
<?php
if ($my_post_list['property-list'] != "0") { # an existing property selected
?>
<option value="<?php echo($my_post_list['property-list']);?>"><?php echo get_contents(602); ?>
<?php
echo
$property_data[0]['address_line'].", ".
$property_data[0]['address_locality'].", ".
$property_data[0]['address_state'].", ".
$property_data[0]['address_postcode'];
$skip_this_property = $property_data[0]['property_id'];
?>
</option>
<?php
} # /if an existing property selected
?>
<option value="0"><?php echo get_contents(601); ?></option>
<?php
} # /else
if ($my_post_list['property-list-form-submitted'] == "1" && $my_post_list['property-list'] == "0") { # add new property selected
# do nothing
} else { # display remaining properties
for ($i=0; $i<sizeof($property_list); $i++){
if ($property_list[$i]['property_id'] != $skip_this_property){ # Don't display selected property in the list - it is displayed above
?>
<option value="<?php echo $property_list[$i]['property_id'];?>">
<?php
echo
$property_list[$i]['address_line'].", ".
$property_list[$i]['address_locality'].", ".
$property_list[$i]['address_state'].", ".
$property_list[$i]['address_postcode'];
?>
</option>
<?php
} # /if add new property selected
} # /for
} # /if Don't display selected property
?>
</select>
</div> <!-- /property-list-div -->
</form> <!-- /property-list-form -->
</div> <!-- formbox for property selection-->
<?php
if ($property_selected){ # only show stored images & image upload form if property is selected
$sql = "SELECT * FROM " . DBPREFIX . "tbl_property_picture WHERE property_id = " . $property_id . " AND landlord_id = " . $member_id;
if (!($property_pics = sql_get_results_array($sql))){
$no_images = TRUE;
} else {
$no_images = FALSE;
}
?>
<div class="formbox">
<table align="center" border="0" cellpadding="4" cellspacing="0">
<tr>
<?php
if ($no_images){
?>
<td align="center"><img src="<?php echo PROPERTY_IMG_FOLDER ;?>noimages.png" alt="Thumbnail" width="100" height="100"></td>
<?php
} else {
for ($i=0; $i<sizeof($property_pics); $i++){
list($ImageWidth,$ImageHeight)=getimagesize($property_pics[$i]['picture_path'] . $property_pics[$i]['picture_filename']);
?>
<td align="center">
<img src="<?php echo $property_pics[$i]['picture_path'];?><?php echo $property_pics[$i]['picture_thumbname'];?>" alt="Thumbnail<?php echo $i;?>" height="100px" width="100px">
<br>
<form name="delete-form-<?php echo $i;?>" id="delete-form-<?php echo $i;?>" class="form" action="<?php echo $_SERVER['PHP_SELF'];?>?memid=<?php echo $member_id;?>&propid=<?php echo $property_id;?>" method="post">
<input type="hidden" name="remove-pic-form-submitted" value="1"/>
<input type="hidden" name="remove-this-path" value="<?php echo $property_pics[$i]['picture_path'];?>"/>
<input type="hidden" name="remove-this-file" value="<?php echo $property_pics[$i]['picture_filename'];?>"/>
</form>
</td>
<div data-role="popup" id="popup<?php echo $i;?>" class="ui-content" data-theme="<?php echo $_SESSION['login_data']['data_theme'];?>" style="max-width:1000px;">
Close
<p class="txtcopyright"><img src="<?php echo $property_pics[$i]['picture_path'];?><?php echo $property_pics[$i]['picture_filename'];?>" alt="Image<?php echo $i;?>" width="<?php echo $ImageWidth;?>" height="<?php echo $ImageHeight;?>"></p>
</div>
<?php
} # /for
} # /if no images
?>
</tr>
</table>
</div> <!-- formbox for image display-->
<div class="formbox">
<div id="uploaderform">
<form action="<?php echo LANDLORD_PROPERTY_IMAGES_PROCESS;?>?memid=<?php echo $member_id;?>&propid=<?php echo $property_id;?>" method="post" enctype="multipart/form-data" name="UploadForm" id="UploadForm">
<input type="hidden" name="max-to-upload" value="<?php echo 10 - sizeof($property_pics);?>"/>
<h1>Property image file upload</h1>
<p>Up to 10 images can by added with each image file size less than 1MB!</p>
<label>Images
<span class="small">Add More Images</span>
</label>
<div id="AddFileInputBox"><input id="fileInputBox" style="margin-bottom: 5px;" type="file" name="file[]"/></div>
<div class="sep_s"></div>
<button type="submit" class="button" id="SubmitButton">Upload</button>
<div id="progressbox"><div id="progressbar"></div ><div id="statustxt">0%</div ></div>
</form>
</div>
<div id="uploadResults">
<div align="center" style="margin:20px;">Toggle Upload Form</div>
<div id="output"></div>
</div>
</div> <!-- formbox -->
<?php
} # /if property selected
?>
<div class="formbox">
<hr>
<table class="fixed">
<tr>
<td><button onClick="loadPage('<?php echo LANDLORD_PROPERTY_DETAILS_PAGE;?>?memid=<?php echo $member_id;?>&propid=<?php echo $property_id;?>');" data-rel="external" data-theme="<?php echo $_SESSION['login_data']['data_theme'];?>" class="ui-btn ui-corner-all ui-icon-action"><?php echo get_contents(618)?></button></td>
<td>
<?php if ($property_selected){ # only show this button if property is selected ?>
<button type="reset" onClick="loadPage('<?php echo LANDLORD_PROPERTY_IMAGES_FORM;?>?memid=<?php echo $member_id;?>&propid=<?php echo $property_id;?>');" data-rel="external" data-theme="<?php echo $_SESSION['login_data']['data_theme'];?>" class="ui-btn ui-corner-all">Refresh View</button>
<?php }?>
</td>
<td><button onClick="loadPage('<?php echo LANDLORD_PROPERTY_FEATURES_PAGE;?>?memid=<?php echo $member_id;?>&propid=<?php echo $property_id;?>');" data-rel="external" data-theme="<?php echo $_SESSION['login_data']['data_theme'];?>" class="ui-btn ui-corner-all ui-icon-action"><?php echo get_contents(609)?></button></td>
</tr>
</table>
</div> <!-- formbox2 -->
</div> <!-- /role-main -->
<div data-role="footer" data-position="fixed">
<?php include("inc/pl_page_footer.inc"); ?>
</div> <!-- /footer -->
</div>
<!-- /property-images-page -->
</body>
</html>
Form processing code:
<?php
# pl_landlord_property_img_upl_proc.php
# Housekeeping
require_once ("lib/required.php");
$_SESSION['login_data'] = get_login_data();
# Login Protected Page - send them back home
if (!$_SESSION['login_data']['user_logged_in']){ # not logged in
$redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
header ( "Location: " . $redirect_url ); # must be logged in - send them to homepage
exit;
} elseif ($_SESSION['login_data']['group_title'] != 'Landlord'){ # logged in but not a Landlord
$redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
header ( "Location: " . $redirect_url ); # id mismatch - send them to homepage
exit;
} elseif (isset($_GET['memid']) && $_GET['memid'] != $_SESSION['login_data']['id']){ # logged in but memid in url is no match (typed in?)
$redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
header ( "Location: " . $redirect_url ); # id mismatch - send them to homepage
exit;
} elseif (isset($_GET['propid'])){
if (!$foo = sql_get_results_array("SELECT * FROM " . DBPREFIX . "tbl_property WHERE property_id = " . $_GET['propid'] . " AND landlord_id = " . $_GET['memid'])){ # logged in but propid in url is no match (typed in?)
$redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
header ( "Location: " . $redirect_url ); # id vs property mismatch - send them to homepage
exit;
} else {
# go through...
}
} else {
$redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
header ( "Location: " . $redirect_url ); # id mismatch - send them to homepage
exit;
}
# DO NOT include the code below on PayPalP Pay Subscription Page
# This code MUST BE INCLUDED on every Login Protected Page
# check subscription and send them to PayPal if not valid
if (!valid_subscription($_SESSION['login_data']['id'],$_SESSION['login_data']['membership_expiry'],$_SESSION['login_data']['grace_expiry'],$_SESSION['login_data']['subscription_fee'])){
$_SESSION['popup_msg_id'] = 37; # this is to popup a "final call" message
$redirect_url = "http://" . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . "/" . PAYPAL_PAY_SUBSCRIPTION_PAGE . "?memid=" . $_SESSION['login_data']['id'];
header ( "Location: " . $redirect_url ); # send them to referring page where resulting messages will be displayed
exit;
}
# DO NOT include the code above on PayPalP Pay Subscription Page
# End-of-Housekeeping
$member_id = $_GET['memid'];
$property_id = $_GET['propid'];
// If you face any errors, increase values of "post_max_size", "upload_max_filesize" and "memory_limit" as required in php.ini
//Some Settings
$ThumbSquareSize = 100; //Thumbnail will be 100x100
$BigImageMaxSize = 1000; //Image Maximum height or width
$ThumbPrefix = "thumb_"; //Normal thumb Prefix
$DestinationDirectory = PROPERTY_IMG_FOLDER; //Upload Directory ends with / (slash)
$Quality = 90;
//ini_set('memory_limit', '-1'); // maximum memory!
foreach($_FILES as $file){
// some information about image we need later.
$ImageName = $file['name'];
$ImageSize = $file['size'];
$TempSrc = $file['tmp_name'];
$ImageType = $file['type'];
if (is_array($ImageName)){
$c = count($ImageName);
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
if ($_POST['max-to-upload'] < 0){
$max_to_upload = 0;
} else {
$max_to_upload = $_POST['max-to-upload'];
}
for ($i=0; $i < $c; $i++){
if ($max_to_upload == 0){
echo '<div class="error">Only 10 files in total allowed!<br>Delete some to upload more.</div>';
break;
}
$max_to_upload--;
$processImage = true;
if(!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i])){
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>, may be file too big!</div>'; //output error
} else {
//Validate file + create image from uploaded file.
switch(strtolower($ImageType[$i]))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($TempSrc[$i]);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($TempSrc[$i]);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($TempSrc[$i]);
break;
default:
$processImage = false; //image format is not supported!
}
//get Image Size
list($CurWidth,$CurHeight)=getimagesize($TempSrc[$i]);
//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
$ImageExt = str_replace('.','',$ImageExt);
//Construct a new image name (with time plus counter) for our new image.
$NewImageName = $member_id . $property_id . time()+$i . '.' . $ImageExt;
//Set the Destination Image path with Random Name
$thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
//Resize image to our Specified Size by calling resizeImage function.
if($processImage && resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i])){
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType[$i])){
echo 'Error Creating thumbnail';
} # /if !cropImage
/*
At this point we have succesfully resized and created thumbnail image
We can render image to user's browser and/or store information in the database
*/
//Get New Image Size
list($ResizedWidth,$ResizedHeight)=getimagesize($DestRandImageName);
echo '<td align="center"><img src="' . PROPERTY_IMG_FOLDER . $ThumbPrefix.$NewImageName . '" alt="Thumbnail" height="100px" width="100px"></td>';
// Insert info into database table
$sql = "INSERT INTO " . DBPREFIX . "tbl_property_picture (property_id,landlord_id,picture_path,picture_filename,picture_thumbname)
VALUES (" . $property_id . "," . $member_id . ",'" . PROPERTY_IMG_FOLDER . "','" . $NewImageName . "','" . $ThumbPrefix.$NewImageName . "')";
if (!db($sql)){
echo '<div class="error">Error inserting into database</div>';
}
} else {
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>! Please check if file is supported</div>'; //output error
} # /if $processImage && resizeImage
} # /else (!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i]))
} # /for
echo '</tr>';
echo '</table>';
} # /is_array($ImageName
} # /foreach
// This function will proportionally resize image
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}
//Construct a proportional size of new image
$ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
$NewWidth = ceil($ImageScale*$CurWidth);
$NewHeight = ceil($ImageScale*$CurHeight);
if($CurWidth < $NewWidth || $CurHeight < $NewHeight)
{
$NewWidth = $CurWidth;
$NewHeight = $CurHeight;
}
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
// Resize Image
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
{
switch(strtolower($ImageType))
{
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}
return true;
}
}
//This function corps image to create exact square images, no matter what its original size!
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0){
return false;
}
//abeautifulsite.net has excellent article about "Cropping an Image to Make Square"
//http://www.abeautifulsite.net/blog/2009/08/cropping-an-image-to-make-square-thumbnails-in-php/
if($CurWidth>$CurHeight){
$y_offset = 0;
$x_offset = ($CurWidth - $CurHeight) / 2;
$square_size = $CurWidth - ($x_offset * 2);
} else {
$x_offset = 0;
$y_offset = ($CurHeight - $CurWidth) / 2;
$square_size = $CurHeight - ($y_offset * 2);
} # /else
$NewCanves = imagecreatetruecolor($iSize, $iSize);
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size)){
switch(strtolower($ImageType)){
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
} # /switch
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
} # /if is_resource
return true;
} # /if imagecopyresampled
} # /function
?>
Can somebody please point me towards a solution, thanks...
How can i add a file size beside my file names using PHP???
Currently Using This:
<?php
# Configuration
$show_path = 0; # Show local path.
$show_dotdirs = 1; # Show '.' and '..'.
$path = substr($_SERVER['SCRIPT_FILENAME'], 0,
strrpos($_SERVER['SCRIPT_FILENAME'], '/') + 1);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div id="menu">
<div id="menualign"><img src="images/home.png" onmouseover="src='images/homed.png'" onmouseout="src='images/home.png'"/><img src="images/moviesa.png"/><img src="images/tv.png" onmouseover="src='images/tvd.png'" onmouseout="src='images/tv.png'"/></div>
</div>
<div id="container">
<div id="fleft">
<table cellspacing="1">
<tr>
<th><?php if ($show_path == 1) { echo $path; } else { echo 'Current Movies'; } ?></th>
</tr>
<tr>
<td align="left"><?php
$dirs = array();
$files = array();
$dir = dir('../Movies/');
while ($entry = $dir->read()) {
if (($entry != '.') and (substr($entry, -4) != '.php')) {
if (is_dir($entry)) {
if (($entry != '..') or $show_dotdirs){
$dirs[] = $entry;
}
} else {
$files[] = $entry;
}
}
}
$dir->close();
sort($dirs);
foreach ($dirs as $dir) {
printf('<strong><</strong> %s <strong>></strong><br />' . "\n", $dir, $dir);
}
sort($files);
foreach ($files as $file) {
printf('<hr />%s<br />' . "\n", $file, $file);
}
?></td>
</tr>
</table>
</div>
<div id="fright">TEST
</div>
</div>
</body>
</html>
Which outputs as this: http://downunderpctech.com/output.png
I Would like to Add a section for Filesize
Probably using the same code but to collect filesize info as the Filename but in a new beside it
I am not too concerned about the Filesize output, but would prefer only to output KB
Thanks, Adam
You should use the function filesize on your $file variable.
And then you can output a human readable size with this little function:
function file_size($size)
{
$filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 Bytes';
}
You define the function before the # Configuration and then you call it in your foreach:
echo file_size(filesize('../Movies/'.$file));
You can write the file, then use the filesize function to get the file size and rename the file with the size in the file name.
http://php.net/manual/en/function.filesize.php
You can add this to your foreach
echo '<span>'.round(filesize ('../Movies/'.$file)/1024, 1).' Kb</span>';