【问题标题】:PHP upload imagePHP上传图片
【发布时间】:2012-11-08 02:10:46
【问题描述】:

好吧,我在这方面投入了很多时间。我是 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 个字段中有名称,在第 11 个字段中有图像 blob,所有导致这些的都是名字、姓氏和随机的东西,比如那。我怎样才能解决这个问题?它正在返回错误:

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

我不知道该怎么办。

【问题讨论】:

    标签: php image upload


    【解决方案1】:

    将代码中的函数 file_get_content() 更改为 file_get_contents() 。您在函数名称的末尾缺少“s”。这就是它给出未定义函数错误的原因。

    file_get_contents()

    删除$image 后的最后一个不必要的逗号

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

    【讨论】:

    • 谢谢你解决了我的错误,现在我没有输出女巫很奇怪
    • 哇,谢谢你让我觉得自己像个白痴,不是一次而是两次,哈哈,真的感谢你花了四个小时
    【解决方案2】:

    代码忽略了调用函数 move_uploaded_file() 来检查指示的文件是否可以上传。

    您可能希望在以下位置查看一个简单示例:

    http://www.w3schools.com/php/php_file_upload.asp

    【讨论】:

    • 嗯,谢谢,但我在这部分迷路了,我没有解决错误,但我不知道如何将文件放入我声称 move_upload_file 的 mysql 服务器,但我似乎无法理解工作。
    • 如何上传文件存储在目录路径中?
    【解决方案3】:

    你需要添加两个新文件,一个是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】:
      <?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;
      }
      
      ?> 
      

      【讨论】:

      • 纯代码响应被认为是低质量的。请通过单击编辑并在您的答案中添加一些细节来总结您的代码的作用。
      【解决方案5】:
        <?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");
       ?>
      

      【讨论】:

        【解决方案6】:

        我会建议你将图片保存在服务器中,然后将 URL 保存在 MYSQL 数据库中。

        首先,您应该对图像进行更多验证,以免未经验证的文件导致巨大的安全风险。

        1. 查看图片

          if (empty($_FILES['image']))
            throw new Exception('Image file is missing');
          
        2. 将图像保存在变量中

          $image = $_FILES['image'];
          
        3. 检查上传时间错误

          if ($image['error'] !== 0) {
             if ($image['error'] === 1) 
                throw new Exception('Max upload size exceeded');
          
             throw new Exception('Image uploading error: INI Error');
          }
          
        4. 检查上传的文件是否存在于服务器中

          if (!file_exists($image['tmp_name']))
              throw new Exception('Image file is missing in the server');
          
        5. 验证文件大小(根据需要更改)

           $maxFileSize = 2 * 10e6; // = 2 000 000 bytes = 2MB
              if ($image['size'] > $maxFileSize)
                  throw new Exception('Max size limit exceeded'); 
          
        6. 验证图片(检查文件是否为图片)

           $imageData = getimagesize($image['tmp_name']);
               if (!$imageData) 
               throw new Exception('Invalid image');
          
        7. 验证图像 mime 类型(根据您的需要执行此操作)

           $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 prepared statements 进行查询以提高安全性。

        谢谢。

        【讨论】:

        • empty($_FILES['image']) 如果文件未上传,也返回 true。数组([名称] => [类型] => [tmp_name] => [错误] => 4 [大小] => 0)
        • 我得到Undefined index: mime .is mime 被贬低了吗?
        【解决方案7】:

        这段代码很容易通过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);
        ?>
        

        【讨论】:

        • 谢谢,这对我很有帮助
        【解决方案8】:

        简单的 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'; 
           }
        
         ?>
        

        【讨论】:

          【解决方案9】:

          这是一个基本示例,说明如何将具有某些限制(如下所列)的图像文件上传到服务器。

          • 图像存在。
          • 图片扩展验证
          • 检查图像大小。

            <?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>
            

            归功于this 页面。

          【讨论】:

            猜你喜欢
            • 2016-10-12
            • 2011-03-16
            • 2013-04-29
            • 2014-07-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多