0

I'm trying to let my script check if an image exist before echoing it into my table. If it doesn't exist, it should echo another image in stead. My problem is that even though the image exist, it still goes to the else factor. Can anyone spot any coding mistakes?

<?php
mysql_select_db("xxxx");
$result = mysql_query("SELECT * FROM yyyy WHERE frivillig=1 ORDER BY stilling");
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td width="50px" class="frivillig"><?php  if (file_exists($url . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg")) {
echo "<img" . " " . "src='" . $url . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg'" . " " . "height='50px'/>";
}
else {
echo "<img" . " " . "src='" . $url . "images/mangler.png'" . " " . "height='50px'/>";
}
?>

As you can see, I use $url for my complete url, and the images are placed in the /ansatte/ folder.

Thanks for any help!

4

3 回答 3

2

考虑以下用于检查远程资源的代码段:

$path = $url . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg"

$ch = curl_init($path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpcode < 400) { // Filter out bad request, not found, etc
 // found
} else {
 // not accessible
}

如果您没有安装 php5-curl,您还可以查看以下替代方案:

获取图像大小

同样,这里只支持某些流,但使用很简单,它会更好地验证返回:

if (getimagesize($path) !== FALSE) {
  //exists
}

开放

if (fopen($path,"r") !== FALSE) {
  // exists
}

获取标题

$headers = get_headers($path, TRUE);
if ($headers !== false && isset($headers['Content-Type']) && $headers['Content-Type'] == 'image/jpeg') {
  // exists
}
于 2013-01-29T20:11:54.643 回答
2

file_exists()不适用于检查 URL。您的调用file_exists()应反映相对或绝对文件系统路径,而不是 URL。

于 2013-01-29T20:07:17.733 回答
0

我在这里预感到并假设图像文件实际上与脚本位于同一服务器上。如果是这样,您应该在检查文件是否存在时使用绝对或相对路径,而不是 URL。

<?php

$stmt = $dbh->prepare("SELECT * FROM yyyy WHERE frivillig=1 ORDER BY stilling");
$stmt->execute();
$rows = $stmt->fetchAll();

$url = 'http://www.yoursite.com/subdir/';
$path = '/path/to/yoursite/subdir/';

foreach ($rows as $row) {
    ?>
    <tr>
    <td width="50px" class="frivillig">
    <?php
    if (file_exists($path . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg")) {
        echo "<img" . " " . "src='" . $url . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg'" . " " . "height='50px'/>";
    }
    else {
        echo "<img" . " " . "src='" . $url . "images/mangler.png'" . " " . "height='50px'/>";
    }
}
?>

同样正如@crush 提到的,您不应该使用mysql_*函数。自 PHP 5.5 起,它们已被弃用。上面的例子使用了 PDO。

于 2013-01-29T20:23:17.963 回答