【问题标题】:CakePHP - need URL to route to the tmp directory?CakePHP - 需要 URL 来路由到 tmp 目录?
【发布时间】:2013-01-20 13:33:33
【问题描述】:

我正在尝试使用 Cake PHP 中的 GD lib 创建缩略图。

我可以将调整大小的缩略图写入 tmp 目录,并创建合理的 URL 以显示 tmp 目录中的图像:

//set up empty GD resource  
$tmp = imagecreatetruecolor(200*$iw/$ih, 200);
//create thumbnail image in the empty GD resource
imagecopyresampled($tmp, $src, 0, 0, 0, 0,200*$iw/$ih, 200, $iw, $ih);
//build full path to thumbnail in the cakephp tmp directory
$thumbfile = APP.'tmp/thumb.jpg';
//build URL path to the same thumbnail
$thumblink = $this->webroot.'tmp/thumb.jpg';
//write jpeg to the tmp directory
$return=imagejpeg($tmp,$thumbfile);
//write out the image to client browser
echo "<img=\"$thumblink\" alt=\"thumb\" height=\"200\" width=\"200*$iw/$ih\">";

缩略图被创建并写入 tmp 目录,但是当我尝试访问 URL 时,我收到以下错误消息:

Error: TmpController could not be found.
Error: Create the class TmpController below in file: app/Controller/TmpController.php

显然我有一个路由错误 - Cake 尝试调用 tmp 控制器,而不是查看 tmp 目录。我该如何解决这个问题,或者是否有另一种方法可以使用 GD lib 提供临时缩略图? 我计划为每个会话或用户创建唯一的缩略图,但我需要先完成这项工作。

Config/routes.php 中的路由:

Router::connect('/', array('controller' => 'MsCake', 'action' => 'index'));
Router::connect('/pages/*', array('controller' => 'pages'));
CakePlugin::routes();

我查看了 ThumbnailHelper,但它没有使用 GD Lib。我还需要能够从外部访问存储在非 apache 可访问目录中的文件,但我什至无法访问任何临时符号链接来访问它们。例如。

  • 在 tmp 目录中创建一个临时符号链接,指向相关文件。
  • 创建一个 HTML 链接,使用 $this->webroot.'tmp/link-to-myfile' 指向符号链接,如上所述

...我得到与上面相同的错误 - 错误:找不到 TmpController。

【问题讨论】:

    标签: cakephp-2.1 tmp


    【解决方案1】:

    不要那样做

    如果您采取任何措施使 tmp 目录中的文件可通过网络访问 - 您将严重降低网站的安全性。 tmp 目录中的东西永远不应该是 Web 可访问的。

    把你的图片放在 webroot 中

    一个更好的主意是将您的临时图像放在 webroot 目录中 - 这是唯一一个通常可以通过网络访问的目录。例如:

    $filename = md5($userId);
    $thumbfile = APP.'webroot/img/cache/' . $filename . '.jpg';
    
    ...
    $url = '/img/cache/' . $filename . '.jpg';
    

    或路由到控制器动作

    或者,使用media view class 路由到控制器操作以处理请求。但是请注意,使用 php 提供图像不是免费的 - 在处理您的请求时可能会有明显的延迟 - 而指向静态文件没有这种成本/风险,因为它只是负责提供服务的网络服务器内容。

    【讨论】:

    • 谢谢!您解释了 tmp 目录,所以每个人都可以理解它。问题解决了。
    【解决方案2】:

    由于它是临时的,您可以做的是将图像显示为数据 url 而不是 tmp 目录,就像这样(在imagecopyresampled() 调用之后替换):

    ob_start();
    imagepng($tmp);
    $contents =  ob_get_contents();
    ob_end_clean();
    imagedestroy($tmp);
    
    
    //write out the image to client browser
    echo "<img src='data:image/png;base64,".base64_encode($contents)."' alt='thumb' height='200' width='".(200*$iw/$ih)."'>";
    

    这使用了更多带宽,因为图像是 base64 编码而不是作为二进制发送。

    【讨论】:

      猜你喜欢
      • 2019-11-26
      • 2022-10-05
      • 2011-07-23
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      相关资源
      最近更新 更多