PHP - 发送 GET 请求并获取图片作为返回

标签 php javascript html css

我需要向我的页面 pic.php 发送一个 GET 请求,我想得到一张真实的图片作为返回。

现在我是这样实现这个想法的:

<?php
if ((isset($_GET['pic']))&&(isset($_GET['key']))){
$pic = $_GET['pic'];
$pic=stripslashes($pic);

header('Location: /content/'.$pic);

}
?>

但这并不是我真正想要的 - 它直接重定向到图像。我想要的是保留相同的 URL,但根据提交的值获取所需的文件。 最好的方法是什么? 谢谢。

最佳答案

此示例代码片段应该可以满足您的要求。如果在服务器上启用了魔术引号,我还包含了仅去除斜杠的代码。这将使您的代码更具可移植性,并与 future 版本的 PHP 兼容。我还添加了 getimagesize() 的使用来检测 MIME 类型,以便您为图像输出正确的 header ,而不必假设它是特定类型。

<?php
if(isset($_GET['pic']))
{
    //Only strip slashes if magic quotes is enabled.
    $pic = (get_magic_quotes_gpc()) ? stripslashes($_GET['pic']) : $_GET['pic'];

    //Change this to the correct path for your file on the server.
    $pic = '/your/path/to/real/image/location/'.$pic;

    //This will get info about the image, including the mime type.
    //The function is called getimagesize(), which is misleading 
    //because it does much more than that.
    $size = getimagesize($pic);

    //Now that you know the mime type, include it in the header.
    header('Content-type: '.$size['mime']);

    //Read the image and send it directly to the output.
    readfile($pic);
}
?>

关于PHP - 发送 GET 请求并获取图片作为返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9742076/

相关文章:

PHP+MySQL 脚本无法运行

javascript - JQuery 未捕获类型错误

javascript - 同步事件中的 ServiceWorker 无法使用 waitUntil

css - 无法在 MaterializeCSS 中选择单选按钮

html - 使用词缀 Bootstrap 将粘性导航栏居中并扩展边框

php - Google ReCaptcha 未发布 'g-recaptcha-response'

php - 非常奇怪的数据库查询结果

javascript - D3 .bandwidth() 返回 NaN

html - 我的 Bootstrap 模式仅适用于 index.html 页面

php laravel/vuejs 部署我的 vuejs View 未渲染