I am new to PHP and trying to implement below functionality through code give
Functionality:
I have one Download button and upon clicking i should be able to download my .pdf file stored under htdocs-->xxfilename-->abc.pdf;
Code:
I am using below code in my xyz.php web page
<?php
$title = "Learning";
$content = '
<h3> Intro</h3>
<p>
Introduction goes here
</p>
<form action = "xyz.php" method = "post" name = "downloadform">
<input type="submit" value="Download" name="dwnld_file"/>
</form>
';
if (isset($_POST['dwnld_file'])) {
mysql_connect("localhost", "root", "");
mysql_select_db("PQR");
$res = mysql_query("Select * from tab1");
while ($row = mysql_fetch_array($res)) {
$file = '$row["col2"]';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $row["col2"] . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Content-Length:' . filesize($file));
readfile($file);
}
}
include 'Template.php';
?>
Error:
My pdf file is getting downloaded but upon opening it it says "failed to load pdf document"
Please help where i am wrong.
***Edit****
I tried different approach and my file is downloading but still it says "failed to load pdf document"
My other approach code is below
<form action = "xyz.php" method = "post" name = "downloadform">
<input type="submit" value="Download " name="dwnld_file"/>
</form>
<?php
if (isset($_POST['dwnld_file'])) {
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$res = mysql_query("Select * from tab1");
while ($row = mysql_fetch_array($res)) {
$file = $row["col1"];
echo $file;
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' .$file. '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Content-Length:' . filesize($file));
readfile('myfile/'.$file);
}
}
?>
Please tell me if i am doing anything wrong.
I implemented another solution after doing some more study and i was able to solve the problem.
Below is my code i used to implement.
Concept:
1) We can use HTML+JSP+PHP to get this functionality.
2) At HTML + JSP side we need to call eventListener to capture the event of clicking the button.
3) This event will redirect to the php page which will download the pdf file to your local computer.
Code Snippet:(here XYZ is the name of page where you want to show Download button)
in XYZ.php
<input type="button" id="btnshow" value="Download" name="dwnld" />
<script>
var btn = document.getElementById('btnshow');
btn.addEventListener('click', function () {
document.location.href = '<?php echo 'download.php'; ?>'
})
</script>
in download.php
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("database_name");
$res = mysql_query("Select * from table_name");
while ($row = mysql_fetch_array($res)) {
$file = 'Pdf_File/' . $row["Path"];
$filename = $row["Path"];
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
readfile($file);
}
?>
Hope it help some one out there newbie like me.
Happy Coding!
Related
Hello I'm doing my project and i want to ask just a simple question. Every time I go to that page it downloads automatically without getting inside on that page. When I click the button it automatically download the files. But I want to go that page and click a link before downloading it. Anyone help?
if(isset($_GET['profile']))
{
$id=$_GET['profile'];
$query = "SELECT * FROM profile_table WHERE id=?";
$stmt=$con->prepare($query);
$stmt->bind_param("i",$id);
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$vid = $row['id'];
$vfname = $row['fname'];
$vlname = $row['lname'];
$vmname = $row['mname'];
$vsex = $row['sex'];
$vage = $row['age'];
$vbday = $row['bday'];
$vbloodtype = $row['bloodtype'];
$vheight = $row['height'];
$vweight = $row['weight'];
$vreligion = $row['religion'];
$vcolorhair = $row['colorhair'];
$vdistmark = $row['distmark'];
$vmobile = $row['mobile'];
$vtin = $row['tin'];
$vphealth = $row['phealth'];
$vlegaldep = $row['legaldep'];
$vaddress = $row['address'];
$vtsize = $row['tsize'];
$vheadgear = $row['headgear'];
$vshoes = $row['shoes'];
$vuniform = $row['uniform'];
$vphoto = $row['photo'];
$vsoi = $row['soi'];
if (file_exists($vsoi)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($vsoi));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('documents/' . $row['name']));
readfile('documents/' . $row['name']);
}
}
I think the problem their is the file_exist in vsoi. And I dont know what to do or to change in my code. I appreciate all the answers. TIA!
I think first you need to understand what your code is trying to do, e-g
if (file_exists($vsoi)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($vsoi));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('documents/' . $row['name']));
readfile('documents/' . $row['name']);
}
Above code is used to when we want to force a browser to download a file.
But in your case you only want to download the file when the page is loaded and user clicks on a download link and then the download starts.
It can be achieved by just displaying a download link which will then execute the same code you wrote in the if statement.
So change your if statement as following and then write the same code which was in the if statement previously to that download link page.
if (file_exists($vsoi)) {
echo 'Download File
}
You can simply display a direct download link to the file as following.
<php
$download_link = 'https://yourdomain.com/files/sample.pdf';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Sample file</h1>
Download
</body>
</html>
I want to open the pdf file on my browser, but the file won't open. Chrome said "Failed to load PDF document". Please help.
Here's my code:
<?
include 'connection.php';
$query=mysql_query("SELECT * FROM book");
$p=mysql_fetch_array($query);
$ebook=$p['ebook'];
$title=$p['title'];
$file = "admin/upload/$ebook";
$filename = "$title";
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
#readfile($file);
?>
Any help is appreciated!
While I am not sure if this approach is applicable to your situation, if you are running jQuery this will accomplish what you are trying to do according to your question:
No db query is required... you can use glob('admin/upload/*')
PHP code:
echo '<select id="getPDF" name="getPDF">';
echo '<label>Select PDF</label>';
echo '<option value=""> Select PDF</option>';
foreach(glob('admin/upload/*') as $specific_pdf) {
$this_pdf = str_replace('.pdf','',basename($specific_pdf));
$this_pdf = ucwords(str_replace('-',' ',$this_content));
$this_pdf_url = $specific_pdf; # ADJUST THIS TO FULL URL TO PDF
echo '<option value="'.$this_pdf_url.'">'.$this_pdf.'</option>';
}
echo '</select>';
jQuery:
$(function() {
$( "#getPDF" ).change(function(){
var pdf_url = $(this).val();
window.open(pdf_url);
});
});
This will open the pdf in a new window/tab.
Is it possible to display the content of a php file to another php file?
I have here an example where in the PDF is displayed in a php file.
<?php
$file = 'path of your PDF file';
$filename = 'custom pdf file name'; /* Note: Always use .pdf at the end. */
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
?>
but when I tried to display a php file to another php file. Its not working.
<?php
$file = 'path to my php file';
$filename = 'custom pphp file name';
header('Content-type: text/html');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
?>
Can anyone tell me what I'm doing wrong?
Here is one way to display the contents of another .php file:
show_included_file.php
<?php
include ('file1.php');
?>
file1.php
<?php
echo "This is the included file.";
?>
when upon entering show_included_file.php in your web browser,
will echo This is the included file if that is the intented result.
From a form input
Another way of showing content taken from a form (POST method) variable is this:
From a form input, for example <input type="text" name="variable_1">
Now if the user enters Hello world in the field,
then in your handler $variable_1 = $_POST['variable_1'];
you could then do echo $variable_1; and it would echo Hello world
PHP handler
<?php
$variable_1 = $_POST['variable_1'];`
echo $variable_1;
?>
I hope this is what you are looking for.
<?php
echo htmlentities(file_get_contents("yourphpfile.php"));
i have a link pointing to a music file on my site, now the name of the file was hashed when it was uploaded so i want to use the original filename which i have stored in my database, I did some research and found this new 'download' attribute for the 'a' tag but that only works in later versions of firefox and chrome, it doesn't work in ie and also doesn't work with the download manager i use so i checked online and found out about headers which i then implemented. I now get the filename changed allright but the music file keeps on getting saved as a '11.35kb' filesize no matter the music file i try to download. This is my code:
if (isset($_REQUEST['download']))
{
$download_id = $_REQUEST['download'];
$db = new MysqliDatabase(ConnectionString);
$result = array();
$result = $db->query_one("SELECT TrackID, ma.ArtisteName, FeaturedArtistes,
mc.Category, TrackName
FROM `musictracks` mt
LEFT JOIN `musiccategories` mc
ON mt.CategoryID = mc.CategoryID
LEFT JOIN `musicartistes` ma
ON mt.ArtisteID = ma.ArtisteID
WHERE mt.TrackID = '$download_id';");
$filename = $result->TrackPath;
$outputfilename = $result->ArtisteName . ' ft. ' . $result->FeaturedArtistes . ' - ' . $result->TrackName . '.mp3';
header("Content-Type: audio/mpeg");
header("Content-Disposition: attachment; filename=\"" . basename($outputfilename) . "\";" );
header("Content-Transfer-Encoding: binary");
readfile("$filename");
}
And this is the download link:
<a href="<?php echo 'musicdownload.php?download='. $row->TrackID ?>" ><img src="images/download.png" alt="download" title="download" width="14" height="14" /></a>
My PHP is a bit rusty but I can think of one thing with your code, no content length header. Update your code to this and see if that works:
if (isset($_REQUEST['download'])) {
{
$download_id = $_REQUEST['download'];
// ...
$filename = $result->TrackPath;
$outputfilename = $result->ArtisteName . ' ft. ' . $result->FeaturedArtistes . ' - ' . $result->TrackName . '.mp3';
if (file_exists($filename)) {
header("Content-Type: audio/mpeg");
header("Content-Disposition: attachment; filename=\"" . basename($outputfilename) . "\";" );
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($filename));
ob_clean();
flush();
readfile($filename);
exit;
}
}
}
Note that we use flush(); to send the headers to the browser before we start downloading the actual file. And I also added an if (file_exists($filename)) to make sure we have a file to send. I'd recommend you put an else clause there to give you something that will show you if you don't have a file like you expect...
header("Content-Type: application/force-download");
header("Content-Type:audio/mpeg");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=".$file_name);
Please download your mp3 files using curl
Here is sample code for your reference
<?php
if(isset($_REQUEST['inputurl']) && $_REQUEST['inputurl']!="") {
$file = $_REQUEST['inputurl'];
header("Content-type: application/x-file-to-save");
header("Content-Disposition: attachment; filename=".basename($file));
readfile($file);
}
?>
<form name="from" method="post" action="">
<input name="inputurl" type="text" id="inputurl" value="" />
<input type="submit" name="Button1" value="Get File" id="Button1" />
</form>
may be it will help you.
i have written some code to select a row from a database and generate a link. the link is working ok but when i try to download the pdf i get this:
����)�^�z8��AQ�[��rr�=��73KJ��KR]�PD�H�����>3;,;~˾����ɫS����/ؤ���,������=??<8��3��L�����e�\I�aN�i.����A�.�����������|x�F�oN���1>MʙJ�#�Mz�'�N��?K��sx`D�5gژ�r&�N3��M�f����߱9<]R��,))�dj���D#k&O-�7V����M��d�I��HMN=��9��/�ubS���`189\S�����f�p_��T�T�&ӭ���E>�O�)eAœ
displaying on the page.
my code is:
<?php
$sql="SELECT * from table1 where invoice_number = '".$_GET["inv"]."' and sequence = '".$_GET["seq"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
if(mysql_num_rows($rs) > 0)
{
$result=mysql_fetch_array($rs);
$file = 'http://www.domain.co.uk/invoices/'.$result["pdf"].'';
$filename = 'Custom file name for the.pdf'; /* Note: Always use .pdf at the end. */
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
}
?>
any ideas how i can make it download the file rather than try and display it in the browser. please note, its a shared hosting server so i cannot make many changes on the actual server itself
Change the following:
header('Content-Disposition: inline; filename="' . $filename . '"');
to
header('Content-Disposition: attachment; filename="' . $filename . '"');