I want a database that should fetch images from a URL.How can I do that?

Dani AI

Generated

was right: a database does not by itself "fetch" remote files — it only stores data. For images on the web there are two practical patterns:

  1. store the image URL in the database and output that URL in an <img> tag; or
  2. download the remote image to your server (or into a BLOB) and store the local path or binary in the DB.

Which to pick depends on requirements: storing URLs keeps DB size small but risks broken links and hotlinking; storing local copies avoids those issues but adds bandwidth, disk, and backup cost.

A minimal schema and PHP flow for storing remote-URLs (validated) looks like:

CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
url VARCHAR(2083) NOT NULL,
title VARCHAR(255),
mime VARCHAR(100),
size INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Example PHP (validation + safe insert):

$url = $_POST['url'] ?? '';
if (!filter_var($url, FILTER_VALIDATE_URL) || !preg_match('#^https?://#i', $url)) {
    die('Invalid URL');
}
$headers = @get_headers($url, 1);
if (!$headers || strpos((string)$headers['Content-Type'], 'image/') !== 0) {
    die('Not an image');
}
$stmt = $pdo->prepare('INSERT INTO images (url, title, mime) VALUES (:url, :title, :mime)');
$stmt->execute([':url'=>$url, ':title'=>$_POST['title'] ?? null, ':mime'=>$headers['Content-Type']]);

If hotlinking or availability is a concern, fetch and save the file (cURL or file_get_contents), validate the MIME and size, create a collision-resistant filename (hash + extension), save it to a protected folder and store the local path in the DB. When outputting, always escape the URL/path with htmlspecialchars().

Notes and best practices:

  • Validate URLs and limit remote file size and download timeout.
  • Use prepared statements (PDO) to avoid SQL injection. See PDO.
  • Check content-type with headers or getimagesize before trusting the file. See getimagesize.
  • Prefer filesystem/CDN storage for many or large images; use BLOBs only when you need transactional storage or single-file backups. See MySQL BLOB docs for trade-offs.

Respect copyright and hotlinking policies of remote hosts when copying images.

Recommended Answers

All 5 Replies

database does not fetch it only stores.

So can I input images thhrough their URLs in a Php form?

where the images are stored in what format ?

well most ( not all) the images are on the net.So do you mean, i will have to first copy them, convert to a certain format and all?

if the images are in net what is in database ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.