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; ?>
Related
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';
}
?>
When I use session_start() in my code i have the session setup properly and when I run the code and log in it keeps me logged in and everything works properly, but when I add HTML underneath the PHP code located at the top of the page and refresh it (while logged in) it logged me out?
My Code Without HTML
Core file
ob_start();
session_start();
function loggedin() {
if(isset($_SESSION['user_id'])&&!empty($_SESSION['user_id'])) {
return true;
} else {
return false;
}
}
require 'connect.inc.php';
require 'core.php';
include 'main_login.inc.php';
if (loggedin()) {
$dir = $user_name;
if($handle = #opendir($dir)) {
if($handle2 = #opendir($dir.'/docs')){
//If Logged In And Users File Exists: Load Page
}
} else {
// If Users File Does Not Exist: Create User File
#mkdir($user_name, 0755, true);
// Create Docs
#mkdir($user_name.'/docs', 0755, true);
}
} else {
// If User Is Not Logged: Redirect To Jamie Co Home
#header('Location: http://www.jamieco.ca');
}
?>
My code with HTML (Non-working code)
<?php
require_once 'connect.inc.php';
require_once 'core.php';
include 'main_login.inc.php';
if (loggedin()) {
$dir = $user_name;
if($handle = #opendir($dir)) {
if($handle2 = #opendir($dir.'/docs')){
//If Logged In And Users File Exists: Load Page
}
} else {
// If Users File Does Not Exist: Create User File
#mkdir($user_name, 0755, true);
// Create Docs
#mkdir($user_name.'/docs', 0755, true);
}
} else {
// If User Is Not Logged: Redirect To Jamie Co Home
#header('Location: #');
}
?>
<!DOCTYPE html>
<html>
<body>
<header>
<nav>
<ul>
<li>Home</li>
<li>Clients</li>
<li>Sign In</li>
<li>Contact</li>
</ul>
</nav>
</header>
<div id = "clear" />
<div id = "big_wrapper">
<div id = "wrapper">
<br><br>
<!-- Logged In Stuff Goes Here -->
<div id = "user_options">
<ul>
<li><?php echo 'Welcome, '.$first_name.' '.$last_name.'<br><br>'; ?></li>
<li>Logout</li>
</ul>
</div>
<?php echo 'Welcome Back '.$first_name; ?>
<br><br>
<table border = "1" cellspacing = "5" id = "files">
<tr><td colspan = "7">File Handling</td></tr>
<tr>
<td>File Name:</td>
<td>File Size:</td>
<td>File Type:</td>
<td>Security Level:</td>
<td colspan = "3">Actions:</td>
</tr>
<?php
$dir = $user_name.'/docs/';
if($handle = #opendir($dir)) {
while($file = #readdir($handle)) {
if($file!='.'&&$file!='..') {
echo '<tr><td>'.$file.'</td>';
$name = $dir.$file;
$size = filesize($dir.$file);
$type = substr($name, strrpos($name, '.')+1);
echo '<td>'.$size.' Bytes'.'</td>';
echo '<td>'.$type.'</td>';
echo '<td>'.$file_grade.'</td>';
echo '<td>'.'Download'.'</td>';
echo '<td>'.'Rename'.'</td>';
echo '<td>'.'Delete'.'</td>';
}
}
}
?>
</tr>
</table>
<br><br>
<!-- Stuff Here -->
<br><br>
</div>
</div>
</body>
</html>
Problem Solved. I changed the session to a token, not sure why this works but it does!
I am not able to display the content of the text file within the same webpage.The code is below (called display.php file)
<html>
<head>
<link rel="icon" type="image/png" href="logo.png">
<body>
<?php
$selectedfile = #$_POST['file_to_be_displayed'];
$content = file($selectedfile);
$data = implode("<br>",$content);
echo $data;
?>
<?php
$dirname = "<directory to be scanned for files>";
$dir = opendir($dirname);
echo '<form name="displayfile" action="output.php" method="POST">';
echo '<select name="file_to_be_displayed">';
echo '<option value="">Select File</option>';
while(false != ($file = readdir($dir)))
{
if((($file != ".") and ($file != "..") and (($file != "store_show_commands_switches.tcl" and $file != "switches.txt"))and (($file != "store_show_commands_routers.tcl" and $file != "routers.txt"))and (($file != "store_show_commands_firewalls.tcl" and $file != "firewalls.txt"))))
{
echo "<option value=".$file.">$file</option>";
}
}
echo '</select>';
echo '<input type="submit" value="display content of file" />';
echo '</form>';
?>
</body>
</html>
output.php
<html>
<body>
<?php
$myFile =$_POST['file_to_be_displayed'];
$file = file_get_contents ("$myFile");
Echo $file;
?>
</body>
</html>
The display.php will scan the txt files within the directory and display them within a dropdown menu with a button next to it to display file selected. However, once I click the button I get a blank page with no result(it should display the content of the txt file)
Is there a way to fix this or -even better- is there a way to display the content of the file within the same display.php (I think it can be done with ajax but not sure how)
Thanks
Pantelis
The template file is .php and has those placeholders:
<ul>
<li><a href='a.php'>{{placeholder1}}</a></li>
{{placeholder2}}
</ul>
And this is the code which replaces them:
$file = file_get_contents($template);
$file = str_ireplace('{{placeholder1}}', count_messages(), $file);
$file = str_ireplace('{{placeholder2}}', show_link(), $file);
print $file;
Functions are nothing special ('functions.php'):
function count_messages()
{
ob_start();
if (preg_match('/^[A-Za-z0-9_]{3,40}$/', $_SESSION['username']))
{
$table = $_SESSION['username'];
}
else
{
header('Location: login.php');
exit();
}
try
{
$db = new PDO('sqlite:site.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $db->prepare("SELECT Count(*) FROM `$table` WHERE `isRead` = '0'");
$result->execute();
$count = $result->fetchColumn();
if ($count > 0)
{
print "<b style='color: #00ff00; text-decoration: blink;'>$count</b> <b style='font-size: 6pt; text-decoration: blink; text-transform: uppercase;'>unread</b> ";
}
unset($db);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
ob_end_flush();
}
function show_link()
{
ob_start();
if ($_SESSION['username'] == "admin")
{
print "<li><a href='admin_panel.php' target='main_iframe'><b style='color: #ffff00;'>Admin Panel</b></a></li>;
}
ob_end_flush();
}
First counts the messages and outputs number with some styling, the second adds to the menu 'Admin Panel' link if the username is 'admin.
The problems are (no errors in php log):
count_messages() works but outputs 'n unread' above all elements on the page.
show_link() doesn't output the link.
The file $template is readable and named template.php:
<?php
session_start();
if(!$_SESSION['islogged'])
{
header('Location: login.php');
exit();
}
require_once('functions.php');
?>
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="description" content="Documents" />
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Documents</title>
</head>
<body>
<div id="main">
<iframe src="documents.php" name="main_iframe" id="main_iframe">
</iframe>
</div>
<div id="main_menu">
<ul id="menu_list">
<li>{{placeholder1}}Messages</li>
{{placeholder2}}
<li>Log out</li>
</ul>
</div>
</body>
</html>
The index.php:
<?php
session_start();
require_once('functions.php');
$template = 'template.php';
if (file_exists($template))
{
if (is_readable($template))
{
if(!$_SESSION['islogged'])
{
session_destroy();
header('Location: login.php');
exit();
}
}
else
{
print "Template file cannot be opened";
}
}
else
{
print "Template file doesn't exist";
}
$file = file_get_contents($template);
$file = str_ireplace('{{placeholder1}}', count_messages(), $file);
$file = str_ireplace('{{placeholder2}}', show_link(), $file);
print $file;
?>
I hope someone here knows what causes this behaviour ...
You are using the functions’ result values in the str_ireplace function call but the functions don’t return anything, they are missing a return statement.
You probably meant to use return ob_get_clean(); instead of ob_end_flush(); in your code.
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>';