I Have a form where people can upload a single image. Most people are uploading pictures from their mobile devices. Everyone with an iPhone, has their image uploaded as "image.png". I need to have my form not reject it, and just accept files with the same name without delete the old one or rename them something like "imageupload1.png", "imageupload2.png" or even image.png then "image-Copy.png" then "image-Copy(2).png", etc
I figure something like this might work:
$filename = $_FILES['myfilename']['name'];
$filename = time().$filename;
or
function renameDuplicates($path, $file)
{
$fileName = pathinfo($path . $file, PATHINFO_FILENAME);
$fileExtension = "." . pathinfo($path . $file, PATHINFO_EXTENSION);
$returnValue = $fileName . $fileExtension;
$copy = 1;
while(file_exists($path . $returnValue))
{
$returnValue = $fileName . '-copy-'. $copy . $fileExtension;
$copy++;
}
return $returnValue;
}
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "Sucessfully Uploaded - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
I just don't know where to plug it in. I'm a noob so take it easy on me and please be specific. The options I "figured might work" were taken from other questions but they didn't work for me, chances are i'm doing something wrong so please don't mark this as "already asked" Thank you. Sorry for the bother.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only 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 "<a href='../pie.html' style='border: 5px solid #3a57af;padding-right:50px;padding-bottom:25px;padding-left:50px;display:inline;font-weight:bold;color:#3a57af';> CLICK HERE TO REGISTER</a>";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
html {
padding-top: 5em;
font-family: trebuchet, sans-serif;
font-size: 24px;
font-weight: bold;
-webkit-font-smoothing: antialiased;
text-align: center;
background: white;
}
body {
padding:0;
margin:0;
text-align:center;
}
div.imageupload {
padding: 5em 5em 5em 5em;
height:100vh;
width:100vh;
text-align:justify
}
<html>
<head>
<title>Image Submission</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="assets/css/image.css">
<style type="text/css"></style>
</head>
<body>
<div class="imageupload">
<p><h1>Step 1</h1><br>
Please submit a recent photograph to be featured on the homepage of this website.<br><br>
We will place your yearbook picture in the lower right hand corner of the image you submit.<br>
<br>This will allow our classmates to see how we look now and how we looked then.<br><br>
Please select an appropriate image for a website of this nature. <br><br>
The image should show you from your head to at least your knees. <br><br>
The image should not be a group picture, please be the only one in the picture.<br><br>
Any pictures that do not meet this criteria will be sent back and will not be posted.<br></p>
<form action="PHPmailer/upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form></div>
</body>
</html>
Instead of your $target_file definition, plug in your dedup function:
$target_file = renameDuplicates($target_dir, basename($_FILES["fileToUpload"]["name"]));
(I did not check whether the function behaves properly, but at the first glance it should be all right.)
EDIT: The function was a tiny bit broken.
function renameDuplicates($path, $file) {
$fileName = pathinfo($path . $file, PATHINFO_FILENAME);
$fileExtension = "." . pathinfo($path . $file, PATHINFO_EXTENSION);
$returnValue = $path . $fileName . $fileExtension;
$copy = 1;
while(file_exists($returnValue))
{
$returnValue = $path . $fileName . '-copy-'. $copy . $fileExtension;
$copy++;
}
return $returnValue;
}
Check the lines containing $returnValue for changes.
I have come to your rescue, and written the whole thing for you :)
You will need to have this structure:
upload.php
ImageUpload/uploadMe.php
in upload.php:
<html>
<head>
<title>Upload Your image here | SiteName</title>
<!-- Latest compiled and minified Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<?php
$FLAG = $_GET['e'];
if($FLAG == "UPLOAD_FAILED"){ ?>
<div class="col-md-12 alert alert-warning">
Ooops! It looks like an error occured when uploading your image.
</div>
<?php } else if($FLAG == "NOT_IMAGE"){ ?>
<div class="col-md-12 alert alert-warning">
Hey! Thats not an image?<br/>
<pre>We only allow: png, jpg, gif and jpeg images.</pre>
</div>
<?php } else{} ?>
<div class="well col-md-6">
<form action="ImageUpload/uploadMe.php" method="POST" enctype="multipart/form-data">
<legend>
Image Upload
</legend>
<input type="file" name="file" class="form-control btn btn-info"/>
<br/>
<input type="submit" value="Upload" class="btn btn-primary"/>
</form>
</div>
<div class="well col-md-6">
<p><h1>Step 1</h1><br>
Please submit a recent photograph to be featured on the homepage of this website.<br><br>
We will place your yearbook picture in the lower right hand corner of the image you submit.<br>
<br>This will allow our classmates to see how we look now and how we looked then.<br><br>
Please select an appropriate image for a website of this nature. <br><br>
The image should show you from your head to at least your knees. <br><br>
The image should not be a group picture, please be the only one in the picture.<br><br>
Any pictures that do not meet this criteria will be sent back and will not be posted.<br></p>
</div>
</div>
</div>
</body>
</html>
In ImageUpload/uploadMe.php:
<?php
if(isset($_FILES['file'])){
$File = $_FILES['file'];
//File properties:
$FileName = $File['name'];
$TmpLocation = $File['tmp_name'];
$FileSize = $File['size'];
$FileError = $File['error'];
//Figure out what kind of file this is:
$FileExt = explode('.', $FileName);
$FileExt = strtolower(end($FileExt));
//Allowed files:
$Allowed = array('jpg', 'png', 'gif', 'jpeg');
//Check if file is allowed:
if(in_array($FileExt, $Allowed)){
//Does it return an error ?
//No:
if($FileError==0){
$ImageFolder = "uploads";
//Check if exist, otherwise create it!
if (!is_dir($ImageFolder)) {
mkdir($ImageFolder, 0777, true);
}
else{}
//Create new filename:
$NewName = uniqid('', true) . rand(123456789,987654321). '.' . $FileExt;
$UploadDestination = $ImageFolder ."/". $NewName;
//Move file to location:
if(move_uploaded_file($TmpLocation, $UploadDestination)){
//Yay! Image was uploaded!
//Do whatever you want here!
}
//File didnt upload:
else{
//Redirect:
header("Location: /upload.php?e=UPLOAD_FAILED");
}
}
//An error occured ?
else{
//Redirect:
header("Location: /upload.php?e=UPLOAD_FAILED");
}
}
//Filetype not allowed!
else{
//redirect:
header("Location: /upload.php?e=NOT_IMAGE");
}
}
else{
//No file was submitted :s send them back, eh ?
header("Location: /upload.php");
}
OK, i think its done now!
If you want to use your own "Look" just copy and paste the <form></form> stuff and maybe the simple "error" handler ?
Have a good one :)
<input class="uploadGAConnection" #uploadFile type="file" (change)="uploadGAConnectionDetails($event)" placeholder="Upload file" accept=".csv,.json" (click)="uploadFile.value=null">
You can simply give a reference and set its value null on every click.
Related
Hi so I'm trying to allow users to upload a photo to a listing. I'm using dropzone.js and I have the form done, it works perfectly! except that photos don't actually upload to the folder "uploads/"
I have tried many many different ways spent days researching and I cannot for the life of me figure out what is wrong.
Kindly note that it is a multipage form so I cannot post the whole form on here but ill try to share the important scripts!
Dropzone code:
<head>
<script src="https://unpkg.com/dropzone#5/dist/min/dropzone.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/dropzone#5/dist/min/dropzone.min.css" type="text/css" />
</head>
<div class="container" >
<div class='content'>
<form action="create.php" method="post" type="file" name="file" class="dropzone" id="dropzonewidget" enctype="multipart/form-data">
</div>
</div>
</div>
</div>
<div class="row form-block flex-column flex-sm-row">
<div class="col text-center text-sm-start"><a class="btn btn-link text-muted" href="user-add-2.php"> <i class="fa-chevron-left fa me-2"></i>Back</a>
</div>
<div class="col text-center text-sm-end"><button type="submit" name="save" class="btn btn-primary">save</button><i class="fa-chevron-right fa ms-2"></i></div>
</form>
Now for the PHP script: I have 2 attempts that got close, the first actually makes its way into the database and the second just echo's all error scripts
Script 1: (kinda works)
$uploadDir = 'var/www/uploads';
$tmpFile = $_FILES['file']['tmp_name'];
// upload file to directory
$fileName = $uploadDir.'/'.time().'-'. $_FILES['file']
['name'];
move_uploaded_file($tmpFile,$fileName); {
$sql = "INSERT INTO hosts(id, user_name, name, type,
country, city, state, zip, about, price, photo)
VALUES('$id', '$user_name', '$name',
'$type', '$country', '$city', '$state', '$zip',
'$about', '$price', '$fileName')";
Script 2:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]
["name"]);
$uploadOk = 1;
$imageFileType =
strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 1000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png"
&& $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only 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["file"]["tmp_name"],
$target_file)) {
echo "The file ". htmlspecialchars( basename(
$_FILES["file"]["name"])). " has been uploaded.";
//$pictureName = "uploads". basename(
$_FILES["fileToUpload"]["name"]);
} else {
echo "Sorry, there was an error uploading your
file.";
}
At the end of both of these attempts I have a simple insert query (p.s. I know about SQL injections, just trying to get it to work first.)
hope I didn't give you a headache
Just a heads up I am new to PHP and to SO so be kind and I hope a more experienced developer can help me out of these troubling times! Thanks in advance, and if you understand my issue please post some code not a vague response :) cheers
For dropzone uploads (multiple file uploads)
a. you do NOT need to specify enctype="multipart/form-data" and method="post" type="file" name="file"
b. No need to use submit button
c. As stated before, make sure there is a sub-folder known as uploads and it is write-permitted
d. To do further db maninpulation (e.g. insert), execute the insert query in the php , make sure using $_FILES['file']['name'] when constructing the insert query
Hence, please amend your code to:
HTML
<head>
<script src="https://unpkg.com/dropzone#5/dist/min/dropzone.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/dropzone#5/dist/min/dropzone.min.css" type="text/css" />
</head>
<div class="container" >
<div class='content'>
<form action="create.php" class="dropzone" id="dropzonewidget">
</form>
</div>
</div>
create.php
<?php
$target_dir = "./uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir.$_FILES['file']['name'])) {
$status = 1;
// do further update in database
// please note that the file name is $_FILES['file']['name']
// make sure you use parametized prepared statement in your insert query
// to avoid SQL injection attacks
//
}
?>
hey guys so I created a website that you can upload books to and display them as a list I have a form to input the name of the book and the file type and I want them to display as the name and file type (on the same line) example (nameofabook epub) but when I try is display them it shows up like (nameofabook
new line epub) here's my code thank you
<?php
if (isset($_FILES['file']) && isset($_POST['name'])) {
$file = $_FILES['file'];
$file_name = $file['name'];
$file_type = $file['type'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode(".", $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array("mov", "avi", "mp4", "epub", "pdf"); //The extensions you allow
if (in_array($file_ext, $allowed)) {
if ($file_error === 0) {
if ($file_size <= 2097152) { //the maximum filesize
$file_destination = ''.$file_name; // If ' ', the file will be placed in this directory
if (move_uploaded_file($file_tmp, $file_destination)) {
echo $file_destination;
$fp = fopen('book_list.txt', "a");
fwrite($fp, $_POST['name']. "|||" .$file_destination."\n");
fwrite($fp, $_POST['type']. "|||" .$file_destination."\n");
fclose($fp);
} else {
echo "An error has been encountered while moving your file!";
}
} else {
echo "Your file is too big!";
}
} else {
echo "An error has been encountered while uploading your file!";
}
} else {
echo "You can't upload files of this type!";
}
}
?>
if anyones curious heres my html for the upload page
<!DOCTYPE html>
<html>
<head>
<title>Upload a Book</title>
<link href = "style2.css" type = "text/css" rel = "stylesheet" />
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Name: <input type="text" name="name" required/>
Type: <input type="text" name="type" required/>
File: <input type="file" name="file" required/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
Firstly...
Don't upload files directly in your site! You should upload them with an API, outside, in a cloud storage. In this case, you can use Cloudinary . So, you don't need to think much about the files uploaded. Again, you can show them easily!
Don't store information like names and others(without the file) in a text file. Storing them in a MySQL database is the best way to do so.
Secondly...
Use different inputs for collecting book names and other information so that, you can display and modify them easily.
Thirdly...
Please give the code you are using for displaying data
I'm a Homo sapiens So I can write anything wrong. Please forgive me for that.
Code below works fine without PRG, BUT i want PRG because i really hate refresh-repost. Though, i did not foresee that problem: i assume that if i dont upload my images immediately with post, get wont find any files to move from temp folder to server folder (they are deleted immediately after post i guess?).
Now, since images should be uploaded before filtered anyway (using server sided languages), i had an idea of uploading without using PRG, and then using a session state like a temp file that will include all the submit info in order just to destroy it and get refresh-repost free... well, its not working. I know it uploads only the correct files, BUT i cant get any $vars out of it, resulting in being unable to show my $error variables / warnings for users.
So... how do i get two birds with one shot php gurus?
trying to figure out if 'fake' sessions can work:
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_POST['submit_pic'])) {
$countfiles = count($_FILES['image']['name']);
$target_dir = "../images/";
$error_array = array();
$upload_array = array();
$eupload_array = array();
for($i=0;$i<$countfiles;$i++) {
$filename = $_FILES['image']['name'][$i];
$target_file = $target_dir.$filename;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"][$i]);
if($check !== false) {
$uploadOk = 1;
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
array_unshift($error_array, "Image $filename is not JPG, JPEG, PNG or GIF.");
$uploadOk = 0;
}
} else {
array_unshift($error_array, "File $filename is not an image.");
$uploadOk = 0;
}
if (file_exists($target_file)) {
array_unshift($error_array, "Image $filename already exists.");
$uploadOk = 0;
}
if ($_FILES["image"]["size"][$i] > 500000) {
$u = 1;
array_unshift($error_array, "Image $filename is too large.");
$uploadOk = 0;
}
if ($uploadOk == 0) {
array_unshift($eupload_array, "Sorry, image $filename was not uploaded.");
} else {
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $target_file)) {
array_unshift($upload_array, "Image $filename has been uploaded.");
} else {
array_unshift($eupload_array, "Sorry, $filename there was an error uploading your file.");
}
}
}
}
if(strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) {
$_SESSION['postdata'] = $_FILES;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
if( isset($_SESSION['postdata'])) {
$_FILES = $_SESSION['postdata'];
unset($_SESSION['postdata']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel='stylesheet' href='../assets/style.css'/>
<title>CMS TEST</title>
</head>
<body>
<div class='container'>
<a href='add_picture.php' id='logo'><h2>Add Picture</h2></a>
<br/>
<small class='test_warning' style='color:#B83333'>
❶ Images should be JPG, JPEG, PNG or GIF format extentions. <br/>
❷ Images should not be above 500KB size.<br/>
❸ Please try to rename images before uploading for easier use.
</small> <br/><br/>
<form action='add_picture.php' method="post" enctype="multipart/form-data">
<input type="file" name="image[]" id="image" class="custom-file-input" multiple required/><br/><br/><br/>
<input type="submit" value="Upload" name="submit_pic"/>
</form>
<?php if (!empty($upload_array)) { ?>
<small style='color:#00FF00'>
<?php echo '<br/><br/>', implode("<br/>",$upload_array), '<br/>'; ?>
</small>
<?php }?>
<?php if (!empty($eupload_array)) { ?>
<small style='color:#aa0000'>
<?php echo '<br/><br/>', implode("<br/>",$eupload_array), '<br/>'; ?>
</small>
<?php }?>
<?php if (!empty($error_array)) { ?>
<small style='color:#aa0000'>
<?php echo implode("<br/>",$error_array), '<br/>'; ?>
</small>
<?php }?>
<br/><br/>
<a href='index.php'>← Back</a>
<br/>
</div>
<a class='logout' href='logout.php'>Logout</a>
</body>
</html>
<?php
} else {
header('Location:index.php');
}
?>
'proper one':
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) {
$_SESSION['postdata'] = $_FILES;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
if( isset($_SESSION['postdata'])) {
$_FILES = $_SESSION['postdata'];
$countfiles = count($_FILES['image']['name']);
$target_dir = "../images/";
$error_array = array();
$upload_array = array();
$eupload_array = array();
for($i=0;$i<$countfiles;$i++) {
$filename = $_FILES['image']['name'][$i];
$target_file = $target_dir.$filename;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"][$i]);
if($check !== false) {
$uploadOk = 1;
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
array_unshift($error_array, "Image $filename is not JPG, JPEG, PNG or GIF.");
$uploadOk = 0;
}
} else {
array_unshift($error_array, "File $filename is not an image.");
$uploadOk = 0;
}
if (file_exists($target_file)) {
array_unshift($error_array, "Image $filename already exists.");
$uploadOk = 0;
}
if ($_FILES["image"]["size"][$i] > 500000) {
$u = 1;
array_unshift($error_array, "Image $filename is too large.");
$uploadOk = 0;
}
if ($uploadOk == 0) {
array_unshift($eupload_array, "Sorry, image $filename was not uploaded.");
} else {
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $target_file)) {
array_unshift($upload_array, "Image $filename has been uploaded.");
} else {
array_unshift($eupload_array, "Sorry, $filename there was an error uploading your file.");
}
}
}
unset($_SESSION['postdata']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel='stylesheet' href='../assets/style.css'/>
<title>CMS TEST</title>
</head>
<body>
<div class='container'>
<a href='add_picture.php' id='logo'><h2>Add Picture</h2></a>
<br/>
<small class='test_warning' style='color:#B83333'>
❶ Images should be JPG, JPEG, PNG or GIF format extentions. <br/>
❷ Images should not be above 500KB size.<br/>
❸ Please try to rename images before uploading for easier use.
</small> <br/><br/>
<form action='add_picture.php' method="post" enctype="multipart/form-data">
<input type="file" name="image[]" id="image" class="custom-file-input" multiple required/><br/><br/><br/>
<input type="submit" value="Upload" name="submit_pic"/>
</form>
<?php if (!empty($upload_array)) { ?>
<small style='color:#00FF00'>
<?php echo '<br/><br/>', implode("<br/>",$upload_array), '<br/>'; ?>
</small>
<?php }?>
<?php if (!empty($eupload_array)) { ?>
<small style='color:#aa0000'>
<?php echo '<br/><br/>', implode("<br/>",$eupload_array), '<br/>'; ?>
</small>
<?php }?>
<?php if (!empty($error_array)) { ?>
<small style='color:#aa0000'>
<?php echo implode("<br/>",$error_array), '<br/>'; ?>
</small>
<?php }?>
<br/><br/>
<a href='index.php'>← Back</a>
<br/>
</div>
<a class='logout' href='logout.php'>Logout</a>
</body>
</html>
<?php
} else {
header('Location:index.php');
}
?>
Besides temp pictures not existing between post get requests, also the variables are deleted from refreshing and i could not use them inside my html to show errors.
So i tried to play around with sessions even more, i moved the pic upload code to post, created some sessions to store my error arrays, and then at get i recreated my error arrays from the sessions i created for them.
Problem solved, pics are filtered, errors displaying, PRG is working.
Gosh... i just started with php there are soooo many things i dont understand D:
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) {
$_SESSION['postdata'] = $_FILES;
$error_array = array();
$upload_array = array();
$eupload_array = array();
$countfiles = count($_FILES['image']['name']);
$target_dir = "../images/";
for($i=0;$i<$countfiles;$i++) {
$filename = $_FILES['image']['name'][$i];
$target_file = $target_dir.$filename;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"][$i]);
echo $_FILES["image"]["tmp_name"][$i];
if($check !== false) {
$uploadOk = 1;
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
array_unshift($error_array, "Image $filename is not JPG, JPEG, PNG or GIF.");
$uploadOk = 0;
}
} else {
array_unshift($error_array, "File $filename is not an image.");
$uploadOk = 0;
}
if (file_exists($target_file)) {
array_unshift($error_array, "Image $filename already exists.");
$uploadOk = 0;
}
if ($_FILES["image"]["size"][$i] > 500000) {
$u = 1;
array_unshift($error_array, "Image $filename is too large.");
$uploadOk = 0;
}
if ($uploadOk == 0) {
array_unshift($eupload_array, "Sorry, image $filename was not uploaded.");
} else {
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $target_file)) {
array_unshift($upload_array, "Image $filename has been uploaded.");
} else {
array_unshift($eupload_array, "Sorry, $filename there was an error uploading your file.");
}
}
}
$_SESSION['error_array'] = $error_array;
$_SESSION['upload_array'] = $upload_array;
$_SESSION['eupload_array'] = $eupload_array;
header("Location:add_picture.php");
exit;
}
if( isset($_SESSION['postdata'])) {
$error_array = $_SESSION['error_array'];
$upload_array = $_SESSION['upload_array'];
$eupload_array = $_SESSION['eupload_array'];
unset($_SESSION['postdata']);
unset($_SESSION['error_array']);
unset($_SESSION['upload_array']);
unset($_SESSION['eupload_array']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel='stylesheet' href='../assets/style.css'/>
<title>CMS TEST</title>
</head>
<body>
<div class='container'>
<a href='add_picture.php' id='logo'><h2>Add Picture</h2></a>
<br/>
<small class='test_warning' style='color:#B83333'>
❶ Images should be JPG, JPEG, PNG or GIF format extentions. <br/>
❷ Images should not be above 500KB size.<br/>
❸ Please try to rename images before uploading for easier use.
</small> <br/><br/>
<form action='add_picture.php' method="post" enctype="multipart/form-data">
<input type="file" name="image[]" id="image" class="custom-file-input" multiple required/><br/><br/>
<input type="submit" value="Upload" name="submit_pic"/>
</form>
<?php if (!empty($upload_array)) { ?>
<small style='color:#00FF00'>
<?php echo '<br/><br/>', implode("<br/>",$upload_array), '<br/>'; ?>
</small>
<?php }?>
<?php if (!empty($eupload_array)) { ?>
<small style='color:#aa0000'>
<?php echo '<br/><br/>', implode("<br/>",$eupload_array), '<br/>'; ?>
</small>
<?php }?>
<?php if (!empty($error_array)) { ?>
<small style='color:#aa0000'>
<?php echo implode("<br/>",$error_array), '<br/>'; ?>
</small>
<?php }?>
<br/><br/>
<a href='index.php'>← Back</a>
<br/>
</div>
<a class='logout' href='logout.php'>Logout</a>
</body>
</html>
<?php
} else {
header('Location:index.php');
}
?>
Problem:
I have created a upload.php file, which contains a HTML form and the PHP code needed to upload images and I use XAMPP localhost:
htdocs/web2/assets/upload.php
I want to upload images to the folder upload in the same directory:
htdocs/web2/assets/uploads/
Script:
<?php
<form action="?" method="post" enctype="multipart/form-data">
<!--wrap input button as around pre-existing image -->
<?php
echo '<label class="profile_gallery_image_in"><input type="file" name="fileToUpload" id="fileToUpload" onchange="form.submit()"/><p class="label"></p><img class="myImg" src='.$image.' height="100%" width="100%" /></label>';
?>
</form>
<!-- Commence Photo Upload -->
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
The form is set to auto-submit upon input type change. This appears to be working fine and the form is submitting.
However, I get no actual image uploaded and no error at all.
How do I solve this problem?
There seems to be an error in the code. You can use the below code for image uploading.
<?php
if(isset($_FILES['image'])){
$errors= array();
$dir = "images/";
$file_name = $_FILES['image']['name'];
$file_name = $dir. $file_name;
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$tmp = explode('.',$_FILES['image']['name']);
$file_ext=strtolower(end($tmp));
$extensions= array("jpeg","jpg","png","gif");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a GIF, JPEG or PNG file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp, $file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>
<form action = "" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "image" />
<input type = "submit"/>
</form>
</body>
</html>
I want to upload two images, one of the user and second of his ID, using one submit button using mysqli. Here is my HTML.
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
your image: <input type="file" name="img"><br/>
your Id card: <input type="file" name="img2">
<input type="submit" name="publish" value="upload">
</form>
</body>
</html>
All I know is to upload the single image at a time but what if want to upload these image into the database with single submit. I am not writing PHP because I don't know how to do this. I can upload multiple images at a time using an array but I want to use this method. Is it possible to do with PHP??
PHP for single upload:
<?php
$dir = "uploads/";
$t_file = $dir . basename($_FILES["img"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($t_file,PATHINFO_EXTENSION));
if(isset($_POST["upload"])) {
$check = getimagesize($_FILES["img"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
I can do it by using javascript. All respected users, please be more helpful for those who are new to any language. Or make this website only for experts, not for beginners.
So I use PHP for my first upload and JS for my second image upload.
here is js:
<script>
function startUpload(){
document.getElementById('uploadProcess').style.visibility = 'visible';
document.getElementById('uploadForm').style.visibility = 'hidden';
return true;
}
function stopUpload(success,uploadedFile){
var result = '';
if (success == 1){
result = '<span class="sucess-msg">The file was uploaded successfully!<\/span><br/><br/>';
//Uploaded file preview
var embed = document.getElementById("UploadedFile");
var clone = embed.cloneNode(true);
clone.setAttribute('src',uploadedFile);
embed.parentNode.replaceChild(clone,embed);
}else {
result = '<span class="error-msg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('uploadProcess').style.visibility = 'hidden';
document.getElementById('uploadForm').innerHTML = result + '<label>File:<input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('uploadForm').style.visibility = 'visible';
return true;
}
</script>
The html:
<form action="upload.php" method="post" enctype="multipart/form-data" onsubmit="startUpload();">
<p id="uploadForm">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="file" name="myfile" id="fileToUpload1">
<input type="submit" value="submitBtn" name="submit">
</p>
</form>
and the upload.php:
<?php
$success = 0;
$uploadedFile = '';
//File upload path
$uploadPath = 'uploads/';
$targetPath = $uploadPath . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $targetPath)){
$success = 1;
$uploadedFile = $targetPath;
}
sleep(1);
?>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
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 ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>