<?php
	session_start();
	session_regenerate_id(true);
	if(!isset($_SESSION['user'])){
		header("Location: index.php");
		exit;
	}
	
	if(!isset($_POST['submit']) || empty($_FILES)){
		header("Location: gallery.php");
		exit;
	}
	
/*	$type = $_FILES['fileToUpload']['type'];
	if($type != "image/jpeg" && $type != "image/png" && $type != "image/gif" ){
		echo 'Only images are allowed!';
		exit;
	}*/
	
	$path = $_FILES['fileToUpload']['name'];
	$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
	$allowedExtensions = array("jpg", "png", "gif");
	if(!in_array($ext, $allowedExtensions)){
		echo 'Only images are allowed!';
		exit;		
	}
		
	if(getimagesize($_FILES['fileToUpload']['tmp_name'])==false){
		echo 'You uploaded broken image';
		exit;
	}
	
	if($ext == "jpg"){
		$cleanimage = imagecreatefromjpeg($_FILES['fileToUpload']['tmp_name']);
		imagejpeg($cleanimage, $_FILES['fileToUpload']['tmp_name'], 90);
	}
	
	if($ext == "png"){
		$cleanimage = imagecreatefrompng($_FILES['fileToUpload']['tmp_name']);
		imagepng($cleanimage, $_FILES['fileToUpload']['tmp_name'], 0);
	}
	
	// Аналогично за gif
	
	
	$target = "./uploads/".hash("sha256",openssl_random_pseudo_bytes(12).basename($path)).".".$ext;
	
	if(!move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target)){
		echo 'Error uploading file';
		exit;
	}
	
	echo 'Upload success. <a href="gallery.php">Back to gallery</a>';
?>