download image from mysql using php

//You can save this to test.php and call it with test.php?id=1 for example
<?php

//Database class with PDO (MySQL/MariaDB)
require_once("database.php"); //If you need this, write to [email protected] i'll send you the db class

//Connect to database
$database = new Database();
$pdo = $database->dbConnection();

//Get ID from GET (better POST but for easy debug...)
if (isset($_GET["id"])) {
	$id=(int)$_GET["id"];
} else {
  echo "Wrong input";
  exit;
}

//Prepare PDO SQL
$q = $pdo->prepare("SELECT * FROM `table_with_image` WHERE `id`=:p_id");

//Add some data
$q->bindparam(":p_id", $id); //Filter user input, no sanitize necessary here

//Do the db query
$q->execute();

//If something found (always only 1 record!)
if ($q->rowCount() == 1) {
  
  	//Get the content of the record into $row
	$row = $q->fetch(PDO::FETCH_ASSOC); //Everything with id=$id should be in record buffer
  	
  	//This is the image blob mysql item  
  	$image = $row['image'];
  	
  	//Clean disconnect
  	$database->disconnect();
    
  	//Now start the header, caution: do not output any other header or other data!
  	header("Content-type: image/jpeg");
    header('Content-Disposition: attachment; filename="table_with_image_image'.$id.'.jpg"');
    header("Content-Transfer-Encoding: binary"); 
    header('Expires: 0');
    header('Pragma: no-cache');
    header("Content-Length: ".strlen($image));
    //Output plain image from db
	echo $image;
} else {
  //Nothing found with that id, output some error
  $database->disconnect();
  echo "No image found";
}

//No output and exceution further this point
exit();

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source