使用file_exists检查echo之前是否存在图像

时间:2013-01-29 20:05:27

标签: php file-exists

我正在尝试让我的脚本检查图像是否存在,然后将其回显到我的表中。如果它不存在,它应该反过来回显另一个图像。我的问题是,即使图像存在,它仍然会转向其他因素。有人能发现任何编码错误吗?

<?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'/>";
}
?>

如您所见,我使用$ url作为我的完整网址,图片放在/ ansatte /文件夹中。

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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,您还可以查看以下备选方案:

<强>和getimagesize

此处仅支持某些流,但使用很简单,它将更好地验证返回:

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

<强>的fopen

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

<强> get_headers

$headers = get_headers($path, TRUE);
if ($headers !== false && isset($headers['Content-Type']) && $headers['Content-Type'] == 'image/jpeg') {
  // exists
}

答案 2 :(得分: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。