如何使用PHP实现远程图片显示?基于$id获取动态图片SRC
Solution: Fetch Remote Image by ID and Display It
Got it, let's work through this. You need to grab a remote image's source URL using an $id, pull the actual img src from that remote page, then render the image on your site. Here's a robust PHP implementation that does exactly that, with error handling and edge case fixes:
<?php $id = "brown_fox"; $remotePageUrl = "http://example.com/$id"; function get_remote_img($url) { // Use cURL for reliable remote content fetching (better than file_get_contents) $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects if the page moves curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable only if target uses self-signed SSL (adjust as needed) $pageContent = curl_exec($ch); $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Check for cURL errors or non-success HTTP status if (curl_errno($ch) || $httpStatus !== 200) { curl_close($ch); return null; // Return null on failure to fetch page } curl_close($ch); // Regex to extract src attribute from any img tag (handles single/double quotes) if (preg_match('/<img[^>]+src=["\']([^"\']+)["\']/i', $pageContent, $matches)) { return $matches[1]; // Return the captured src value } return null; // Return null if no img src is found on the page } // Get the image source from the remote page $imgSrc = get_remote_img($remotePageUrl); // Render the image tag if we have a valid src if ($imgSrc) { // Convert relative URLs to absolute (so the browser can load them correctly) if (!filter_var($imgSrc, FILTER_VALIDATE_URL)) { $parsedRemoteUrl = parse_url($remotePageUrl); $baseRemoteUrl = $parsedRemoteUrl['scheme'] . '://' . $parsedRemoteUrl['host']; if (str_starts_with($imgSrc, '/')) { $imgSrc = $baseRemoteUrl . $imgSrc; } else { $imgSrc = $baseRemoteUrl . '/' . $imgSrc; } } echo "<img src='$imgSrc' />"; } else { echo "Sorry, couldn't load the remote image."; } ?>
Key Details to Note:
- cURL Reliability: I used cURL instead of
file_get_contentsbecause it handles redirects, SSL configurations, and error states much better—critical for fetching remote content consistently. - Regex Matching: The regex pattern targets any
imgtag and captures itssrcvalue, whether the attribute uses single or double quotes, and works case-insensitively. - Relative URL Fix: If the remote page returns a relative path (like
sjf5d85v258d.jpginstead of a full URL), the code converts it to an absolute URL using the base of the remote page's URL. This ensures your browser can find the image. - Error Handling: We check for failed cURL requests, non-200 HTTP statuses, and missing
imgtags, so we can show a friendly message instead of a broken image placeholder.
内容的提问来源于stack exchange,提问作者IGNAS
相关产品推荐
相关产品推荐

