PHP - image upload

懵懂的女人 提交于 2019-12-13 09:25:12

问题


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

Here is code for image upload

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

And here is html form

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.

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

I set in php.ini file file_uploads = On.

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?

Edit:

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

回答1:


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

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

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 to upload:

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

Call to your model:

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

Database and output:

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.

Upload Code to folder:

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


来源:https://stackoverflow.com/questions/49365315/php-image-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!