简体   繁体   English

从MySQL的PHP​​显示路径中的图片

[英]Displaying pictures from path in PHP from MySQL

I am in the early stage of developing a bidding system whereby users are able to insert items that they want to sell. 我处于开发出价系统的早期阶段,通过该系统,用户可以插入他们想出售的物品。 Here is the script to copy the image from the temporary path and store the path of the image to another folder. 这是用于从临时路径复制图像并将该图像的路径存储到另一个文件夹的脚本。

    define ("MAX_SIZE","10000");

    //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
    function getExtension($str) {
        $i = strrpos($str,".");
        if (!$i) {
            return "";
        }
        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);
        return $ext;
    };

    //This variable is used as a flag. The value is initialized with 0 (meaning no error found) and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
    $errors = 0;

    //Checks if the form has been submitted
    if (isset($_POST['Submit']))
    {
        //Reads the name of the file the user submitted for uploading
        $image=$_FILES['image']['name'];

        //If it is not empty
        if ($image)
        {
            //Get the original name of the file from the clients machine
            $filename = stripslashes($_FILES['image']['name']);

            //Get the extension of the file in a lower case format
            $extension = getExtension($filename);
            $extension = strtolower($extension);

            //If it is not a known extension, we will suppose it is an error and will not upload the file, otherwize we will do more tests
            if (($extension != "jpg") &&
                ($extension != "jpeg") &&
                ($extension != "png") &&
                ($extension != "gif"))
            {
                //Print error message
                echo '<h1>Unknown extension!</h1>';
                $errors=1;
            }
        else
        {
            //Get the size of the image in bytes
            //$_FILES['image']['tmp_name'] is the temporary filename of the file in which the uploaded file was stored on the server
            $size=filesize($_FILES['image']['tmp_name']);

            //Compare the size with the maxim size we defined and print error if bigger
            if ($size > MAX_SIZE*111111111111024)
            {
                echo '<h1>You have exceeded the size limit!</h1>';
                $errors=1;
            }

            //We will give an unique name, for example the time in Unix time format
            $image_name=time().'.'.$extension;

            //The new name will be containing the full path where will be stored (images folder).
            $imagepath='C:\\xampp\\htdocs\\biddingsystem\\Images\\' . $image_name;

            //We verify if the image has been uploaded, and print an error instead
            $copied = copy($_FILES['image']['tmp_name'], $imagepath);
            if (!$copied)
            {
                echo '<h1>Picture upload failed!</h1>';
                $errors=1;
            }
        }
    }
}

//If no errors registred, print the success message
if(isset($_POST['Submit']) && !$errors && isset($_POST['image']))
{
    echo "<h1>Picture Uploaded Successfully! Try again!</h1>";
}

Then, I inserted the image path along with other data to a MySQL database with the script below and tried to display them back to the user using a table. 然后,我使用下面的脚本将图像路径以及其他数据插入到MySQL数据库中,并尝试使用表将其显示给用户。 Other data worked out fine but for the image display (imagepath), only the path of the image gets displayed, not the image itself. 其他数据工作正常,但对于图像显示(imagepath),仅显示图像的路径,而不显示图像本身。

mysql_query("INSERT INTO items
    (username, item, price, description, start_date, start_time, imagepath)
    VALUES    ('$username', '$_POST[item]', '$_POST[price]', '$_POST[description]','$_POST[start_date]', '$_POST[start_time]', '$imagepath') ")
    or die ("Error - Couldn't add item");

    echo "Item added successfully";
    echo "<h1>You have added the following item:</h1>";
    $sql = "SELECT item, price, description, start_time, start_date, imagepath FROM items WHERE username = '$username' AND item='$_POST[item]'";
    $result = mysql_query($sql);

$row = mysql_fetch_assoc($result);
echo"<table border=2>

         <tr><td>Item</td>
             <td>Price</td><td>Description</td><td>Start time</td><td>Start date</td><td>Picture</td></tr>

         <tr><td> $row[item]</td>
              <td> $row[price]</td>
              <td> $row[description]</td>
             <td> $row[start_time]</td>
             <td> $row[start_date]</td>
             <td> $row[imagepath]</td>
         </tr>
     </table></br>";

I have tried using <img src="<?php $imagepath ?>"> to show the image but to no avail. 我尝试使用<img src="<?php $imagepath ?>">显示图像,但无济于事。 I have even tried storing the actual image itself in the database using the BLOB type. 我什至尝试使用BLOB类型将实际图像本身存储在数据库中。 However, the result is a page filled with strange characters. 但是,结果是页面上充满了奇怪的字符。 How do I fix this problem? 我该如何解决这个问题?

You are confusing the filesystem path and web URL . 您正在混淆文件系统路径和Web URL You have to store only /biddingsystem/Images/ part or even just only name and generate full path dynamically at display time. 您只需要存储/biddingsystem/Images/部分,甚至仅存储名称,并在显示时动态生成完整路径。

Also note that you aren't formatting your data properly, which will lead to some bugs and security vulnerabilities. 还要注意,您没有正确格式化数据,这将导致一些错误和安全漏洞。 I've explained formatting rules in my earlier answer, to Stack Overflow question How to include a PHP variable inside a MySQL insert statement . 我已经在较早的答案“ Stack Overflow”中解释了格式化规则,该问题如何在MySQL insert语句中包含PHP变量

If you want to go with the first solution, displaying from a path, make sure you're pointing to the image in an accessible path. 如果要使用第一种解决方案(从路径显示),请确保您指向的图像位于可访问的路径中。 From the code you listed, it looks like $imagepath is a file:// path. 从您列出的代码中,看起来$ imagepath是file://路径。 On a web server, you'll have to map that to a relative web path. 在网络服务器上,您必须将其映射到相对的网络路径。

If you decide to go with the BLOB, the best method is to make a separate page that serves images. 如果决定使用BLOB,最好的方法是制作一个单独的页面来提供图像。 Your output image tags should point to that and you need to change the content type in the header of the image service page. 您的输出图像标签应指向该位置,并且您需要更改图像服务页面标题中的内容类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM