Providing download links in php - php

I recently uploaded videos,audios and pdf files using php to my multimedia folder on my server.
Basically its a site providing tutorials on various engineering subjects. I have kept folders like mechanics, computer programming etc and stored files in them accordingly, now i want to provide a link to the files using hyperlinks so that user can view them.
How can i achieve this?

To show files to user use this.
$dir = '/mechanics';
$files = scandir($dir);
You will get the files array. And you can acces them as files[0], files[1 ].
Now if you want to give them facility to download then use this.
<?php
header('Content-disposition: attachment; filename=huge_document.pdf');
header('Content-type: application/pdf');
readfile('huge_document.pdf');
?>
For more detail see this

The easiest way to do this is to enable directory listing, by putting Options +Indexes in an .htaccess file. This way, all files in that directory will be shown by your web server as a listing.
You could also look at dir() or DirectoryIterator.

http://www.php.net/scandir
with this function you can scan all files and directories in a folder. with the return value you can generate in a for-loop hyperlinks

Well, I believe there are two approaches.
One is create a loop for respected directories:
<? php
$yourDirectory = "../path/to/your/directory/";
if (is_dir($yourDirectory )) {
if ($reading = opendir($yourDirectory)){
while (($files = readdir($reading)) !== false){
if( $files != "." && $files != ".." && $files[0] != "." ){
echo "<a href='fancybox'><img src='$files' alt='' /></a>";
}
}
closedir($reading);
}
}
?>
by this way you can view your videos in Fancybox. Of course you need to set Fancybox plugin first.
Other way is using FlowPlayer to play content in your pages.
Hope this helps.

Related

Dictate how specific file types open with PHP

sorry if this has been asked already, couldn't find anything on it.
I need a code that will force how certain filetypes open.
For example, I have an Apache directory listing that displays a bunch of .mp4 files. I have a custom template set up with it, and I have an iframe on the page.
What I want is so that only .mp4 files open in the iframe, but so that all other extensions open normally.
I tried using the simple: base target="iframe_content"
but that will make EVERY link open in the iframe.
Specifying: target="_parent"
on all my navigation urls is not an option, because I need people to be able to navigate through folders within the listing as well, and open other filetypes in the listing normally.
I'm thinking I need some sort of If/Else statement, but I can't figure out how to do it.
Sorry if this is a fairly obvious answer, I'm somewhat newb-ish at PHP.
Thanks
You just need to iterate through your files, and check, is the extension is mp4 or not. If yes, then open it in the iframe, if no, then open it normally:
$dir = '.'; //The dir what you want to list
$dirContent = scandir($dir);
foreach ($dirContent as $entry) {
if (!in_array($entry, array('.', '..')) && !is_dir($entry)) {
$pathInfo = pathinfo($entry);
if ($pathInfo['extension'] == 'mp4') {
//Open in iframe where the id of iframe is: myIframe
?>
<?php echo $entry; ?><br />
<?php
} else {
//Open normally
?>
<?php echo $entry; ?><br />
<?php
}
}
}

How to access files in data folder in zend framework?

currently i am working on zf2. Right now i have to give download option to download pdf files.i have stored all the pdf files in data directory.How can i specify link to that pdf files from .phtml file?
thanks in advance.
A user will never gain direct access to your /data directory. This would be just not that good. But you can easily write yourself a download-script.php or the likes that will hand out the content of this directory to your users.
If you take a look at the first six lines of public/index.php you'll see the following:
<?php
/**
* This makes our life easier when dealing with paths. Everything is relative
* to the application root now.
*/
chdir(dirname(__DIR__));
With this in mind, you know that from PHP's side of things the access to anything inside the data directory is as simple as data/file.pdf
You'd always want to write yourself some sort of download-logger. Write yourself a controller. Have an action inside of that controller probably called something like download or anything like that. That action should have one parameter filename.
All that this action does is to check if filename exists file_exists('data/'.$filename) and if it exists, you simply deliver this file to your users. An example mix or zf2 and native php could be:
public function downloadAction()
{
$filename = str_replace('..', '', $this->params('filename'));
$file = 'data/' . $filename;
if (false === file_exists($file)) {
return $this->redirect('routename-file-does-not-exist');
}
$filetype = finfo_file($file);
header("Content-Type: {$filetype}");
header("Content-Disposition: attachment; filename=\"{$filename}\"");
readfile($file);
// Do some DB or File-Increment on filename download counter
exit();
}
This is not clean ZF2 but i'm lazy right now. It may be much much more ideal to use a proper Response Object and do the File-Handling there!
Important Update this thing was actually quite insecure, too. You need to disallow parent-folders. You wouldn't wanna have this guy do something outside of the data/download directory like
`http://domain.com/download/../config/autoload/db.local.php`
If I'm not totally mistaken, simply replacing all occurences of double-dots should be enough...
I would create a symbolic link in public directory for PDF files in data folder.
For example:
ln -s /your/project/data/pdfdir /your/project/public/pdf
and create links something like
File.pdf
Borrowing Sam's code, here's what it looks like in ZF2 syntax.
public function downloadAction()
{
$filename = str_replace('..', '', $this->params('filename'));
$file = 'data/' . $filename;
if (false === file_exists($file)) {
return $this->redirect('routename-file-does-not-exist');
}
$filetype = finfo_file($file);
$response = new \Zend\Http\Response\Stream();
$response->getHeaders()->addHeaders(array(
'Content-Type' => $filetype,
'Content-Disposition' => "attachement; filename=\"$filename\""
));
$response->setStream(fopen($wpFilePath, 'r'));
return $response;
}

Is there any quick way to add same php file to many folders?

I have a index.php file. In my root folder, there are approximately 200 folders. I want to add index.php file to all 200 folder. Instead of copy-paste, is there a quick way to add it?
There is a quick way to do this but I feel there are better ways to do what you need.
Is the index file purely to stop people seeing folders?
If so try putting IndexIgnore * into your .htaccess
More info here: http://www.javascriptkit.com/howto/htaccess11.shtml
Well, like all the other people have already said, there is probably something wrong in your design. If you want to make sure people can't access it, just use Apache to do that, not PHP. If you still feel the need to add an index.php file to every single directory, here's how:
<?php
$content = 'Your content';
$files = glob( './*' );
foreach( $files as $file ) {
if( is_dir( $file ) && is_writable( $file ) ) {
file_put_contents( $file . '/index.php', $content );
}
}
Use this function:
function putindexfiles($putfile,$start=""){
$files = glob($start.'*',GLOB_MARK);
foreach($files as $file){
if(is_dir($file)){
copy($putfile,$file.'index.php');
putindexfiles($putfile,$file);
}
}
}
This function use recursion so all sub-directories also get affected.
and $putfile is the path to the file whose contents are to be placed in index.php of every folder. this script creates all index.php automatically in each folder.
while using the function you dont need to provide the $start as this is default parameter is the directory in which the script is placed.
Enjoy

What is the best method to read a folder sub directory and files in those sub directory?

I have a image folder which contains sub directory for each album of images like
Images
Images/Album1
Images/Album2
in PHP file
I create a link for each album using a thumbnail for the album using GLOB to read all folders under Images
$dir=glob('images/*');
$dir_listing=array();
foreach($dir as $list)
{
if(is_dir($list))
$dir_listing[]= (basename($list));
}
$thumbs=glob('images/thumbnails/*');
$count=0;
foreach($thumbs as $th )
{
echo" $dir_listing <br/>";
echo"<a href='$dir_listing[$count]' ><img src='$th' /> </a>";
$count++;
}
I use Glob on each page load to get list of directories and images.
I want to know if there is a better way of doing this.
I also want to get list of all files and folder based on there Last Modified time in descending Order {Latest files and Folders first}.
Is using Glob correct or should we save the sub-directories and files in text file and read from it?
I can't tell you for sure if there is a better way of doing this, but your code should definitely work.
Using glob() is the right approach only if you have a relatively low number of files in the directory (<10,000), because if yoy have a lot of files then you could get a "Allowed memory size of XYZ bytes exhausted ..." error. In this case, it is best to use opendir();
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
// do something with the file
// note that '.' and '..' is returned even
}
closedir($handle);
Finally, use the flag GLOB_NOSORT on glob() so the end result is just like its listed on the directory in case that may be used to give you results based on last modified date.
Hope this helps.

php directory content list above root

how do i use php to access the directory above my site root, i need to specifically go up one directory and show contents to the user so they can pick from a couple different directories on the same level as public_html, navigate into them, and when clicking on a file serve it up? server is unix/apache
zipsanimspublic_htmlThank you ahead.
David
i found that if they know the file name it can be served to them by this... named image.php
then image.php?file=imagename.jpg
Thank you!
<?php
$file = $_GET['file'];
$fileDir = '/path/to/files/';
if (file_exists($fileDir . $file))
{
// Note: You should probably do some more checks
// on the filetype, size, etc.
$contents = file_get_contents($fileDir . $file);
// Note: You should probably implement some kind
// of check on filetype
header('Content-type: image/jpeg');
echo $contents;
}
You go up one directory using the .. link. Example:
<?php include("../foo.bar"); ?>
Note that if you're on shared hosting, there's a good chance that the server won't let you do this.

Categories