php PHP上传图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13465929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:29:51  来源:igfitidea点击:

PHP upload image

phpimageupload

提问by user1544586

Alright I have way to much time invested in this. I am new to PHP programming and trying to grasp the basics, but I am a little lost as of last night I was able to get a PHP form to upload basic data like a name address and stuff to my (MySQL) server.

好吧,我在这方面投入了大量时间。我是 PHP 编程的新手并试图掌握基础知识,但截至昨晚我有点迷茫,我能够获得一个 PHP 表单来将基本数据(如名称地址和内容)上传到我的(MySQL)服务器。

But today I said let's do the next step which would be an image to the server. I have watched 3 videos on YouTube probably a 100 times just recoping code and trying it in so many different ways.

但是今天我说让我们做下一步,将图像发送到服务器。我在 YouTube 上观看了 3 个视频,大概 100 次,只是重新编写代码并以多种不同的方式尝试它。

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

and still haven't been able to get it.

并且仍然无法得到它。

But long story short: I have a config.php file that connects to the server and here is the the code I'm running on the upload form page:

但长话短说:我有一个连接到服务器的 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>

The reason for all the '', '', '', ''on the insert line is because I have the name in the 10th field and the image blob in the 11th and all the ones leading up to that are first name, last name and random stuff like that. How can I fix this? It is returning the error:

'', '', '', ''插入行上所有的原因是因为我在第 10 个字段中有名称,在第 11 个字段中有图像 blob,所有导致该字段的都是名字、姓氏和类似的随机内容。我怎样才能解决这个问题?它正在返回错误:

Fatal error: Call to undefined function file_get_content() in /home/content/34/9587634/html/WEBPAGE/UploadContent.php on line 22

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

I don't know what to do.

我不知道该怎么办。

回答by ???? ?????

The code overlooks calling the function move_uploaded_file() which would check whether the indicated file is valid for uploading.

该代码忽略调用函数 move_uploaded_file() ,该函数将检查指示的文件是否可用于上传。

You may wish to review a simple example at:

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

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

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

回答by Mudassir Hasan

Change function file_get_content()in your code to file_get_contents(). You are missing 's' at the end of function name. That is why it is giving undefined function error.

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

file_get_contents()

file_get_contents()

Remove last unnecessary comma after $imagefiled in line

$image在线提交后删除最后一个不必要的逗号

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

回答by Kannan Chakkara

You need to add two new file one is index.html, copy and paste the below code and other is imageup.php which will upload your image

您需要添加两个新文件,一个是 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);
 ?>

The above code will upload your image with encrypted name

上面的代码将使用加密名称上传您的图像

回答by Supun Kavinda

I would recommend you to save the image in the server, and then save the URL in MYSQL database.

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

First of all, you should do more validation on your image, before non-validated files can lead to huge security risks.

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

  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');
    
  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');
    

This might help you to create a secure image uploading script with PHP.

这可能会帮助您使用 PHP 创建安全的图像上传脚本。

Code source: https://developer.hyvor.com/php/image-upload-ajax-php-mysql

代码来源:https: //developer.hyvor.com/php/image-upload-ajax-php-mysql

Additionally, I suggest you use MYSQLI prepared statementsfor queries to improve security.

此外,我建议您使用MYSQLI 准备好的查询语句来提高安全性。

Thank you.

谢谢你。

回答by Sumit Kumar Gupta

This code is very easy to upload file by php. In this code I am performing uploading task in same page that mean our html and php both code resides in the same file. This code generates new name of image name.

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

first of all see the html code

首先看html代码

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

now see the php code

现在看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);
?>

回答by Majbah Habib

Simple PHP file/image uploadcode on same page.

同一页面上的简单 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'; 
   }

 ?>

回答by Hymans

Here is a basic example of how an image file with certain restrictions (listed below) can be uploaded to the server.

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

  • 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 thispage.

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

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

    归功于页面。

回答by saad mohmed

  <?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");
 ?>

回答by SAgar

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

?>