从URL复制图像,更改名称并保存到文件夹

时间:2014-09-04 00:07:56

标签: php

我即将开始使用PHP脚本导入csv数据库。

csv有一个包含产品图片网址的列。

我需要做的是获取图像,检查它是什么类型的文件(jpg,png等),更改名称,将文件保存到服务器上的文件夹,然后将文件名插入数据库。

插入数据库我可以做的事情,它重新命名的文件与我混淆。

是否可以像上传文件一样获取信息,例如:

使用html格式的文件输入上传文件

$_FILES['file']['name'];
or
$_FILES['file']['type'];

如果下载文件,可能会这样吗

$downloaded_image['name'];
or
$downloaded_image['type'];

还是完全不合适?

我以前从未这样做过,而且stackoverflow上的大部分答案都没有完全回答我的问题,所以希望有人能指出我正确的方向如何做到这一点。

EDITED /更新:

这样的事情是否可以获得文件属性......

$image_id = '123456';
$the_image = file_get_contents($downloaded_image);
$image_name = $the_image['name'];
$image_type = $the_image['type'];

$new_name = $image_id . '.' . $image_type;

$img_path = '/images/';
$save_image = file_put_contents($img_path, $new_name);
if($save_image) {
echo 'image saved';
} else {
echo 'Not Saved';
}

希望我有所作为。

更新:这是脚本原样(仍需要整理)

define('CSV_PATH','E:/xampp/htdocs/aff/csv-import/');
// path where your CSV file is located

$csv_file = CSV_PATH . "infotuts.csv"; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
    $csv_data[] = fgets($csvfile, 1024);
    $csv_array = explode(",", $csv_data[$i]);
    $insert_csv = array();
    $insert_csv['test_id'] = $csv_array[0];
    // $insert_csv['test_aw_id'] = $csv_array[1];
    // $insert_csv['test_name'] = $csv_array[2];
    $image_id = $csv_array[1];
    $download_image = $csv_array[2];

    // Store the original filename
    $original_name = basename($download_image);

    // Original extension by string manipulation
    $original_extension = substr($original_name, strrpos($original_name, '.')); // ".jpg"

    // An array to match mime types from finfo_file() with extensions
    // Use of finfo_file() is recommended if you can't trust the input
    // filename's extension
    $types = array('image/jpeg' => '.jpg','image/png' => '.png','image/gif' => '.gif');

    // Get the file and save it
    $img = file_get_contents($download_image);
    $stored_name = 'images/' . $image_id . $original_extension;
    if ($img) {
      file_put_contents($stored_name);

      // Get the filesize if needed
      $size = filesize($stored_name);

      // If you don't care about validating the mime type, skip all of this...
      // Check the file information
      $finfo = finfo_open(FILEINFO_MIME_TYPE);
      $mimetype = finfo_file($finfo, $stored_name);

      // Lookup the type in your array to get the extension
      if (isset($types[$mimetype])) {
        // if the reported type doesn't match the original extension, rename the file
        if ($types[$mimetype] != $original_extension) {
          rename($stored_name, 'images/' . $image_id . $types[$mimetype]);
        }
      }
      else {
        // unknown type, handle accordingly...
      }
      finfo_close($finfo);

        $query = "INSERT INTO test(test_id, test_aw_id, test_name) VALUES ('', '$image_id', '$stored_name')";
        $n=mysqli_query($con, $query);
        $i++;
    }
    else {
      echo 'Could not get file';
    }

}
fclose($csvfile);

2 个答案:

答案 0 :(得分:4)

通过file_get_contents()检索文件,您将无法获得有关其格式的任何特别有用的信息。它不包含类似于$_FILES中的上传内容的元数据。

如果图片网址应该是带有扩展名的完整文件名,并且您信任该扩展程序是正确的,那么您可以将其用作您的类型。但是,使用FILEINFO_MIME_TYPE选项的finfo_file()将探测文件以返回其mime类型,如image/jpegimage/png

因此,您的工作流程将是:

  1. 使用file_get_contents()
  2. 检索图像
  3. 使用新名称
  4. 将其保存到本地文件系统
  5. 致电finfo_file()以检索其mime类型
  6. 使用所需的详细信息更新您的数据库。
  7. 示例:

    // Assume this URL for $download_image from your CSV
    $download_image = 'http://example.com/images/img1.jpg';
    $image_id = 12345;
    
    // Store the original filename
    $original_name = basename($download_image); // "img1.jpg"
    // Original extension by string manipulation
    $original_extension = substr($original_name, strrpos($original_name, '.')); // ".jpg"
    
    // An array to match mime types from finfo_file() with extensions
    // Use of finfo_file() is recommended if you can't trust the input
    // filename's extension
    $types = array(
      'image/jpeg' => '.jpg',
      'image/png' => '.png',
      'image/gif' => '.gif'
      // Other types as needed...
    );
    
    // Get the file and save it
    $img = file_get_contents($download_image);
    $stored_name = 'images/' . $image_id . $original_extension;
    if ($img) {
      file_put_contents($stored_name, $img);
    
      // Get the filesize if needed
      $size = filesize($stored_name);
    
      // If you don't care about validating the mime type, skip all of this...
      // Check the file information
      $finfo = finfo_open(FILEINFO_MIME_TYPE);
      $mimetype = finfo_file($finfo, $stored_name);
    
      // Lookup the type in your array to get the extension
      if (isset($types[$mimetype])) {
        // if the reported type doesn't match the original extension, rename the file
        if ($types[$mimetype] != $original_extension) {
          rename($stored_name, 'images/' . $image_id . $types[$mimetype]);
        }
      }
      else {
        // unknown type, handle accordingly...
      }
      finfo_close($finfo);
    
      // Now save all the extra info you retrieved into your database however you normally would
      // $mimetype, $original_name, $original_extension, $filesize
    }
    else {
      // Error, couldn't get file
    }
    

    如果您想从已有的扩展名中获取mimetype字符串,并且未使用finfo验证类型,可以将$types翻转为包含值的交换键。

    if (in_array($original_extension), $types) {
      $mimetype = array_flip($types)[$original_extension];
    }
    

答案 1 :(得分:0)

<?php

include_once('includes/functions.php');

define('CSV_PATH','E:/xampp/htdocs/aff/csv-import/');

$csv_file = CSV_PATH . "infotuts.csv";
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
    $csv_data[] = fgets($csvfile, 1024);
    $csv_array = explode(",", $csv_data[$i]);
    $insert_csv = array();
    $insert_csv['test_id'] = $csv_array[0];
    $insert_csv['test_aw_id'] = $csv_array[1];
    $insert_csv['test_name'] = $csv_array[2];

    $image_id = $insert_csv['test_aw_id'];
    $download_image = $insert_csv['test_name'];

    $original_name = basename($download_image);

    $original_extension = substr($original_name, strrpos($original_name, '.')); // ".jpg"

    $types = array('image/jpeg' => '.jpg','image/png' => '.png','image/gif' => '.gif');

    $img = file_get_contents($download_image);
    $stored_name = $image_id . $original_extension;
    $stored_name = trim($stored_name);
    if ($img) {
      file_put_contents($stored_name, $img);

      //$size = filesize($stored_name);

      $finfo = finfo_open(FILEINFO_MIME_TYPE);
      $mimetype = finfo_file($finfo, $stored_name);
      if (isset($types[$mimetype])) {
        if ($types[$mimetype] != $original_extension) {
          rename($stored_name, 'E:/xampp/htdocs/aff/images/products/' . $stored_name);

        }
      }
      else {

      }
      finfo_close($finfo);

        $query = "INSERT INTO test(test_id, test_aw_id, test_name) VALUES ('', '$image_id', '$stored_name')";
        $n=mysqli_query($con, $query);
        $i++;
    }
    else {
      echo 'Could not get file';
    }

}
fclose($csvfile);

echo "File data successfully imported to database!!";
mysqli_close($con);
?>