How to make a button to start a configured file download in PHP?

Hi Experts!

I'm facing difficulties to make a form with a button to fire a download.
This form must send a parametrized name of a file to be downloaded.

            ....
               <tr>
                    <td class="tg-yw4l">
                    <!-- The point where I intend to fire the download  -->
                   <form action="download_pdf_publicacoes.php" method="post">

                  // This is the file to be downloaded:
                  <?php "base_url("."cesanshome/carregando_arquivo/".$idpublicacoes.")" ?>

                    // Here:  How to configure it to send to the other page?

                    <input type="submit" name="download_pdf" value="PDF"/>
 

                   </form>
                    </td>
              </tr>

...

Open in new window



The download_pdf_publicacoes.php
 <?php

                // How the $filename name must be received here?

	$post = filter_input(INPUT_POST,"download_pdf");
 

    if ($post)
	{
		$filename = ???;
		header("Content-Type: application/octet-stream");
		header("Content-Length: " . filesize($filename));
		header("Content-Disposition: attachment; filename=" . basename($filename));
		readfile($filename);
	}
?>

Open in new window


Thanks in advance!
Eduardo FuerteAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
I can show you how to force a file download.  This seems to work correctly in every browser.  Perhaps you can change the "link" to a "button" and get what you need.
<?php // demo/force_download.php

/**
 * Show how to force a file download
 *
 * Choose a file to download, either via a hard-coded file path
 * or via a URL parameter like this
 *
 * path/to/demo/force_download.php?url=path/to/file.txt
 *
 * If you wanted to use the URL parameter, you might want to
 * (1) Secure the script with password protection
 * (2) replace the $url variable with something like this:
 * $url = $_GET['url'];
 *
 * If you use the URL parameter, be careful that the script
 * does not expose sensitive data on your server!
 */
error_reporting(E_ALL);


// WHAT FILE DO WE WANT TO DOWNLOAD?
$url = "http://www.IcoNoun.com/demo/short_text_file.txt";


// USE CASE
force_download($url);


// FUNCTION TO FORCE A DOWNLOAD FROM A FILE
function force_download($url, $filename=NULL)
{
    // GET THE DOWNLOAD FILE NAME
    if (empty($filename)) $filename = basename($url);

    // GET LENGTH AND FILE RESOURCE POINTER
    $hdr = get_headers($url, TRUE);
    $len = trim($hdr['Content-Length']);
    $fpr = fopen($url,'rb');

    // ON SUCCESS
    if ($fpr)
    {
        // THESE HEADERS ARE USED ON ALL BROWSERS
        header("Content-Type: application-x/force-download");
        header("Content-Disposition: attachment; filename=$filename");
        header("Content-length: $len");
        header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
        header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");

        // THIS HEADER MUST BE OMITTED FOR IE 6+
        if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE '))
        {
            header("Cache-Control: no-cache, must-revalidate");
        }

        // THIS IS THE LAST HEADER
        header("Pragma: no-cache");

        // FLUSH THE HEADERS TO THE BROWSER
        flush();

        // WRITE THE FILE
        fpassthru($fpr);
    }

    // ERROR
    else
    {
        trigger_error("Unable to open $url", E_USER_ERROR);
    }
}

Open in new window

0
Eduardo FuerteAuthor Commented:
Hello

Could you give me just one more help?

Using your function in a button.
This piece of code doesn't  work out, what's wrong and what coudl be done to fix it?

   <form action="force_download(<?php echo base_url("cesanshome/carregando_arquivo/$idpublicacoes)"); ?>" method="post">
                        <input type="submit" value="PDF"/>
                    </form>

Open in new window



img01
To make it more difficult this Project uses CodeIgniter... so the localization is much more complex.
0
Ray PaseurCommented:
Sure!  Here is the file that causes the download to occur.
<?php // demo/temp_efuerte_download.php

/**
 * Show how to force a file download
 *
 * Choose a file to download, either via a hard-coded file path
 * or via a URL parameter like this
 *
 * path/to/demo/force_download.php?url=path/to/file.txt
 *
 * If you wanted to use the URL parameter, you might want to
 * (1) Secure the script with password protection
 * (2) replace the $url variable with something like this:
 * $url = $_GET['url'];
 *
 * If you use the URL parameter, be careful that the script
 * does not expose sensitive data on your server!
 */
error_reporting(E_ALL);


// WHAT FILE DO WE WANT TO DOWNLOAD?
$url = "http://www.IcoNoun.com/demo/short_text_file.txt";


// USE CASE
force_download($url);


// FUNCTION TO FORCE A DOWNLOAD FROM A FILE
function force_download($url, $filename=NULL)
{
    // GET THE DOWNLOAD FILE NAME
    if (empty($filename)) $filename = basename($url);

    // GET LENGTH AND FILE RESOURCE POINTER
    $hdr = get_headers($url, TRUE);
    $len = trim($hdr['Content-Length']);
    $fpr = fopen($url,'rb');

    // ON SUCCESS
    if ($fpr)
    {
        // THESE HEADERS ARE USED ON ALL BROWSERS
        header("Content-Type: application-x/force-download");
        header("Content-Disposition: attachment; filename=$filename");
        header("Content-length: $len");
        header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
        header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");

        // THIS HEADER MUST BE OMITTED FOR IE 6+
        if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE '))
        {
            header("Cache-Control: no-cache, must-revalidate");
        }

        // THIS IS THE LAST HEADER
        header("Pragma: no-cache");

        // FLUSH THE HEADERS TO THE BROWSER
        flush();

        // WRITE THE FILE
        fpassthru($fpr);
    }

    // ERROR
    else
    {
        trigger_error("Unable to open $url", E_USER_ERROR);
    }
}

Open in new window

And here is the file that creates the button and summons the download file.
<?php // demo/temp_efuerte_form.php

/**
 * Call the download script with a form
 */
error_reporting(E_ALL);


$html = <<<EOD
<style type="text/css">
form input {
    background-color:orange;
    border:black 2 px solid;
    width: 9em;
    height: 9em;
}
</style>

<form action="http://iconoun.com/demo/temp_efuerte_download.php">
<input type="submit" />
</form>
EOD;

echo $html;

Open in new window

HTH, ~Ray
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Eduardo FuerteAuthor Commented:
Thank you very much for the assistance, Ray!
0
Ray PaseurCommented:
Glad to help!  Best of luck with the project, ~Ray
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.