PHP上传图片

15

我已经在这上面投入了太多的时间。我是PHP编程的新手,试图掌握基础知识,但昨晚我有点迷失方向,能够让PHP表单上传类似姓名、地址和其他基本数据到我的(MySQL)服务器。

但今天我说让我们进行下一步,也就是将图片上传到服务器。 我在YouTube上看了3个视频,大概重复了100遍的代码并尝试了很多不同的方式。

http://www.youtube.com/watch?v=CxY3FR9doHI
http://www.youtube.com/watch?v=vFZfJZ_WNC4&feature=relmfu

我仍然无法获得它。

简而言之:我有一个连接到服务器的config.php文件,以下是我在上传表单页面上运行的代码:

<html>
  <head>
    <title>Upload an image</title>
  </head>
<body>
  <form action="UploadContent.php" method="POST" enctype="multipart/form-data">
  File:
    <input type="file" name="image"> <input type="submit" value="Upload">
  </form>
<?php

// connect to database
include"config.php";

// file properties
$file = $_FILES['image']['tmp_name'];

if (!isset($file))
  echo "Please select a profile pic";
else
{
  $image = addslashes(file_get_content($_FILES['image']['tmp_name']));
  $image_name = addslashes($FILES['image']['name']);
  $image_size = getimagesize($_FILES['image']['tmp_name']);

  if ($image_size==FALSE)
    echo "That isn't a image.";
  else
  {
    $insert = mysql_query("INSERT INTO content VALUES ('','','','','','','','','','$image_name','$image',)");
  }
}
?>
  </body>
</html>

在插入行中出现所有'', '', '', ''的原因是因为我将名称放在第10个字段中,图像blob放在第11个字段中,所有前面的都是名字,姓氏和类似于那样的随机信息。我该如何解决这个问题?它返回以下错误:

致命错误:在/home/content/34/9587634/html/WEBPAGE/UploadContent.php的第22行调用未定义的函数file_get_content()

我不知道该怎么办。

9个回答

10

谢谢,但我在这部分迷失了方向。我已经解决了错误,但我无法弄清楚如何将文件传输到我的MySQL服务器。你说可以使用move_upload_file,但我似乎无法让它起作用。 - Bishop Morley
如何上传存储在目录路径中的文件? - Sarthak Raval

6

您需要添加两个新文件,一个是index.html,复制并粘贴以下代码,另一个是imageup.php,它将上传您的图像。

 <form action="imageup.php" method="post" enctype="multipart/form-data">
 <input type="file" name="banner" >
 <input type="submit" value="submit">
 </form>

 imageup.php
 <?php
 $banner=$_FILES['banner']['name']; 
 $expbanner=explode('.',$banner);
 $bannerexptype=$expbanner[1];
 date_default_timezone_set('Australia/Melbourne');
 $date = date('m/d/Yh:i:sa', time());
 $rand=rand(10000,99999);
 $encname=$date.$rand;
 $bannername=md5($encname).'.'.$bannerexptype;
 $bannerpath="uploads/banners/".$bannername;
 move_uploaded_file($_FILES["banner"]["tmp_name"],$bannerpath);
 ?>

以上代码将以加密的方式上传您的图片。

4
我建议你将图片保存在服务器上,然后将URL保存在MYSQL数据库中。首先,在非验证文件之前,应对您的图像进行更多的验证,因为非验证文件可能会导致巨大的安全风险。
  1. Check the image

    if (empty($_FILES['image']))
      throw new Exception('Image file is missing');
    
  2. Save the image in a variable

    $image = $_FILES['image'];
    
  3. Check the upload time errors

    if ($image['error'] !== 0) {
       if ($image['error'] === 1) 
          throw new Exception('Max upload size exceeded');
    
       throw new Exception('Image uploading error: INI Error');
    }
    
  4. Check whether the uploaded file exists in the server

    if (!file_exists($image['tmp_name']))
        throw new Exception('Image file is missing in the server');
    
  5. Validate the file size (Change it according to your needs)

     $maxFileSize = 2 * 10e6; // = 2 000 000 bytes = 2MB
        if ($image['size'] > $maxFileSize)
            throw new Exception('Max size limit exceeded'); 
    
  6. Validate the image (Check whether the file is an image)

     $imageData = getimagesize($image['tmp_name']);
         if (!$imageData) 
         throw new Exception('Invalid image');
    
  7. Validate the image mime type (Do this according to your needs)

     $mimeType = $imageData['mime'];
     $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
     if (!in_array($mimeType, $allowedMimeTypes)) 
        throw new Exception('Only JPEG, PNG and GIFs are allowed');
    
这可能会帮助您使用PHP创建安全的图片上传脚本。
代码来源:https://developer.hyvor.com/php/image-upload-ajax-php-mysql 此外,我建议您使用MYSQLI准备语句来查询以提高安全性。
谢谢。

empty($ _ FILES ['image'])返回true,即使文件没有被上传。 数组 (     [name] =>     [type] =>     [tmp_name] =>     [error] => 4     [size] => 0 ) - Gianluca Demarinis
我收到了 Undefined index: mime 的错误消息。mime 是否已经被废弃? - Zahra

4

请将您代码中的函数file_get_content()更改为file_get_contents()。您漏掉了函数名称末尾的“s”,这就是为什么会出现未定义函数错误的原因。

file_get_contents()

请删除$image字段后面多余的逗号。

"INSERT INTO content VALUES         ('','','','','','','','','','$image_name','$image',)

谢谢,这解决了我的错误,但现在我没有输出,这很奇怪。 - Bishop Morley
哇,谢谢你让我感觉像个白痴,不止一次,哈哈。真的谢谢你,为此花了四个小时。 - Bishop Morley

2

在同一页上上传简单的PHP文件/图片代码。

<form action="" method="post" enctype="multipart/form-data">
  <table border="1px">
    <tr><td><input type="file" name="image" ></td></tr>
    <tr><td> <input type="submit" value="upload" name="btn"></td></tr>
  </table>
</form>

 <?php
   if(isset($_POST['btn'])){
     $image=$_FILES['image']['name']; 
     $imageArr=explode('.',$image); //first index is file name and second index file type
     $rand=rand(10000,99999);
     $newImageName=$imageArr[0].$rand.'.'.$imageArr[1];
     $uploadPath="uploads/".$newImageName;
     $isUploaded=move_uploaded_file($_FILES["image"]["tmp_name"],$uploadPath);
     if($isUploaded)
       echo 'successfully file uploaded';
     else
       echo 'something went wrong'; 
   }

 ?>

1
这是一个基本示例,演示如何将带有以下限制的图像文件上传到服务器。
  • Existence of the image.
  • Image extension validation
  • Checks for image size.

    <?php
       $newfilename = "newfilename";
    
       if(isset($_FILES['image'])){
          $errors= array();
          $file_name = $_FILES['image']['name'];
          $file_size =$_FILES['image']['size'];
          $file_tmp =$_FILES['image']['tmp_name'];
          $file_type=$_FILES['image']['type'];
          $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
    
          $expensions= array("jpeg","jpg","png");
          if(file_exists($file_name)) {
            echo "Sorry, file already exists.";
            }
          if(in_array($file_ext,$expensions)=== false){
             $errors[]="extension not allowed, please choose a JPEG or PNG file.";
          }
    
          if($file_size > 2097152){
             $errors[]='File size must be excately 2 MB';
          }
    
          if(empty($errors)==true){
            move_uploaded_file($file_tmp,"images/".$newfilename.".".$file_ext);
            echo "Success";
            echo "<script>window.close();</script>";
    
          }
    
          else{
             print_r($errors);
          }
       }
    ?>
    <html>
       <body>
    
          <form action="" method="POST" enctype="multipart/form-data">
             <input type="file" name="image" />
             <input type="submit"/>
          </form>
    
       </body>
    </html>
    

    Credit to this page.


这一行代码 ' if(empty($errors)==true){ ' 应该修改为 ' if(!count($errors)){ ',因为变量 $errors 已经被赋值为一个空数组。在没有错误的情况下,使用 count($errors) == 0 也是最佳的方式。 - MaZzIMo24

0
<?php

$filename=$_FILES['file']['name'];
$filetype=$_FILES['file']['type'];
if($filetype=='image/jpeg' or $filetype=='image/png' or $filetype=='image/gif')
{
move_uploaded_file($_FILES['file']['tmp_name'],'dir_name/'.$filename);
$filepath="dir_name`enter code here`/".$filename;
}

?> 

2
仅提供代码响应被认为是低质量的。请通过单击编辑并向您的答案添加一些详细信息来总结您的代码所做的事情。 - Mozahler

0
  <?php 
 $target_dir = "images/";
    echo $target_file = $target_dir . basename($_FILES["image"]["name"]);
    $post_tmp_img = $_FILES["image"]["tmp_name"];
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    $post_imag = $_FILES["image"]["name"];
        move_uploaded_file($post_tmp_img,"../images/$post_imag");
 ?>

0

这段代码非常容易通过php上传文件。在这段代码中,我在同一页中执行上传任务,这意味着我们的html和php代码都驻留在同一个文件中。此代码生成新的图像名称。

首先看一下html代码

<form action="index.php" method="post" enctype="multipart/form-data">
 <input type="file" name="banner_image" >
 <input type="submit" value="submit">
 </form>

现在看看 PHP 代码

<?php
$image_name=$_FILES['banner_image']['name'];
       $temp = explode(".", $image_name);
        $newfilename = round(microtime(true)) . '.' . end($temp);
       $imagepath="uploads/".$newfilename;
       move_uploaded_file($_FILES["banner_image"]["tmp_name"],$imagepath);
?>

谢谢,这对我非常有帮助。 - Sumit Kumar Gupta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接