Browsers download files, not open

Discussion in 'Programming' started by s_ruben, Jan 24, 2011.

  1. #1
    Hello

    I want to know how can do so that the browsers download the files (for example .txt files, .jpg files e.t.c., besides .php files) and don't open in the browser.

    Thank you.
     
    s_ruben, Jan 24, 2011 IP
  2. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #2
    Check out following code snippet.
    You may need to change content-type based on the file type if needed.

    
    	if(file_exists($file_name))
    	{
    		header('Content-Description: File Transfer');
    		header('Content-Type: application/octet-stream');
    		header('Content-Disposition: attachment; filename=' . basename($file_name));
    		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_name));
    		ob_clean();
    		flush();
    		readfile($file_name);
    		exit;
    	}
    
    PHP:
     
    mastermunj, Jan 25, 2011 IP
  3. s_ruben

    s_ruben Active Member

    Messages:
    735
    Likes Received:
    26
    Best Answers:
    1
    Trophy Points:
    78
    #3
    Thank you mastermunj. But I've already used this and it works greate:

    
    $file = $_GET['file'];
    
    header("Content-type: octet/stream");
    header("Content-disposition: attachment; filename=".$file.";");
    header("Content-Length: ".filesize($file));
    readfile($file);
    exit;
    
    PHP:
     
    s_ruben, Jan 25, 2011 IP