• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 209
  • Last Modified:

How do I open documents (.txt, .doc, .pdf, etc.) through their links that I have retrieved in a browser?

Hi!

I'm working on a basic document management system using PHP / MYSQL.

I have the files uploaded to a folder on the server. I have also added a reference to each file in a mySql database at the time of upload. Through a web browser, I can successfully display the filename as a link to the file in the folder (that I had uploaded the files into which I have named "uploaded_files").

My PROBLEM is that when I click the link (filename) it takes me to the "uploaded_files" folder through the browser AND DOES NOT OPEN THE FILE.

WHAT I REQUIRE: is that when I click the filename link (for example: name.txt) It should open the file through the associated application on the Operating System. HOW DO I DO THAT?


// This is the code for reference purposes 
$result = mysql_query("Select * from xyz") or die(mysql_error());

while ($row = mysql_fetch_array($result)){
echo $row['author_name'];
echo ":";
echo "<a href=$FileName?file_name=";
echo $row['file_name'];
echo ">'".$row['file_name']."'</a>";
echo "<br>";
}

Open in new window

0
786aslamkhan
Asked:
786aslamkhan
  • 6
  • 3
1 Solution
 
Loganathan NatarajanLAMP DeveloperCommented:
0
 
786aslamkhanAuthor Commented:
Thanks a ton loqudotcom for reading and responding to my question.
I know that this can solve my problem but I don't know how to apply it. I'm still fiddling around... 
Thanks for now!

<?php
// This is the example from the link that you provided loqudotcom - Thanks!
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

Open in new window

0
 
786aslamkhanAuthor Commented:
Thanks loqudotcom!

It works but not in the way that I require and I'm sure it requires some tweaks!
when I click on the filename link, it takes me to the directory of my webserver , and from there, when I select and click the link, it opens.

I need it to avoid going to the folder on my webserver- obviously and for so many reasons...

Please could I request you to have a look at the code snippet that I have attached to see what I have done wrong- I HAVE DONE SOMETHING WRONG!!!! Can you please help me????
Thanks a lot.

<?php
//some code above this

$result = mysql_query("Select * from xyz") or die(mysql_error());

while ($row = mysql_fetch_array($result)){

$file = $row['file_name'];

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}

echo $row['author_name'];
echo ":";
//echo $row['file_name'];
//echo "<br>";
echo "&nbsp;";
echo "<a href=$FileName?readfile($file)";
//echo $row['file_name'];
echo ">'".$row['file_name']."'</a>";
echo "<br>";
}
?>

Open in new window

0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
786aslamkhanAuthor Commented:

<?php
// I think I should have included these lines as the problem may be there
$FileDir = "../dms/xyz/";
$FileName = $FileDir . $file_name;

Open in new window

0
 
adbrettCommented:

<?php

// right at the top:
if(!empty($_GET['file'])) {
	if (file_exists('myfiles/' . $_GET['file'])) { // this is horribly insecure, please change this later
		header('Content-Description: File Transfer');
		header('Content-Type: application/octet-stream');
		header('Content-Disposition: attachment; filename='.basename($file));
		header('Content-Transfer-Encoding: binary');
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
		header('Content-Length: ' . filesize($file));
		ob_clean();
		flush();
		readfile($file);
		exit;
	}
}

//some code above this

$result = mysql_query("Select * from xyz") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
	$file = $row['file_name'];
	echo $row['author_name'];
	echo ":";
	echo "&nbsp;";
	echo "<a href=\"{$_SERVER['PHP_SELF']}?file={$file}\">{$row['file_name']}</a>";
	echo "<br>";
}
?>

Open in new window

0
 
786aslamkhanAuthor Commented:
Thanks a lot adbrett for your solution. I've been trying to implement it to work but have not yet been successful. I'm still trying. I have not noticed the advantage or difference of placing the readfile() code "Right at the top" .
I still am not getting the file to open without going through the directory on the server and AGAIN SELECTING / CLICKING THE REQUIRED FILE.
I'm sorry but I have to say that I have tried but am not able to understand or implement the attached line either as using it makes no noticeable difference that I can see. Thanks a lot for the time being.

<?php
echo "<a href=\"{$_SERVER['PHP_SELF']}?file={$file}\">{$row['file_name']}</a>";
?>

Open in new window

0
 
adbrettCommented:
1) The read file code should be at the top because it is sending browser headers which should be before all other output to work

2) This is required for the soltuion to work as you want.  All you are doing your way is linking to the file, and not even correctly, which is why it just links to the directory.

My way is passing the filename as a variable back to the script and the script is forcing a download - which is what you want to do.

If you implement the soltuion as I posted it will work as you want, if you don't without a better reason than "i don't want to" I can't help you further.
0
 
786aslamkhanAuthor Commented:
Hi adbrett!
First of all please excuse me for not responding earlier as I was kept from doing so at work- I'm very sorry for the delayed response.
I think that I have unwittingly given you the wrong impression for which too, I profusely apologize.
The wrong impression is that I do not want to implement the solution as you posted... In fact I'm trying to learn from you and I have been trying to implement the code and have somehow not been able to accomplish what is desired.
Thank you for the excellent explanation of placing the readfile() code at the very top.... passing the headers.... yes that does indeed force the open / download dialog box (without going to the folder on my server)- 
I think that I may have some path issue (which I am exhausted trying to solve) as when I click the open / download button ,,, I get the download dialog with the correct application selected but the download shows 0 kb. The file is not present in the temp file of my browser where it had downloaded neither is it saved where I specified it to be.
I have attached the code for your perusal. I have been trying to implement it just in the way you have advised.
Thanks for the explanation once again and the solution... please do help me and see where I have gone wrong.

<?php
if(!empty($_GET['file'])) {
        if (file_exists('uploaded_files/' . $_GET['file'])) { // this is horribly insecure, please change this later
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename='.basename($file));
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Content-Length: ' . filesize($file));
                ob_clean();
                flush();
                readfile($file);
                exit;
        }
}

$link = mysql_connect("localhost", "xxxxxxx", "xxxxxxxxxxx")
  or die("Could not connect: " . msql_error());
mysql_select_db("xxxxxxx", $link) 
  or die (mysql_error()); 
/*  
$FileDir = "../xxxxxx/uploaded_files/";
$FileName = $FileDir . $file_name;
*/  
$result = mysql_query("Select * from xyz") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
        $file = $row['file_name'];
        echo $row['author_name'];
        echo ":";
        echo "&nbsp;";
        echo "<a href=\"{$_SERVER['PHP_SELF']}?file={$file}\"> {$row['file_name']}</a>";

        echo "<br>";
}

?>

Open in new window

0
 
adbrettCommented:
If you see lines 5, 11, and 14, you are using the variable $file which hasn't been set yet - that may be my fault for not including it in my original solution, sorry.  This means you are trying to get the filename of an empty string (which doesn't exist), then the filesize (which is 0), and then calling readfile to get it's contents (which is nothing).

If you replace lines 1-17 with the attached code this should work
<?php
if(!empty($_GET['file'])) {
        $dir = "../xxxxxx/uploaded_files/";
        $file = $dir . $_GET['file'];

        if (file_exists($file)) { // this is horribly insecure, please change this later
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename='.basename($file));
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Content-Length: ' . filesize($file));
                ob_clean();
                flush();
                readfile($file);
                exit;
        }
}

Open in new window

0
 
786aslamkhanAuthor Commented:
Thanks a ton adbrett! the solution works splendidly!
0

Featured Post

2018 Annual Membership Survey

Here at Experts Exchange, we strive to give members the best experience. Help us improve the site by taking this survey today! (Bonus: Be entered to win a great tech prize for participating!)

  • 6
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now