PHP-图片上传 [英] PHP - image upload

查看:69
本文介绍了PHP-图片上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

老实说,我不太擅长php,所以我寻求帮助.

Honestly, I'm not very good at php, so I'm asking for help.

以下是图片上传的代码

PHP

session_start();
require_once('../odliczanie/connect.php');
$prof = basename($_FILES["file"]["name"]);
$uploadOk = 1;
if($prof != ""){
    $target_dir = "../odliczanie/images/prof/";
    $target_file = $target_dir . basename($_FILES["file"]["name"]);
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["file"]["tmp_name"]);
        if($check !== false) {
            //echo "Plik jest zdjęciem - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            $_SESSION['how'] = false;
            $_SESSION['msg'] = "Plik nie jest zdjęciem";
            mysqli_close($connection);
            //header("Location: ". $_SESSION['current_page']);
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
            $_SESSION['how'] = false;
        $_SESSION['msg'] = "Nazwa pliku jest już zajęta";
        mysqli_close($connection);
        //header("Location: ". $_SESSION['current_page']);
    }
    // Check file size
    if ($_FILES["file"]["size"] > 104858) {
        $_SESSION['how'] = false;
        $_SESSION['msg'] = "Za duży rozmiar pliku, max 1MB";
        mysqli_close($connection);
        //header("Location: ". $_SESSION['current_page']);
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" ) {
        $_SESSION['how'] = false;
        $_SESSION['msg'] = "Tylko pliki JPG, JPEG i PNG są obsługiwane";
        mysqli_close($connection);
        //header("Location: ". $_SESSION['current_page']);
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        //$_SESSION['e_prof']="Coś było nie tak z tym zdjęciem";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        }
    }
} else {
    $_SESSION['how'] = false;
    $_SESSION['msg'] = "error1";
    mysqli_close($connection);
    //header("Location: ". $_SESSION['current_page']);
}
if ($uploadOk==1){
    //Dodajemy boba do bazy
    $email = $_SESSION['email'];
    //here is error
    if($connection->query("UPDATE `prof` SET `prof` = '".$prof."' WHERE `prof`.`osoba` = '".$email."'")){
        $zapytanie = "select * FROM prof WHERE id = '".$email."'";
        $wynik = mysqli_query($connection,$zapytanie);
        $row = mysqli_fetch_assoc($wynik);
        $profdel = $row['prof2'];
        unlink("/odliczanie/prof/images/$profdel");
        if($connection->query("UPDATE `prof` SET `prof2` = '".$prof."' WHERE `prof`.`osoba` = '".$email."'")){
          $_SESSION['how'] = true;
          $_SESSION['msg'] = "Zdjęcie profilowe zapisane pomyślnie";
          mysqli_close($connectionion);
          //header("Location: ". $_SESSION['current_page']);
        }
    }else{
        $_SESSION['how'] = false;
    $_SESSION['msg'] = "Błąd podczas zapisywania zdjęcia profilowego";
    mysqli_close($connection);
    //header("Location: ". $_SESSION['current_page']);
    }
} else {
    $_SESSION['how'] = false;
    $_SESSION['msg'] = "error2";
    mysqli_close($connection);
    //header("Location: ". $_SESSION['current_page']);
}

这是html表单

HTML

<form method="POST" action="/odliczanie/upload" enctype="multipart/form-data" id="upload" style="padding:16px;">
  <div style="width:300px;height:400px;margin:auto;">
    <? echo "<img id='img' src='/odliczanie/images/prof/$prof' height='300px' width='300px' alt='image preview...'>"; ?><br>
    <input type="file" name="file" id="file" class="inputfile" onchange="previewFile()" />
    <label for="file"><span>Wybierz zdjęcie</span></label><br>
  </div>
  <div class="clearfix">
    <button type="button" class="cancelbtn" onclick="document.getElementById('id02').style.display='none'">Anuluj</button>
      <div style="float:right;">
        <button type="submit" form="form1" value="Submit">Zapisz</button>
      </div>
  </div>
</form>  

有警告消息,我不知道怎么了.

There is warning message and I don't know what's wrong.

警告:mysqli :: query():无法在第61行的/home/kivvi/domains/redrose.pulawy.pl/public_html/odliczanie/upload.php中获取mysqli

Warning: mysqli::query(): Couldn't fetch mysqli in /home/kivvi/domains/redrose.pulawy.pl/public_html/odliczanie/upload.php on line 61

我在php.ini文件file_uploads = On中进行了设置.

I set in php.ini file file_uploads = On.

我尝试使用mysqli_query ($ connection, $ sql)而不是$ connection-> query ($sql),但是它也不起作用.

I tried to use mysqli_query ($ connection, $ sql) instead of $ connection-> query ($sql)but it does not work either.

图像已发送到服务器,但数据库中的记录未更改.有什么建议吗?

The image is sent to the server, but the record in the database doesn't change. Any suggestions?

connect.php内容

connect.php content

$connection = mysqli_connect('localhost', 'kivvi_redrose', '**********');
if(!$connection){
  die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'kivvi_redrose');
if(!$select_db){
  die("Database Selection Failed" . mysqli_error($connection));
}

推荐答案

请参阅下面的代码.这是我定制的.

See my code below. It is custom made by me.

仅剩下的是您需要Use命名空间类.

Only thing left is you need to Use the namespaced class.

也许您可以在下面使用我的代码,因为它将上传多个(如果超过1个)图像.您可以将代码编辑为其他文件,而不是图像.

Perhaps you can use my code below, because it will upload multiple (if there are more than 1) images. You can edit the code to other files instead of images.

要上传的HTML:

<?php echo $this->uploadfile->getImageUploadHTML('imageupload[]', 1) ;?>

致电您的模型:

$result = $this->uploadImage->upload('imageupload', $_FILES['imageupload'], '/uploads/feedback', 'image');

数据库和输出:

下面的代码将返回一个数组,其中包含有关上载图像的所有信息.使用此数组将PATH(和其他信息)保存到数据库中.在您的HTML中,您可以在图片src中回显PATH.

The code below will return an array with all information about the uploaded image(s). Use this array to save the PATH (and any other information) into your database. Within your HTML you can echo the PATH within the image src.

将代码上传到文件夹:

<?php
/**
 * Created by PhpStorm.
 * User: Ronnie Oosting
 * Date: 15-3-18
 * Time: 11:33
 */

namespace Company\Extension;

/**
 * Class UploadFile
 * @package Company\Extension
 * todo: Add different file types to upload: 'PDF, Audio, ?'
 */
class UploadFile
{

	private $allowedImageType;

	private $maxImageSize;

	private $minImageSize;

	private $baseDir;

	private $maxWidth;

	private $maxHeight;

	/**
	 * UploadFile constructor.
	 * @note: Any other file can be added to be uploaded. Only things which are needed:
	 *      1) Make new global settings in the constructor
	 *      2) Create a new private function which is going to be used for your file type
	 *      3) Use the public function 'upload'. Make sure you send the $filetype
	 *      4) Inside the public function 'upload' create a new 'switch' case statement based on your $filetype.
	 */
	public function __construct()
	{
		/**
		 * Image settings.
		 */
		$this->allowedImageType = [
			'image/jpg',
			'image/png',
			'image/jpeg',
		];
		$this->maxImageSize     = 500000;
		$this->minImageSize     = 1;
		$this->baseDir          = BASE_PATH;
		$this->maxWidth         = 1600;
		$this->maxHeight        = 900;
	}

	/**
	 * @param string $name
	 * @param int    $multiple
	 * @param string $type
	 * @param string $accept
	 *
	 * @return string
	 *
	 * @note: Make sure you add '[]' after the name if the multiuploader is activated ($multiple = 1)
	 */
	public function getImageUploadHTML($name = 'imageupload', $multiple = 0, $type = 'file', $accept = 'image/png, image/jpeg, image/jpg')
	{
		$multiple = ($multiple == 1) ? 'multiple' : '';

		return '<input type="' . $type . '" accept="' . $accept . '" name="' . $name . '" ' . $multiple . '>';
	}

	/**
	 * @param string $file_array_name
	 * @param        $file_array_content
	 * @param null   $dir
	 * @param null   $filetype
	 * @param int    $max_width
	 * @param int    $max_height
	 *
	 * @return bool
	 *
	 * @note: The function will return an array or FALSE. Inside the array you find the filename, which can be stored
	 *        into the database.
	 */
	public function upload($file_array_name = 'file1', $file_array_content = [], $dir = null, $filetype = null, $max_width = 99999, $max_height = 99999)
	{
		$file_array_content = $this->reArrayFiles($file_array_content);
		$result             = [];

		foreach($file_array_content as $file_for_each)
		{
			switch($filetype)
			{
				case 'image':
					$result[] = $this->uploadImage($file_array_name, $file_for_each, $dir, $max_width, $max_height);
					break;
				default:
					return false;
			}
		}

		if( empty($result))
		{
			$result = false;
		}

		return $result;
	}

	/**
	 * @param string $file_array_name
	 * @param        $file_array_content
	 * @param null   $dir
	 * @param        $max_width
	 * @param        $max_height
	 *
	 * @return bool
	 */
	private function uploadImage($file_array_name = 'file1', $file_array_content, $dir = null, $max_width, $max_height)
	{

		/**
		 * Check if the given $_FILES is not empty and if it's an array.
		 * If the file is not valid it will return FALSE.
		 *
		 * Check if directory is given, it it's empty it will return FALSE.
		 */
		$file_array_name = strtolower($file_array_name);

		if( !is_array($file_array_content) || $file_array_content['error'] != 0 || !$dir)
		{
			return false;
		}

		/**
		 * A check on the file type. If the file type is not valid it will return FALSE.
		 */
		if( !in_array($file_array_content['type'], $this->allowedImageType))
		{
			return false;
		}

		/**
		 * Check if file is between the allowed sizes.
		 * If the file is not between the allowed sizes it will return FALSE.
		 */
		if(($file_array_content['size'] > $this->maxImageSize) || $file_array_content['size'] < $this->minImageSize)
		{
			return false;
		}

		/**
		 * Get the file extension.
		 * If the file extension is not valid, it will return FALSE.
		 */
		$file_name      = explode(".", $file_array_content['name']);
		$file_extension = end($file_name);

		if( !$file_extension)
		{
			return false;
		}

		/**
		 * Create the file settings for easier reading and to upload.
		 */
		list($image_width, $image_height) = getimagesize($file_array_content['tmp_name']);

		$file_settings = [
			'tmp_name'  => $file_array_content['tmp_name'],
			'file_name' => date('YmdHis') . '_' . md5($file_array_name) . '_' . rand($this->minImageSize, $this->maxImageSize) . '.' . $file_extension,
			'size'      => $file_array_content['size'],
			'width'     => $image_width,
			'height'    => $image_height,
		];

		/**
		 * Check resolution of file.
		 * Both WIDTH and HEIGHT are being checked, first it will check if the file is not higher than the max size,
		 * second it will check the given input (if it's given). If needed it will crop to the maximum allowed sizes.
		 */
		$set_width  = ($max_width) ? $max_width : $this->maxWidth;
		$set_height = ($max_height) ? $max_height : $this->maxHeight;
		if(($file_settings['width'] > $set_width) || ($file_settings['height'] > $set_height))
		{
			/**
			 * Crop the WIDTH / HEIGHT image. WIDTH is being sent to the function cropImage.
			 */
			$this->cropImage($file_settings['tmp_name'], $this->baseDir . $dir . '/' . $file_settings['file_name'], $set_height);
		}
		else
		{
			/**
			 * Upload the file.
			 * If the file is not uploaded it will return FALSE.
			 */
			if( !move_uploaded_file($file_settings['tmp_name'], $this->baseDir . $dir . '/' . $file_settings['file_name']))
			{
				return false;
			}
		}

		return $file_settings;
	}

	/**
	 * @param $src
	 * @param $dest
	 * @param $max
	 *
	 * @return bool
	 */
	private function cropImage($src, $dest, $max)
	{
		/**
		 * Get size
		 */
		list($width, $height, $source_image_type) = getimagesize($src);

		switch(strtolower($source_image_type))
		{
			case IMAGETYPE_GIF:
				$image = imagecreatefromgif($src);
				break;
			case IMAGETYPE_JPEG:
				$image = imagecreatefromjpeg($src);
				break;
			case IMAGETYPE_PNG:
				$image = imagecreatefrompng($src);
				break;
		}

		/**
		 * Set new sizes
		 */
		$source_aspect_ratio  = $width / $height;
		$desired_aspect_ratio = $max / $max;

		if($source_aspect_ratio > $desired_aspect_ratio)
		{
			$temp_height = $max;
			$temp_width  = ( int ) ($max * $source_aspect_ratio);
		}
		else
		{
			$temp_width  = $max;
			$temp_height = ( int ) ($max / $source_aspect_ratio);
		}

		/**
		 * Create new size
		 */
		$temp_gdim = imagecreatetruecolor($temp_width, $temp_height);
		imagecopyresampled($temp_gdim, $image, 0, 0, 0, 0, $temp_width, $temp_height, $width, $height);

		$x0 = ($temp_width - $max) / 2;
		$y0 = ($temp_height - $max) / 2;

		$desired_gdim = imagecreatetruecolor($max, $max);
		imagecopy($desired_gdim, $temp_gdim, 0, 0, $x0, $y0, $max, $max);
		imagejpeg($desired_gdim, $dest, 98);
		imagedestroy($image);
		imagedestroy($desired_gdim);

		return true;
	}

	/**
	 * @param $file_post
	 *
	 * @return array
	 */
	private function reArrayFiles(&$file_post)
	{
		$file_ary   = array();
		$file_count = count($file_post['name']);
		$file_keys  = array_keys($file_post);

		for($i = 0; $i < $file_count; $i++)
		{
			foreach($file_keys as $key)
			{
				$file_ary[$i][$key] = $file_post[$key][$i];
			}
		}

		return $file_ary;
	}
}

这篇关于PHP-图片上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆