Jump to content

How to click on a file to download it, not open it


tekrscom

Recommended Posts

Hi, I was hoping someone could help me with how I would go about making a link or button that when clicked, it would download the file, not open it up in the browser... I'll post all of the code that I have so far to give a general idea of what I have.... after that I'll just post the relevant piece...

 

<?

function get_file_dir() {
    global $argv;
    return realpath($argv[0]);
}


$dirname = get_file_dir() . '/files/';


if(isset($_POST['upload']))	{
$changedDirname = $dirname . '/' . basename( $_FILES['uploaded']['name']) ;
    if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $changedDirname))	{
    $file_name = basename( $_FILES['uploaded']['name']);
    echo '<p><span style="color: #FF0000;">' . $file_name . ' was successfully uploaded.</span></p>';
    }
}

if(isset($_POST['DeleteFile']))	{
    $FileName = $dirname . $_POST['FileName'];
    unlink($FileName);
}


echo '
<br />
<form enctype="multipart/form-data" action="' . $_SERVER['php_self'] . '" method="POST">
<table style="width: 500px; margin-bottom: 50px;">
  <tr>
  	<td>Please choose a file:</td>
<td style="margin-left: 20px;"><input name="uploaded" type="file">
  	<td style="margin-left: 20px;"><input type="submit" name="upload" value="Upload"></td>
  </tr>
</table>
</form>';


$pattern="(\.jpg$)|(\.jpeg$)|(\.bmp$)|(\.gif$)|(\.png$)|(\.txt$)|(\.doc$)|(\.docx$)|(\.xls$)|(\.xlsx$)";
$files = array();
if($handle = opendir($dirname)) {
    echo '
    <form action="' . $_SERVER['php_self'] . '" method="post" id="submitform" name="submitform">
    <table style="width: 500px;">';
        	$counter = 0;
            while(false !== ($file = readdir($handle))) {
                if(eregi($pattern, $file)) {
                	$counter += 1;
                    if($counter % 2) {
                    echo '<tr bgcolor="#C0C0C0">';
                }
                else {
                    echo '<tr bgcolor="#FFFFFF">';
                }
                echo '
                    <td style="width: 100%;">' . $file . '</td>
                    <td style="padding-left: 20px; padding-right: 20px;"><a href="files/' . $file . '" target="_blank">View</a></td>
                    <td style="padding-left: 20px; padding-right: 20px;"><a href="files/' . $file . '">Download</a></td>
                    <td style="padding-left: 20px; padding-right: 20px;">
                        	<form action="' . $_SERVER['php_self'] . '" method="post">
                            	<input type="hidden" name="FileName" value="' . $file . '">
                            	<input type="submit" name="DeleteFile" value="Delete" onClick="return confirmDelete()">
                            </form>
                        </td>
                </tr>';
                }
            }
            echo '
    </table>
    </form>';
}

closedir($handle);

?>

 

Ok, so notice this piece of code at the bottom... There is a "View" link and a "Delete" button, in between them is where I'd like to have either a link or button so that the user can "Download" the file...

                    <td style="width: 100%;">' . $file . '</td>
                    <td style="padding-left: 20px; padding-right: 20px;"><a href="files/' . $file . '" target="_blank">View</a></td>
                    <td style="padding-left: 20px; padding-right: 20px;"><a href="files/' . $file . '">Download</a></td>
                    <td style="padding-left: 20px; padding-right: 20px;">
                        	<form action="' . $_SERVER['php_self'] . '" method="post">
                            	<input type="hidden" name="FileName" value="' . $file . '">
                            	<input type="submit" name="DeleteFile" value="Delete" onClick="return confirmDelete()">
                            </form>
                        </td>

 

Anyone have any ideas or pointers?

Link to comment
Share on other sites

In order to have a link that can be clicked and cause a file to be downloaded, you need to have a php file be the target of that link. This php file needs to output the correct 'Content-Disposition: attachment...' header (along with a few other headers), followed by the actual contents of the file.

 

If you search the Internet for "php force download" you will find examples of how to do this.

Link to comment
Share on other sites

You can't.  That's something built into the browser. You can offer the file up in a form that the browser will download, like a zip. But you can't make someone's browser download vs. view something like a .txt file or other file that the browser normally renders.

 

Well, that just sucks doesn't it... LOL... How about it is there a way that when a file is uploaded, it automatically zips it into a .zip format?

Link to comment
Share on other sites

In order to have a link that can be clicked and cause a file to be downloaded, you need to have a php file be the target of that link. This php file needs to output the correct 'Content-Disposition: attachment...' header (along with a few other headers), followed by the actual contents of the file.

 

If you search the Internet for "php force download" you will find examples of how to do this.

 

Ok, I will research that.

Link to comment
Share on other sites

Yes there are php functions that allow you to make zips.  Though I think PFM's method where you point to a script that dynamically outputs the content with headers would be the better choice.

 

Ok, thanks, I'm researching that now... Does sound like a good solution...

Link to comment
Share on other sites

Make sure that you validate that $filename or $file_extension in that code contains only what you want to allow to be downloaded or that code will allow someone to download your file that contains things like your database connection information...

 

Edit: And in fact because that script allows directory transversal (using ../) it will allow anyone to download any file that is present on your server that php has access to.

Link to comment
Share on other sites

Make sure that you validate that $filename or $file_extension in that code contains only what you want to allow to be downloaded or that code will allow someone to download your file that contains things like your database connection information...

 

Edit: And in fact because that script allows directory transversal (using ../) it will allow anyone to download any file that is present on your server that php has access to.

 

Yes, thank you... actually the pages is going to be password protected...

<?
session_start();
if(!$_SESSION['Condition'] == "Logged")	{
header("Location: index.php");
						}
elseif($_SESSION['Condition'] == "Logged")	{
?>

Link to comment
Share on other sites

okay but who has access to it if they login?  Random registered user? Admin who have server access anyway?  Depending on who is able to login and access the page, that might not be good enough.

 

Tis true... I was going to add a PermissionLevel column and pass as SESSION Var to check along with the CONDITION == Logged... but I didn't really consider anyone outside of those who would log in... Although I'm the admin for this little program for them... Here's what I had in mind... Do you think this would do the trick for the force-download.php page? Available permissionlevels would be view, viewdownload, and viewdownloaddelete

session_start();
if(!$_SESSION['Condition'] == "Logged" and !$_SESSION['PermissionLevel'] == "ViewDownload")	{
header("Location: login.php");
						}
elseif($_SESSION['Condition'] == "Logged" and $_SESSION['PermissionLevel'] == "ViewDownload")	{

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.