查看Blob文件内容

时间:2011-12-13 14:17:50

标签: php blob

使用我在'devarticles.com'和'mistonline'找到的一些例子我将下面显示的脚本放在一起,允许用户将图像文件保存到mySQL数据库,将文件保存为BLOB。

<?php
$db_host = 'hostname'; 
$db_user = 'username';
$db_pwd = 'password';

$database = 'databasename';
$table = 'tablename';
// use the same name as SQL table


if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
    if (get_magic_quotes_gpc())
        $s = stripslashes($s);

    return mysql_real_escape_string($s);
}

// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // cleaning title field
    $title = trim(sql_safe($_POST['title']));

    if ($title == '') // if title is not set
        $title = '(empty title)';// use (empty title) string

    {
        if (isset($_FILES['photo']))
        {
            @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
            // Get image type.
            // We use @ to omit errors

            if ($imtype == 3) // cheking image type
                $ext="png";   // to use it later in HTTP headers
            elseif ($imtype == 2)
                $ext="jpeg";
            elseif ($imtype == 1)
                $ext="gif";
            else
                $msg = 'Error: unknown file format';

            if (!isset($msg)) // If there was no error
            {
                $data = file_get_contents($_FILES['photo']['tmp_name']);
                $data = mysql_real_escape_string($data);
                // Preparing data to be used in MySQL query

                mysql_query("INSERT INTO {$table}
                                SET ext='$ext', title='$title',
                                    data='$data'");

                $msg = 'Success: image uploaded';
            }
        }
        elseif (isset($_GET['title']))      // isset(..title) needed
            $msg = 'Error: file not loaded';// to make sure we've using
                                            // upload form, not form
                                            // for deletion

                if (isset($_POST['del'])) // If used selected some photo to delete
        {                         // in 'uploaded images form';
            $imageid = intval($_POST['del']);
            mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
            $msg = 'Photo deleted';
        }
        if (isset($_POST['view'])) // If used selected some photo to delete 
{ // in 'uploaded images form'; 
$imageid = intval($_POST['view']); 
mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid"); 
if(mysql_num_rows($result) == 1) 
{ 
$image = $row['myimage']; 
header("Content-type: image/gif"); // or whatever 
print $image; 
exit; 
} 
} 


    }
}
elseif (isset($_GET['show']))
{
    $imageid = intval($_GET['show']);

    $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
                             FROM {$table}
                            WHERE imageid=$imageid LIMIT 1");

    if (mysql_num_rows($result) == 0)
        die('no image');

    list($ext, $imagetime, $data) = mysql_fetch_row($result);

    $send_304 = false;
    if (php_sapi_name() == 'apache') {
        // if our web server is apache
        // we get check HTTP
        // If-Modified-Since header
        // and do not send image
        // if there is a cached version

        $ar = apache_request_headers();
        if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
            ($ar['If-Modified-Since'] != '') && // not empty
            (strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
            $send_304 = true;                                     // imagetime
    }

    if ($send_304)
    {
        // Sending 304 response to browser
        // "Browser, your cached version of image is OK
        // we're not sending anything new to you"
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);

        exit(); // bye-bye
    }

    // outputing HTTP headers
    header('Content-Length: '.strlen($data));
    header("Content-type: image/{$ext}");

    // outputing image
    echo $data;
    exit();
}
?>
<html><head>
<title>Save Photo(s) to Find</title>
</head>
<body>
<?php
if (isset($msg)) // this is special section for
                 // outputing message
{
?>
<p style="font-weight: bold;"><?=$msg?>
<br />
</p>
<?php
}
?>
<h1>Save Find images </h1>
<h2>Uploaded Find images:</h2>
<form action="<?=$PHP_SELF?>" method="post">
<!-- This form is used for image deletion -->

<?php
$result = mysql_query("SELECT imageid, imagetime, title FROM {$table} ORDER BY imageid DESC");
if (mysql_num_rows($result) == 0) // table is empty
    echo '<ul><li>No images loaded</li></ul>';
else
{
    echo '<ul>';
    while(list($imageid, $imagetime, $title) = mysql_fetch_row($result))
    {
        // outputing list
        echo "<li><input type='radio' name='del' title, value='{$imageid}'/>";
        echo "&nbsp;<small>{$title}</small>&nbsp;&nbsp";
        echo "<small>{$imagetime}</small></li>";
    }

    echo '</ul>';

    echo '<input type="submit" value="Delete selected"/>';

    echo "<input type=\"button\" value=\"View Photo\" onclick=\"location.href='<?=$PHP_SELF?>?show=1'\" />"; 
}
?>

</form>
<h2>Upload new Find image:</h2>
<form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data">
<label for="title"></label>
<label for="photo"></label>
<label for="password"></label>
<table border="0" cellpadding="0" cellspacing="0" bordercolor="#111111" width="38%">
  <tr>
    <td bgcolor="#FF9900" height="22" colspan="2"><p style="margin-left: 10"><b><font face="Verdana" size="2" color="#FFFFFF"> Upload a File</font></b></td>
  </tr>
  <tr>
    <td bgcolor="#FFE3BB" colspan="2"><p style="margin-left: 10; margin-right: 10"><font face="Verdana" size="2"> <br>
      Please select a file from your local computer to upload to our web server 

      for saving in our database. This file can be of any type you like. Once you 

      have chosen a file, please click on the &quot;Upload this file&quot; button below.&nbsp;

      &nbsp;<br>
      &nbsp;</font></td>
  </tr>
  <tr>
    <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> File Description:</font></td>
    <td width="66%" bgcolor="#FFE3BB"><input type="text" name="title" id="title" size="64"/></td>
  </tr>
  <tr>
    <td bgcolor="#FFE3BB"><span style="margin-left: 10"><font face="Verdana" size="2">File Location:</font></span></td>
    <td bgcolor="#FFE3BB"><input type="file" name="photo" id="photo"/></td>
  </tr>
  <tr>
    <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> <br>
              <br>
      &nbsp;</font></td>
    <td width="66%" bgcolor="#FFE3BB"><input name="submit" type="submit" value="Upload This File"/></td>
  </tr>
</table>
<p>&nbsp;</p>
<p>&nbsp;</p>
</form>
</body>
</html>

我可以保存,列出保存的文件并从数据库中删除文件,但是我遇到了一个问题,我无法弄清楚如何检索和查看图像,实际上我的“查看照片”删除了它

我认为答案在“输出列表”部分,但我尝试了多种方法尝试“查看照片”按钮来执行“查看”命令。

我只是想知道是否有人可以看看这个并让我知道我哪里出错了。

1 个答案:

答案 0 :(得分:0)

这里是:

<?php
$db_host = 'localhost'; 
$db_user = '';
$db_pwd = '';

$database = '';
$table = 'images';
// use the same name as SQL table

if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
    if (get_magic_quotes_gpc())
        $s = stripslashes($s);

    return mysql_real_escape_string($s);
}

// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if (!isset($_POST["action"]))
    {
        // cleaning title field
        $title = trim(sql_safe($_POST['title']));

        if ($title == '') // if title is not set
            $title = '(empty title)';// use (empty title) string

        if (isset($_FILES['photo']))
        {
            @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
            // Get image type.
            // We use @ to omit errors

            if ($imtype == 3) // cheking image type
                $ext="png";   // to use it later in HTTP headers
            elseif ($imtype == 2)
                $ext="jpeg";
            elseif ($imtype == 1)
                $ext="gif";
            else
                $msg = 'Error: unknown file format';

            if (!isset($msg)) // If there was no error
            {
                $data = file_get_contents($_FILES['photo']['tmp_name']);
                $data = mysql_real_escape_string($data);
                // Preparing data to be used in MySQL query

                mysql_query("INSERT INTO {$table}
                                SET ext='$ext', title='$title',
                                    data='$data'");

                $msg = 'Success: image uploaded';
            }
        }
        elseif (isset($_GET['title']))      // isset(..title) needed
            $msg = 'Error: file not loaded';// to make sure we've using
                                            // upload form, not form
                                            // for deletion

        if (isset($_POST['del'])) // If used selected some photo to delete
        {                         // in 'uploaded images form';
            $imageid = intval($_POST['del']);
            mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
            $msg = 'Photo deleted';
        }

        if (isset($_POST['view'])) // If used selected some photo to delete 
        { // in 'uploaded images form'; 
            $imageid = intval($_POST['view']); 
            mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid"); 

            if(mysql_num_rows($result) == 1) 
            { 
                $image = $row['myimage']; 
                header("Content-type: image/gif"); // or whatever 
                print $image; 
                exit; 
            } 
        } 
    }
    else
    {
        $imageid = intval($_POST['del']);

        if ($_POST["action"] == "view")
        {
            $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
                                     FROM {$table}
                                    WHERE imageid=$imageid LIMIT 1");

            if (mysql_num_rows($result) == 0)
                die('no image');

            list($ext, $imagetime, $data) = mysql_fetch_row($result);

            $send_304 = false;
            if (php_sapi_name() == 'apache') {
                // if our web server is apache
                // we get check HTTP
                // If-Modified-Since header
                // and do not send image
                // if there is a cached version

                $ar = apache_request_headers();
                if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
                    ($ar['If-Modified-Since'] != '') && // not empty
                    (strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
                    $send_304 = true;                                     // imagetime
            }

            if ($send_304)
            {
                // Sending 304 response to browser
                // "Browser, your cached version of image is OK
                // we're not sending anything new to you"
                header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);

                exit(); // bye-bye
            }

            // outputing HTTP headers
            header('Content-Length: '.strlen($data));
            header("Content-type: image/{$ext}");

            // outputing image
            echo $data;
            exit();
        }
        else if ($_POST["action"] == "delete")
        {
            $imageid = intval($_POST['del']);
            mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
            $msg = 'Photo deleted';
        }
    }
}
?>
<html><head>
<title>Save Photo(s) to Find</title>
</head>
<body>
<?php
if (isset($msg)) // this is special section for
                 // outputing message
{
?>
<p style="font-weight: bold;"><?=$msg?>
<br />
</p>
<?php
}
?>
<h1>Save Find images </h1>
<h2>Uploaded Find images:</h2>
<form action="<?=$PHP_SELF?>" method="post">
<!-- This form is used for image deletion -->

<?php
$result = mysql_query("SELECT imageid, imagetime, title FROM {$table} ORDER BY imageid DESC");
if (mysql_num_rows($result) == 0) // table is empty
    echo '<ul><li>No images loaded</li></ul>';
else
{
    echo '<ul>';
    while(list($imageid, $imagetime, $title) = mysql_fetch_row($result))
    {
        // outputing list
        echo "<li><input type='radio' name='del' title, value='{$imageid}' />";
        echo "&nbsp;<small>{$title}</small>&nbsp;&nbsp";
        echo "<small>{$imagetime}</small></li>";
    }

    echo '</ul>';

    echo '<input type="submit" value="Delete selected" onclick="document.getElementById(\'action\').value=\'delete\'" />';

    echo '<input type="submit" value="View Photo" onclick="document.getElementById(\'action\').value=\'view\'" />';
}
?>
    <input type="hidden" name="action" id="action" />
</form>
<h2>Upload new Find image:</h2>
<form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data">
<label for="title"></label>
<label for="photo"></label>
<label for="password"></label>
<table border="0" cellpadding="0" cellspacing="0" bordercolor="#111111" width="38%">
  <tr>
    <td bgcolor="#FF9900" height="22" colspan="2"><p style="margin-left: 10"><b><font face="Verdana" size="2" color="#FFFFFF"> Upload a File</font></b></td>
  </tr>
  <tr>
    <td bgcolor="#FFE3BB" colspan="2"><p style="margin-left: 10; margin-right: 10"><font face="Verdana" size="2"> <br>
      Please select a file from your local computer to upload to our web server 

      for saving in our database. This file can be of any type you like. Once you 

      have chosen a file, please click on the &quot;Upload this file&quot; button below.&nbsp;

      &nbsp;<br>
      &nbsp;</font></td>
  </tr>
  <tr>
    <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> File Description:</font></td>
    <td width="66%" bgcolor="#FFE3BB"><input type="text" name="title" id="title" size="64"/></td>
  </tr>
  <tr>
    <td bgcolor="#FFE3BB"><span style="margin-left: 10"><font face="Verdana" size="2">File Location:</font></span></td>
    <td bgcolor="#FFE3BB"><input type="file" name="photo" id="photo"/></td>
  </tr>
  <tr>
    <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> <br>
              <br>
      &nbsp;</font></td>
    <td width="66%" bgcolor="#FFE3BB"><input name="submit" type="submit" value="Upload This File"/></td>
  </tr>
</table>
<p>&nbsp;</p>
<p>&nbsp;</p>
</form>
</body>
</html>

希望它适合你!!