How to upload photos/file to server using PHP - php

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

Related

Undefined index: fileToUpload while load a createpost page?

I have the following PHP code in which i am creating a post with title description and image and i am storing image in a folder images. all things working fine while i create a post this move file to images folder. title , description and imagepath gone to news folder and so on. but when firstly arrive on createnews.php page this error is shown how to handle this error.
NOTE: this error is shown on page load after loading post is submitting correctly
Error
Notice: Undefined index: fileToUpload in E:\Software projects Folder\htdocs\Criclite\createnews.php on line 63
Sorry, there was an error uploading your file.
createnews.php
<!DOCTYPE html>
<html>
<head>
<title>Add news</title>
</head>
<body>
<form action="createnews.php" method="post" enctype="multipart/form-data">
<h2>Add Post Details Here</h2>
<?php if (isset($_GET['error'])) { ?>
<p class="error"><?php echo $_GET['error']; ?></p>
<?php } ?>
<label>Title</label>
<input type="text" name="title" placeholder="Enter Post Title"><br>
<label>Description</label>
<br>
<textarea rows="8" cols="100" name="description"></textarea>
<br><br>
<label >Select image:</label>
<input type="file" name="fileToUpload"
value="" />
<div>
<button onclick="allnews()" type="submit"name="upload">
Submit
</button>
</div>
</form>
</body>
</html>
<?php
include("db_config.php");
require_once "header.php";
$target_dir = "images/";
$file_name = date("U").".jpg";
$target_file = $target_dir . $file_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 (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$title=$_POST['title'];
$description=$_POST['description'];
$sql= "
INSERT INTO `news` ( `title`, `description`, `image`) VALUES ( '".$title."', '".$description."', '".$target_file."')";
if ($link->query($sql) === TRUE) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
}
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
This may not be a clean approach but a quick one. You can just add the following snippet to make sure that the form submission script only executes when the form is posted. You can add this at the beginning of the script.
<?php
if(!isset($_POST["submit"])){
return false;
}
...

Accept uploaded files with the same name?

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.

How to automatically add photo's to page

I have just setup a fileupload.php so that I can upload files but am interesting in having the files instantly be setup on the page that I want it with the css that I assign. Is there a way to do this? I would like to have three columns of photos that viewers can see as I upload the files so I do not have to manually add it into the code every single time I want to add a photo to the page.
I already know how to make a grid with the photos but am really interested in how to actually have all the photos uploaded to the page to instantly be placed on that grid.
My graphics.php page :
<?php include 'includes/header.php' ?>
<div class="graphics_content">
<div class="page_top_image">
<img src="includes/img/heartfx_graphics.png" class="img-responsive" alt="Responsive image">
</div>
</div>
<div class="photo_upload">
<div class="photo_upload_form">
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<br>
<input type="file" name="fileToUpload" id="fileToUpload">
<br>
<input type="submit" value="Upload Image" name="submit">
</form>
</div>
</div>
My upload.php page :
<?php
$target_dir = "uploads/";
$target_file = $target_dir .basename($_FILES["fileToUpload"]["name"]);
$uploadOK = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
//Check if image file is an actual image or a 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;
}
}
// 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 != "png") {
echo "Sorry, only PNG 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 ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Thank you in advance for any help. If anything is needed from my code that you would like me to provide I can do so.
Best regards,
Codi

Error when uploading mp3 using PHP

I have a form on a webpage that allows users to upload mp3 files. It works perfectly fine except when it comes to files over 2MB. Then it says "Sorry, there was an error uploading your file." I have tested mp3s ranging from 2mb - 6mb and they dont work and I believe I have adjusted the code to where it can accept files well over 2MB. Can someone help?
Here's the HTML, (I don't believe this to be the issue):
<div id="contactpara">
<form id="upform" action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Music" name="submit">
<iframe id="upload_target" name="upload_target" src="" style="width:500px;height:100px;border:0px solid #000;"></iframe>
</form>
</div>
Here's the PHP:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = 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"] > 10000000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "mp3" ) {
echo "Sorry, only mp3 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 ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
The reason it says $imageFileType is because this was a PHP code used to accept images that I tweaked to accept audio files. Could this be causing the issue? Please let me know.
I kind of had this same issue and found out it was the max_filesize which was 2m. it makes me think alot cus i troubleshooted.. solution is just to change the max_filesize to the amount you want

php : unable to upload file to the server

hey I am not much of a PHP coder
I am using following to upload file to server acn any body help me whats wrong with this code
<?php
$uploaddir = './uploads/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "http://iphone.zcentric.com/uploads/{$file}";
}
?>
Thanx in advance
I don't see anything wrong with the PHP code, though without an error it is difficult to tell what is happening.
Somethings which could cause uploads not to work, and which may not return errors:
Ensure you have enctype="multipart/form-data in the form tag:
<form enctype="multipart/form-data" action="__URL__" method="POST">
Make sure PHP is accepting the input, by adjusting the following PHP ini variables:
http://us.php.net/manual/en/ini.core.php#ini.post-max-size
http://us.php.net/manual/en/info.configuration.php#ini.max-input-time
http://us.php.net/manual/en/ini.core.php#ini.upload-max-filesize
Finally, ensure that permissions are properly set for both the temp upload folder (http://us.php.net/manual/en/ini.core.php#ini.upload-tmp-dir) and the folder you are moving files to. If it is a Windows server you might also run into an inheritance issue which will require you to change the default upload directory.
iF YOU WANT TO UPLOAD .pdf FILE TO LOCAL SERVER THEN USE THIS SIMPLE METHOD, Lets we are doing code here under Button Click Event...
if (isset($_POST['submit']))
{
if ( ($_FILES["file"]["type"] =="application/pdf"))
{
if (file_exists("C:/xampplite/htdocs/site/upload/" . $_FILES["file"]["name"]))
echo " This File is already exists in folder";
else
{
move_uploaded_file ($_FILES["file"]["tmp_name"],"C:/xampplite/htdocs/site/upload/" . $_FILES["file"]["name"]);
echo "File have been Stored in:-C:/xampplite/htdocs/site/upload/ " . $_FILES["file"]["name"];
}
}
}//end of click_event
could u pls publish what the error u get?Your code looks ok.Here the upload folder must he stay in the upper of the directory where you run the code.Then it should to work.if your script folder like this /test/script/abc.php then your uploads directory should be /test/uploads.
index.php
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload[]" id="fileToUpload" multiple="">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
upload.php
<?php
//$target_dir = "uploads/";
/*$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
*/
if(count($_FILES['fileToUpload']['name']) > 0)
{
$i=0;
while($i<count($_FILES['fileToUpload']['name']))
{
$filen = $_FILES["fileToUpload"]['name']["$i"];
$path = 'uploads/'.$filen;
$imageFileType = pathinfo($path,PATHINFO_EXTENSION);
if (file_exists($path)) {
echo "Sorry, file already exists.";
}else if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
else if(move_uploaded_file($_FILES["fileToUpload"]['tmp_name']["$i"],$path))
{
//echo "The file ". basename( $_FILES["fileToUpload"]["name"]["$i"]). " has been uploaded.";
$files=$_FILES["fileToUpload"]["name"]["$i"];
echo $files;?><img src="<?php echo $path;?>" style="width:200px;height:200px" alt="" >
<?php
}
$i++;
}
}
?>

Categories