sending a file with php

Discussion in 'Software' started by mr_flea, Jan 14, 2005.

  1. mr_flea

    mr_flea First Sergeant

    I'm trying to write a script that will send a file for download, or an image or text page for viewing by the browser, but when I view anything other than text with it it can't seem to get the client to see the file as what it really is, a picture file or whatever. Here's my current code (with comments)

    The 3rd line is disabled for testing purposes, but when enabled, will surpress errors so they don't mess up the file. I have tested it with that line uncommented.

    Code:
     <?PHP
     	//disable errors, those will screw over my file...
     	//ini_set('display_errors','off');
     	//get the location of the file and its name
     	if ($file = $_GET['f']) {
     		//is the file there? if so, open it.
     		if (!$fopen = fopen($file, 'rb')) { return_404(); }
     		//what is the file's mime type?
     		if (!$mime = mime_content_type($file)) { return_500(); }
     		//what is its size?
     		if (!$size = filesize($file)) { return_500(); }
     		//send mime and size in headers.
     		header('Content-Type: '.$mime);
     		header('Content-Length: '.$size);
     		//send file
     		if (!fpassthru($fopen)) { return_500(); }
     		//close fopen
     		if (!fclose($fopen)) { return_500(); }
     	} else {
     		return_404();
     	}
     	//404 error
     	function return_404() {
     		//send error headers.
     		header('HTTP/1.1 404 Not Found');
     		header('Status: 404 Not Found');
     		die;
     	}
     	//500 error
     	function return_500() {
     		//send error headers.
     		header('HTTP/1.1 500 Internal Server Error');
     		header('Status: 500 Internal Server Error');
     		die;
     	}
     ?>
     
    any ideas?
     
  2. goldfish

    goldfish Lt. Sushi.DC

    All I can say is to double check the MIME headers, and see if it is sending the correct ones.
     
  3. mr_flea

    mr_flea First Sergeant

    well, I forgot Content-Disposition: and Connection-Close:, and now it sends anything, but I can't get it to work with Content-Disposition: inline, it wants me to download the file... any ideas?
     
  4. mr_flea

    mr_flea First Sergeant

    nevermind. it works right, just not how I expected it to.
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds