Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Smile restrict direct download of a file

    Can i restrict a file to direct download.suppose in my domain i am having a upload folder in which i am having a exam.pdf file then it should not be downloaded by accessing url http://www.mydomain.com/upload/exam.pdf.If it is possible then please tell me the way.

  • #2
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    Place the file in a non-public folder and use readfile() to send the contents to the client, as well as header() to set the file's name, type, size, and so on.

    Quick example, untested... to download exam.pdf you'd load files.php?id=1
    PHP Code:
    <?php # files.php

    /* - - - - - - - - - -
     * Our hidden files
     */

    $files = array(
        
    => 'exam.pdf',
        
    => 'exam2.pdf',
        
    => 'exam3.pdf',
    );

    /* - - - - - - - - - -
     * Ensure `?id=xxx` is set and valid
     */

    if ( ! isset( $_GET['id'] ) )
    {
        
    header'Location: /' );
        exit;
    }

    $id = ( int ) $_GET['id'];

    if ( ! isset( 
    $files$id ] ) )
    {
        
    header'Location: /' );
        exit;
    }

    /* - - - - - - - - - -
     * Full path to the file
     */

    $path '/var/non-www/files/' $files$id ];

    /* - - - - - - - - - -
     * Ensure $path is a valid file
     */

    if ( ! is_file$path ) )
    {
        
    header'Location: /' );
        exit;
    }

    /* - - - - - - - - - -
     * Send the file as a download with proper headers
     */

    header'Content-type: application/octet-stream' );
    header'Content-Disposition: attachment; filename="' basename$path ) . '"' );
    header'Content-length: ' filesize$path ) );
    readfile$path );
    Last edited by kbluhm; 09-26-2012 at 05:41 AM.

  • #3
    Senior Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    4,429
    Thanks
    62
    Thanked 535 Times in 522 Posts
    Using readfile() can of course hit the scripts maximum execution time limit.

    If your server has it enabled, you would be wise to set_time_limit(0)
    See my new CodingForums Blog: http://www.codingforums.com/blogs/tangoforce/

    Many useful explanations and tips including: Cannot modify headers - already sent, The IE if (isset($_POST['submit'])) bug explained, unexpected T_CONSTANT_ENCAPSED_STRING, debugging tips and much more!


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •