I have these code below to upload single image with compression. but right now I want to upload multiple image. Can someone help with with upload multiple image using the code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Compress and Check</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" accept="image/*" />
<input type="submit" name="btnsubmit" value="submin" id="submit" />
</form>
</body>
</html>
<?php
function compress_image($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source_url);
elseif ($info['mime'] == 'image/jpg') $image = imagecreatefrompng($source_url);
imagejpeg($image, $destination_url, $quality);
return $destination_url;
}
if(isset($_POST['btnsubmit'])){
if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != ""){
$filename = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$file_error = $_FILES['file']['error'];
$target_dir = "img/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$uploadOk = 1;
if(file_exists($target_file)){ exist or not
echo "<script>alert('sorry, file already exists.');</script>";
$uploadOk = 0;
}else if ($file_size > 500000) {
echo "<script>alert('sorry, your file is too large.');</script>";
$uploadOk = 0;
}else if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "<script>alert('sorry, only JPG, JPEG, PNG & GIF files are allowed.');</script>";
$uploadOk = 0;
}else if($file_error > 0){
echo "<script>alert('Your file is corrupted!');</script>";
$uploadOk = 0;
}
if($uploadOk == 0){
echo "<script>alert('sorry, your file was not uploaded!');</script>";
}else{
$rand = md5(sha1(rand(10000, 10000000)));
$url = $target_dir . $rand . '.jpg';
$filename = compress_image($_FILES["file"]["tmp_name"], $url, 80);
}
}else{
echo "<script>alert('No image to upload!');</script>";
}
}
?>
Thank you in advance.....
Change a bit for the input "file" element:
<input type="file" multiple name="file[]" id="file" accept="image/*" />
Its ok, now you can use $_FILES["file"]["name"][0] to get the name of 1st file, or _FILES["file"]["tmp_name"][1] to get the tmp_name of 2nd file, and so on.
I hope you understand, i cannot explain more because i am using phone...
Related
Using www.w3schools.com/php/php_file_upload.asp as a base, I want to upload a file but change the file name to include a field in my form, plus specific test.
How can I do this? (I very new to this)
EG. file name being uploaded = TestFile.jpeg
I want the file renamed to be [first_name field in form]_invoice.jpeg
This is my form:
<form action="upload.php" method="post" enctype="multipart/form-data">
First name
<input type="text" name="first_name" id="first_name" />
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
This is my PHP:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "pdf" && $imageFileType != "txt" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only PDF, TXT, JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Change the first lines in the the code like this:
<?php
$target_dir = "uploads/";
$imageFileType = strtolower(pathinfo($_FILES["fileToUpload"]["name"],PATHINFO_EXTENSION));
$target_file = $target_dir . trim($_POST['your_name']) . '_invoice.' . $imageFileType;
$uploadOk = 1;
But you should also have to have <input type="text" name="your_name"> in your form because according your code and the article, there's no text-typed input.
The problem is this one:
I have a code that uploads a picture to phpmyadmin, the code... doesn't fully work for some reason, it doesn't upload the image fully and the image ends up having a very small size, and it won't show up either. If I upload them directly to the database, they can be shown, but the ones uploaded using the code below have that problem.
This is the code I have:
Code for the button:
<div id="content">
<form method="POST" action =""/>
<table>
<tr>
<td>
Upload a picture
</td>
<td>
<input type="file" name="image"/>
</td>
</tr>
</table>
<input type="submit" name="submit" value="Registrarme"/> <input type="reset"/>
</form>
<?php
if(isset($_POST['submit'])){
require("iniciar.php");
}
?>
</div>
Code for the uploading: (iniciar.php)
<?php
$image = $_POST['image'];
$reqlen = strlen($image);
if($reqlen > 0){
$conn = mysqli_connect('localhost','root','','image');
$sql = "INSERT INTO `images` VALUES ('', '$image', '')";
mysqli_query($conn, $sql);
echo 'Upload successful';
}else{
echo 'Please insert an image';
}
?>
This is the structure of the table:
The table I have
you're assigning like input data instead of
$_FILES["image"]["name"];
//remove thisline
$image=$_POST['evidence'];
// you have to use it like this
$image= $_FILES["image"]["name"];
you have to assign image like this
$target_file = $target_dir . '/' . basename($_FILES["image"]["name"]);
$image=$target_file;
now evidence hold address of image so dir. of image is now on evidence too.now it will be uploaded to data base you aren't passing data. that's the mistake. any questions comment .if it solves your problem mark it as solved :)
for reference ,this is the php script used to upload profile picture,
<?php
if(isset($_POST["submit"]))
{
$target_dir = "profilepic/";
$targetfile=$target_dir.basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($targetfile,PATHINFO_EXTENSION);
if($imageFileType != "jpg" &&$imageFileType != "JPG" && $imageFileType != "png" && $imageFileType != "PNG" && $imageFileType != "jpeg" && $imageFileType != "JPEG" && $imageFileType != "gif" && $imageFileType != "GIF" )
{
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0)
{
echo "<small>Sorry, your file was not uploaded.</small>";
}
else
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetfile))
{
echo "<small>upload successful</small>";
$imgdir="UPDATE user SET profilepic='$targetfile' WHERE username='$uname';";
$con->query($imgdir);
header("location:profile.php");
}
else
echo "not uploaded";
}
}
?>
make changes according to your data base & operations.
I have the following code, but even when I upload a valid image it echoes "Error: your file cannot be uploaded". It's passing all the checks but something is going wrong with the saving to a folder. I have a directory called 'uploads' in the same directory as the php file, so I'm not sure why it isn't saving the images there. I know I could do it with a database but I'm not too sure how. I just want to be able to save the uploaded images somewhere, and display the most recently uploaded image on the page.
Any tips on how to get this to work would be thoroughly appreciated.
Thanks!
upload.html
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>File Upload</title>
</head>
<body>
<header>
<h1>File Upload</h1>
</header>
<form action="/fileUpload.php" method="post" enctype="multipart/form-data">
<br>
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
fileUpload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileUpload"]["name"]);
$uploadCheck = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileUpload"]["tmp_name"]);
if($check !== false) {
$uploadCheck = 1;
} else {
echo "Error: the file you attempted to upload is not an image";
$uploadCheck = 0;
}
}
if (file_exists($target_file)) {
echo "Error: file already exists.";
$uploadCheck = 0;
}
if ($_FILES["fileUpload"]["size"] > 500000) {
echo "Error: file is too large.";
$uploadCheck = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Error: incompatible type. only JPG, JPEG, PNG & GIF files.";
$uploadCheck = 0;
}
if ($uploadCheck == 0) {
echo "Error: your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "Success! Your file - ". basename( $_FILES["fileToUpload"]["name"]). " - has been uploaded.";
} else {
echo "Error: your file could not be uploaded";
}
}
?>
Your solution is here ( it contained errors),
First of all in Upload.html change /fileUpload.php to fileupload.php.
In upload.html & fileUpload.php, name attribute for file should be same.
upload.html
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>File Upload</title>
</head>
<body>
<header>
<h1>File Upload</h1>
</header>
<form action="fileUpload.php" method="post" enctype="multipart/form-data">
<br>
Select image to upload:
<input type="file" name="fileUpload" id="fileUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
fileUpload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileUpload"]["name"]);
$uploadCheck = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileUpload"]["tmp_name"]);
if($check !== false) {
$uploadCheck = 1;
} else {
echo "Error: the file you attempted to upload is not an image";
$uploadCheck = 0;
}
}
if (file_exists($target_file)) {
echo "Error: file already exists.";
$uploadCheck = 0;
}
if ($_FILES["fileUpload"]["size"] > 500000) {
echo "Error: file is too large.";
$uploadCheck = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Error: incompatible type. only JPG, JPEG, PNG & GIF files.";
$uploadCheck = 0;
}
if ($uploadCheck == 0) {
echo "Error: your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $target_file)) {
echo "Success! Your file - ". basename( $_FILES["fileUpload"]["name"]). " - has been uploaded.";
} else {
echo "Error: your file could not be uploaded";
}
}
?>
Instead of using this:
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
Try using this:
list($name,$ext)=explode(".",$_FILES["fileUpload"]["name"]);
and then try to validate the extension part:
if($ext!= "jpg" && $ext!= "png" && $ext!= "jpeg"&& $ext!= "gif" )
I suggest you to use in_array() for the above validation like this:
$img_ext=array("jpg","png","jpeg","gif");
if(!in_array($ext,$img_ext)){ //Your code here }
Try this $target_dir = "./uploads/";
also if your using windows pc under a wamp Environment grant the folder permission
I am trying to upload the image and video in my project, but when I tried to upload video it returns an empty array for $_POST and $_FILES both.
If I try to upload an image, the same code is working fine. The code I have used is below:
extract($_POST);
$upload_dir = wp_upload_dir();
$target_dir = $upload_dir['basedir'].'/mediauploads/';
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if($upd)
{
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if($imageFileType != "mp4" && $imageFileType != "wmv" && $imageFileType != "avi" && $imageFileType != "mov" && $imageFileType != "3gp" && $imageFileType != "mpeg" && $imageFileType != "jpg")
{
echo "File Format Not Suppoted";
} else {
$video_path=$_FILES['fileToUpload']['name'];
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$target_file);
echo "uploaded ";
}
}
Upload video form:
<form method="post" enctype="multipart/form-data">
<table border="1" style="padding:10px">
<tr>
<Td>Upload Video</td>
</tr>
<Tr>
<td><input type="file" name="fileToUpload"/></td>
</tr>
<tr>
<td><input type="submit" value="Uplaod Video" name="upd"/></td>
</tr>
</table>
</form>
if (isset($_FILES["stPic"]["name"]) && $_FILES["stPic"]["tmp_name"] != ""){
$fileName = $_FILES["stPic"]["name"];
$fileTmpLoc = $_FILES["stPic"]["tmp_name"];
$fileType = $_FILES["stPic"]["type"];
$fileSize = $_FILES["stPic"]["size"];
$fileErrorMsg = $_FILES["stPic"]["error"];
if (!preg_match("/.(gif|jpg|png|mp4|3gp|wmw|avi|mkv)$/i", $fileName) ) {
echo "File Format Not Suppoted";
}else{
$moveResult = move_uploaded_file($fileTmpLoc, "video/$fileName");
if ($moveResult != true) {
echo 'file not upload';
exit();
}
else{
//You run sql query
echo 'Uploaded';
}
}
}
<html>
<head>
</head>
<body>
<form action="tutorial.php" method="post" enctype="multipart/form-data">
<b><u>UPLOAD FILE</u></b><br />
Attachment : <input type="file" name="file" /><br />
<input type="submit" name="submit" value="Upload" /><br />
<hr />
</body>
<?php
function compress_image($source, $destination, $quality)
{
$info = getimagesize($source);
if($info['mime'] == 'image/jpeg' || $info['mime'] == "image/jpg")
{
$image = imagecreatefromjpeg($source);
}
else if($info['mime'] == 'image/gif')
{
$image = imagecreatefromgif($source);
}
else if($info['mime'] == 'image/png')
{
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
if(isset($_POST['submit']) && $_POST['submit'] == 'Upload')
{
$type = $_FILES['file']['type'];
$tmp_name = $_FILES['file']['tmp_name'];
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
if(($type == "image/jpg") || ($type == "image/jpeg") || ($type == "image/gif") || ($type == "image/png"))
{
$source = $tmp_name;
$destination = "destination.jpg";
echo 'File size (before): '.$size.'<br />';
$filename = compress_image($source, $destination, 75);
echo 'File size (after): '.filesize($destination).'<br />';
}
else
{
echo "Invalid file size. Only jpg, jpeg, gif, png allowed.";
}
}
?>
From above code, I get the following output after I upload jpeg file:
Original file size: 7034
Compress file size: 7092
I really don't know why after I compress, it is increased? If I upload a large file size, the file size will reduce. When I upload a small file size, the file size is an increase. How should I do?