PHP图片上传功能,保存在目录中然后返回保存图片的网址

时间:2013-09-14 11:01:29

标签: php

我正在尝试使用PHP将图像上传到服务器并在目录中保存,然后返回图像网址。

HTML:

<input name="photo" type="file" />

PHP

save_string_to_database( upload_img($_POST['photo']));

我对PHP不太了解,我从SO获得了代码,但它没有做任何事情。请帮我修复此代码,或者提供一个简单的代码来执行上传:

function upload_img($img){
    if ((($_FILES[$img]["type"] == "image/gif")
    || ($_FILES[$img]["type"] == "image/jpeg")
    || ($_FILES[$img]["type"] == "image/pjpeg")
    || ($_FILES[$img]["type"] == "image/jpg")
    || ($_FILES[$img]["type"] == "image/png"))
    && ($_FILES[$img]["size"] < 20000)
    && (strlen($_FILES[$img]["name"]) < 51)){
       if ($_FILES[$img]["error"] > 0){
           echo "Return Code: " . $_FILES[$img]["error"];
       }
       else{
           // echo "Upload: " . $_FILES["image"]["name"] . "<br />";
           // echo "Type: " . $_FILES["image"]["type"] . "<br />";
           // echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
           //  echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br />";

           if (file_exists(THEME_DIR."/images/" . $_FILES[$img]["name"])){
               echo $_FILES[$img]["name"] . " already exists. ";
           }
           else{
               move_uploaded_file($_FILES[$img]["tmp_name"],THEME_DIR."/images/"  . $_FILES[$img]["name"]);
               return THEME_DIR."/images/"  . $_FILES[$img]["name"];
           }
       }
   }
}

5 个答案:

答案 0 :(得分:16)

这是一个简单的。

用于上传图片的HTML表单

<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="512000" />
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

执行上传

的PHP文件
<?php

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo "<p>";

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
  echo "File is valid, and was successfully uploaded.\n";
} else {
   echo "Upload failed";
}

echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";

?> 

<强> Source

答案 1 :(得分:6)

首先,您需要 multipart / form-data 表单进行上传。这是必须的:)

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

PHP部分相当简单: 这会导致您的文件存储在“upload / {filename}”中 您要考虑的主要部分是如何获取文件名并返回到write_string_to_database过程,您可以在上传页面后执行一个简单的脚本,如

save_string_to_database("upload/" . $_FILES["file"]["name"]);

会做到这一点。

<?php
if ($_FILES["file"]["error"] > 0)
  {
  echo "Error: " . $_FILES["file"]["error"] . "<br>";
  }
else
  {
  move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
  }
}

答案 2 :(得分:1)

用于文件上传试试这个

<?php if(isset($_POST['submit']))
{
$ImageName = $_FILES['photo']['name'];
$fileElementName = 'photo';
$path = 'images/'; 
$location = $path . $_FILES['photo']['name']; 
move_uploaded_file($_FILES['photo']['tmp_name'], $location); 
} ?>
<form name="form1" id="form1" method="post" action="" enctype="multipart/form-data">
<input type="file" name="photo">
<input type="submit" name="submit">
</form>

答案 3 :(得分:0)

这是我的函数,变量$ ten_anh是html中文件图像的名称。

function upload_anh($ten_anh){ //$ten_anh la ten tren html vi du "avatar"
if(isset($_FILES[$ten_anh])){
     $errors= array();
     $file_name = $_FILES[$ten_anh]['name'];
     $file_size =$_FILES[$ten_anh]['size'];
     $file_tmp =$_FILES[$ten_anh]['tmp_name'];
     $file_type=$_FILES[$ten_anh]['type'];
     $file_ext=strtolower(end(explode('.',$_FILES[$ten_anh]['name'])));

     $expensions= array("jpeg","jpg","png");

     if(in_array($file_ext,$expensions)=== false){
            $errors[]="Không chấp nhận định dạng ảnh có đuôi này, mời bạn chọn JPEG hoặc PNG.";
     }

     if($file_size > 2097152){
            $errors[]='Kích cỡ file nên là 2 MB';
     }

     if(empty($errors)==true){
            move_uploaded_file($file_tmp,"../images/".$file_name);
            echo "Thành công!!!";
     }
     else{
            print_r($errors);
     }
}

}

示例:  -html代码:

<input type="file" id="avatar" name="avatar"accept="image/png, image/jpeg"      required/>
  • 调用函数php:upload_anh('avatar');

答案 4 :(得分:0)

<form method='post' action='' enctype='multipart/form-data'> 
  Name  : <input type="text" name="name"  required=""/><br><br>
  Code  : <input type="text" name="code"  required=""/><br><br>
  Price : <input type="text" name="price" required=""/><br><br>
  Image : <input type="file" name="image" required=""/><br><br>
  <button type='submit' class='buy' name="submit">Add Now</button>
</form>
<!--insert data  -->
<?php
session_start();
include('db.php');

if(isset($_POST["submit"]));
{
  /*echo "<pre>";
  print_r($_POST);
  print_r($_FILES);*/
  $name  = $_POST["name"];
  $code  = $_POST["code"];
  $price = $_POST["price"];
  $image = $_FILES["image"]["name"];

  /* folder image save */

  // $target_dir  = "/var/www/html/shivam/new/upload/";
  // $target_file = $target_dir.basename($_FILES["image"]["name"]);
  // /*echo "1121".$target_file;*/

  // $name = basename($_FILES["image"]["name"]);

  // mysqli_query($con,$qry);

  // /* move file */                                   
  // move_uploaded_file($_FILES['image']['tmp_name'],$target_dir.$name);
  /* move_uploaded_file($tmp_name, "$target_dir/$name");*/
  /* end */

  $uploaddir = '/var/www/html/uploads/';
$uploadfile = $uploaddir . basename($_FILES['image']['name']);
echo '44'.$uploadfile;
echo "<p>";

if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
  echo "File is valid, and was successfully uploaded.\n";
} else {
   echo "Upload failed";
}

echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';enter code here
print_r($_FILES);
print "</pre>";
}
?>