I am trying to upload and save an image using PHP scripting, but the image is not getting saved in the specified folder. Please help
here's my code:
<?php
if(isset($_POST['button'])){
$name= "product_name.jpg";
move_uploaded_file($_FILES["fileField"]["tmp_name"],"student_images/$name");
header("location: tryupload.php");
}
?>
<html>
<body>
<form action="tryupload.php" enctype="multiple/form-data" name="myForm" id="myform" method="post">
<table>
<tr>
<td align="right">Product Image</td>
<td><label>
<input type="file" name="fileField" id="fileField" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button"/>
</label></td>
</tr></table>
</form>
</body>
</html>
This part of your code enctype="multiple/form-data" is incorrect.
It needs to read as enctype="multipart/form-data".
Also make sure that the folder you intend on uploading to, has proper permissions to write to.
http://php.net/manual/en/features.file-upload.post-method.php
http://php.net/manual/en/function.chmod.php (setting folder/files permissions).
Uploading security-related links:
https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form
100% safe photo upload script
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
To upload multuple files you can have.
Multiupload.php
<? session_start()?>
<!DOCTYPE html>
<html>
<head>
<title>Blank</title>
<!-------Including jQuery from google------>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/script.js"></script>
<!-------Including CSS File------>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
<body>
<div id="formdiv">
<h1 class="uploadH2">Upload Your Artwork</h1>
<form enctype="multipart/form-data" action="" method="post">
Take a photo, upload your artwork, or choose an image from Facebook or Instagram
<label for="file">
<div id="image" style="margin-top:5%;">
<img src="img/camera.png">
</div>
</label>
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="button" class="add_more" id="add_more" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="img_upload" class="show-page-loading-msg" data-theme="b" data-textonly="false" data-textvisible="false" data-msgtext="" data-icon="arrow-r" data-iconpos="right"/>
</form>
<br/>
<br/>
<!-------Including PHP Script here------>
<?php include "uploadScript.php"; ?>
</div>
</body>
</html>
uploadScript.php
<?php
$dir_id = session_id(md5(uniqid()));
session_start($dir_id);
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>
<?
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = $path;
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png", "gif"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">Only JPG, JPEG, PNG and GIF files types allowed.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
This script will only accept, jpg, png, gif and jpeg. You can't upload or execute anything inside the directory unless you are owner and you can't have a file size bigger than 10KB.
script.js
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src='' style='width:40%; height:40%;'/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'delete', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
else {}
});
});
This will upload multiple files, preview the image on the same page as the upload form, this will create a directory inside /uploads on the server with a directory matching the users session_id(). If the directory exists, the directory will be deleted, if it doesn't the directory will be created. The files will then be uploaded to that directory on the server.
You have incorrect enctype for the form. Instead of "multiple/form-data" use "multipart/form-data".
Related
(Note: Updated title to better match the question)
I am working on adding an image upload feature to ajax chat, and I have the HTML and PHP already written (basically copied from W3Schools) to do this. I have a test HTML page set up on the server to test the image uploads and that works just fine - the form works and the file is uploaded when the "Upload Image" button is pressed (to execute the PHP upload code). However, once the upload is complete the page switches to a blank page with the URL for my upload.php file.
I am currently using a modal in HTML to initially hide the image upload form and only appear when the "Image" button in the chat is pressed. The code is very simple, and as I said is basically the same as seen in the above link but placed inside a modal.
And before anyone complains, I know PHP is easy to exploit and can be dangerous when put on a website but this has been determined to be a non-issue in my case.
Below is the code for the image upload modal. Please pardon all the in-line CSS, I will eventually move it to its own stylesheet but have been using in-line for development purposes. Note that display is set to block for debugging. For the live site it would be set to none and a javascript function is used to set it to block when the "Image" button is pressed in the chat module.
<html>
<body>
<div id="imageUploadModal" style="display:block; position:fixed; z-index:1; left:0; top:0; width:100%; height:100%;.
overflow:auto; background-color:rgb(0,0,0); background-color:rgba(0,0,0,0.4);">
<div style="background-color:#fefefe; margin:15% auto; padding:20px; border:1px solid #888; width:80%;">
<span style="color:#aaa; float:right; font-size:28px; font-weight:bold;">×</span>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image:
<input type="file" name="fileToUpload" id="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
</div>
</div>
</body>
</html>
UPDATE:
Below are the contents of upload.php:
<?php
// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
$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
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
//The file is an image
$uploadOk = 1;
} else {
//The file is not an image
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
//The file already exists
$uploadOk = 0;
}
// Check file size
if (2000000 < $_FILES["fileToUpload"]["size"]) {
//The file is too large
$uploadOk = 0;
}
// Allow certain file formats
if (($imageFileType != "jpg") && ($imageFileType != "png")
&& ($imageFileType != "jpeg") && ($imageFileType != "gif")) {
//Only JPG, JPEG, PNG, and GIF files are allowed
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
//The file was not uploaded
exit();
// if everything is ok, try to upload the file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
exit();
} else {
//There was an error uploading the file
exit();
}
}
?>
EDIT: Updated HTML/Javascript
// Ajax image upload
$(document).ready(function() {
$("#uploadForm").submit(function(event) {
event.preventDefault();
var $form = $("#uploadForm");
var serializedData = $form.serialize();
var request = $.ajax({
type: "POST",
url: "/upload.php",
data: serializedData
});
request.done(function() {
console.log("AJAX Success!");
closeImageUploadModal();
});
})
});
HTML:
<div id="imageUploadModal" style="display:none; position:fixed; z-index:1; left:0; top:0; width:100%; height:100%;
overflow:auto; background-color:rgb(0,0,0); background-color:rgba(0,0,0,0.4);">
<div style="background-color:#0e0e0e; color:#aaa; margin:15% auto; padding:20px; border:1px solid #888; width:50%;">
<span id="close" style="color:#aaa; float:right; font-size:28px; font-weight:bold;" onclick="closeImageUploadModal()">×</span>
<form id="uploadForm">
<h3><b>Select image:</b></h3>
<input type="file" name="fileToUpload" id="fileToUpload" accept=".jpg, .JPG, .png, .PNG, .jpeg, .JPEG, .gif, .GIF"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
</div>
</div>
How to upload a file without refreshing or redirecting.
Method 1: Plugins
Plugins would probably be the best for you, since they are usually well tested and relatively bug free and require hardly any work to get it running. There are a number of plugins you can use, I have them listed below.
jQuery File Uploader
Multiple File Upload Plugin
Mini Multiple File Upload
jQuery File Upload
Method 2: Other StackOverflow Answers
There has been plenty of answers for this type of problem. I have listed some below.
How can I upload files asynchronously?
jQuery AJAX file upload PHP
How to use $.ajax() for input field text AND FILE upload?
jQuery Ajax File Upload
File Upload Ajax PHP
Additional Sources to look at
https://www.sanwebe.com/2012/06/ajax-file-upload-with-php-and-jquery
https://www.formget.com/ajax-image-upload-php/
If you need more sources to look at try searching:
How to upload file with AJAX and PHP
Uploading File with AJAX and PHP
Sending File to AJAX and PHP upload
File Upload AJAX and PHP
Solution
HTML
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" onclick="UploadFile()" />
</form>
<progress></progress>
JavaScript and AJAX
Note: You will need jQuery for this section. Please link the lastest
CDN to your document.
function UploadFile()
{
$.ajax({
url: 'upload.php',
type: 'POST',
data: new FormData($('form')[0]),
cache: false,
contentType: false,
processData: false,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload)
{
myXhr.upload.addEventListener('progress', function(e)
{
if (e.lengthComputable)
{
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
}, false);
}
return myXhr;
},
success: function() {
// close modal here
}
});
}
This does work since I have tested it. You will need to change your PHP a little.
Just merge your PHP code and HTML to a file and then, in the form, submit to it self.
<?php
$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];
?>
<html>
<head>
<title>Personal INFO</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
</form>
<?
echo "Hello, ".$Fname." ".$Lname.".<br />";
?>
How can I get the relative path to my uploaded file? For example if I upload test.png I would get /upload/test.png. Here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Jquery Ajax File Upload</title>
</head>
<body>
<div class="col-sm-6">
<div class="form-group ">
<label>Profile image</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-image"></i></span>
<input type="text" class="form-control" name="profile_image" autocomplete="off" value="" placeholder="" >
<label class="btn btn-default btn-file input-group-addon">
Browse <input type="file" name="image" style="display: none;" onchange="myFunction()" id="image" >
</label>
<div class="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$('#image').change(function(e){
var file = this.files[0];
var form = new FormData();
form.append('image', file);
$.ajax({
url : "http://192.168.1.147/upload.php",
type: "POST",
cache: false,
contentType: false,
processData: false,
data : form,
success: function(response){
$('.result').html(response.html)
}
});
});
</script>
</div>
</div>
</div>
</body>
</html>
PHP:
<?php
$file = $_FILES['image'];
/* Allowed file extension */
$allowedExtensions = ["gif", "jpeg", "jpg", "png", "svg"];
$fileExtension = explode(".", $file["name"]);
/* Contains file extension */
$extension = end($fileExtension);
/* Allowed Image types */
$types = ['image/gif', 'image/png', 'image/x-png', 'image/pjpeg', 'image/jpg', 'image/jpeg','image/svg+xml'];
if(in_array(strtolower($file['type']), $types)
// Checking for valid image type
&& in_array(strtolower($extension), $allowedExtensions)
// Checking for valid file extension
&& !$file["error"] > 0)
// Checking for errors if any
{
if(move_uploaded_file($file["tmp_name"], 'uploads/'.$file['name'])){
header('Content-Type: application/json');
echo json_encode(['html' => /*return uploded file path and name*/ ]);
echo $_FILES['upload']['name'];
}else{
header('Content-Type: application/json');
echo json_encode(['html' => 'Unable to move image. Is folder writable?']);
}
}else{
header('Content-Type: application/json');
echo json_encode(['html' => 'Please upload only png, jpg images']);
}
?>
The code works, that is upload the file but I don't know how to get the path back. The path may change because its for a user profile image and later I will change the upload path to one that is /$username. If you know how get the name only please post that anyway. Thanks in advance.
$file['name'] has the name of the file in it, lets say test1.png
This is the bit of the program that saves your file in a specific location. In this case the folder uploads relative to the current working directory.
if(move_uploaded_file($file["tmp_name"], 'uploads/'.$file['name'])){
header('Content-Type: application/json');
echo json_encode(['html' =>
/* you might want to output something like */
getcwd().'/uploads/'.$file['name']
// getcwd() current working directory
// it may be that you need a relative path based on
// where your application lives to generate a url, for example
// 'http://your_app_base_url/'.'/uploads/'.$file['name']
]);
echo $_FILES['upload']['name']; // this will be empty unless there is a file form field with the name 'upload'
// compare with $_FILE['image'] above
}else{
header('Content-Type: application/json');
echo json_encode(['html' => 'Unable to move image. Is folder writable?']);
}
If you want to move the file later, you could have a directory called profile_pics and move them to there, and rename to the username.
e.g.
$oldfilename = $file['name'];
//create a name for the file based on username and uploaded file extension (.jpg/.png)
$newfilename = $username.'_profile.'.pathinfo($oldfilename,PATHINFO_EXTENSION);
//this will rename /move the file from uploads to profile_pics (directory must exist already)
rename('uploads/'.$oldfilename,'profile_pics/'.$newfilename);
(beginner)
I'm having trouble uploading my file. I see the filename being posted to the database, but the file is not being posted to the images folder. It seems as though nothing is happening. Here is my following code, please advise me what I need to change:
<?php
//the $art variable gets posted to a database eventually
$art = mysql_real_escape_string(stripslashes($_FILES["art"]["name"]));
$art_ext = pathinfo($art, PATHINFO_EXTENSION);
$art = md5($art).".".$art_ext;
if($art!=""){
move_uploaded_file($art, "images/".$art );
}
?>
<script type="text/javascript">
$(function(){
image_upload = {
UpdatePreview: function(obj){
// if IE < 10 doesn't support FileReader
if(!window.FileReader){
// don't know how to proceed to assign src to image tag
} else {
var reader = new FileReader();
var target = null;
reader.onload = function(e) {
target = e.target || e.srcElement;
$("#imageupload").attr("src", target.result);
};
reader.readAsDataURL(obj.files[0]);
}
}
};
});
</script>
<form action="new.php" method="post" enctype="multipart/form-data">
<input type='file' name='art' id="file" onchange='image_upload.UpdatePreview(this)' value="Upload" accept="image/gif,image/jpeg,image/png"/>
</p>
<p>upload a image! (.gif, .jpg, .png formats allowed. 5MB max)</p>
<img id="imageupload" src="1x1.png" alt="test" />
<input type="submit" class="smallbtn4" style="cursor:pointer;" value="post"/>
</form>
Here's the format for move_uploaded_file():
$path = 'images/';
move_uploaded_file($_FILES['art']['tmp_name'], $path.basename($_FILES['art']['name']));
when using move_uploaded_files() your destination path should also include the name of the file....right now your destination path is:
images/
it should be:
images/nameOfImg.ext
Hope this helps!
EDIT:
After seeing the comment by #enhzflep, you should also hash the name of the file and create your filename string before using it in move_uploaded_file();
i want to add a progress bar to my upload code
so i've installed uploadprogress extension ( actually i've downgraded my wamp server to wamp 2.0 as this one already has the extension but new versions seems to have problem with it )
here is my backend code
/////////////////// uploading
<?php
if (isset($_POST['upload'])) {
echo 'UPLOADING . . . <br />';
$location = './uploads';
$new= uniqid().'.'.end(explode('.' , basename($_FILES['mailfile']['name']) ));
if(move_uploaded_file( $_FILES['mailfile']['tmp_name'],"$location/$new"))
echo 'DONE !! ';
else
echo 'error';
}
/////////////// getting upload info
else if(isset($_GET['get_info']))
{
if (function_exists("uploadprogress_get_info")) {
$info = uploadprogress_get_info($_GET['get_info']);
} else {
$info = 'nofunc';
}
var_dump($info);
}
/////////////// upload form
else
{ $uploadID = substr(md5(microtime(true)), 0, 10);
?>
<form enctype="multipart/form-data" action="uploadprogress.php" method="post" >
<input type="text" name="UPLOAD_IDENTIFIER" value="<?php echo $uploadID; ?>" id="uploadIdentifier" />
<input id="file" name="mailfile" type="file" />
<input type="submit" value="Send File" id="btn" name="upload" />
</form>
<?php
}
and this is my front html/jquery code
when file is being uploaded it gets the UPLOAD_IDENTIFIER value from iframe and the sends it to the set() function which is suppose to get the upload progress via ajax calls but it always returns null
<html>
<head>
<script language="javascript" src="../../js/jquery.js"></script>
<script>
var val;
$(function(){
$('#progress_iframe').load(function() {
var ifr = $(this);
$(this)
.contents()
.find('#btn')
.bind('click', function() {
val = ifr.contents().find('#uploadIdentifier').val();
set();
// do stuff
});
});
})
function set() {
$.get('uploadprogress.php' , {get_info : val} , function(data){
data = $.trim(data);
$('#info').html(data) ;
if(data < 100 )
set();
})
}
</script>
</head>
<body>
<div>
<iframe id="progress_iframe" src="uploadprogress.php" frameborder="0"> </iframe>
<span id="info"></span>
</div>
</body>
</html>
so the file is being uploaded without any problem and i've tried a big file but still as the file was being uploaded the uploadprogress_get_info was null
Check if the UploadProgress tmp directory is accessible on the server. Meaning the "uploadprogress.file.filename_template" refers to the right tmp folder in the phpinfo.
You can run the following code to check this.
<div id="status" style="border: 1px black solid;<?php
$templateini = ini_get("uploadprogress.file.filename_template");
$testid = "thisisjustatest";
$template = sprintf($templateini, $testid);
$templateerror = false;
if ($template && $template != $templateini && #touch($template) && file_exists($template)) {
// print '('.$templateini.' is writable. The realpath is ' . str_replace($testid,"%s",realpath($template)) .')';
unlink($template);
} else {
$templateerror = true;
}
if (function_exists("uploadprogress_get_info")) {
if ($templateerror) {
print 'background-color: red;"';
print ">Problem. ";
if ($template == $templateini) {
print "uploadprogress.file.filename_template ($templateini) doesn't have an %s in it for making unique temporary files. Please adjust.<br/>";
} else {
print "$templateini is NOT writable. <br/>Please make sure the directory exists and is writable for the webserver. <br/>
Or adjust the ini setting 'uploadprogress.file.filename_template' to a correct path.";
}
} else {
print 'background-color: green;">The uploadprogress extension is installed and initial checks show everything is good';
}
} else {
?>
background-color: red;">The uploadprogress extension is not installed.
<?php } ?>
</div>
If the above code gives error, point to the correct tmp directory in the php.ini file. The following line was added in the php.ini file for Xampp tmp directory on windows localhost machine. uploadprogress.file.filename_template = C:\xampp\tmp\some_name_%s.txt
Now your code should work.
The following code allows me to upload pictures (using a html form) to a directory on my server.
<?php
$target = "http://www.mockcourt.org.uk/user/htdocs/pics/2012/";
$target = $target . basename( $_FILES['uploaded']['name']);
$ok=1;
if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
Is there any way to modify it so that it will add the pictures to a html page instead?
Thanks
Well after you upload it, you can use javascript to put it on the html page.
I'm not quite sure what your question is, though
EDIT:
So, html form on your page:
<form action="imageUpload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="jupload();" id="form1" >
<div style="visibility:'hidden';" class="imageholder"> <!-- a gif image to show that the process wasn't finished -->
</div>
<input type="file" name="imgfile" />
<input type="submit" name="uploadButton" class="upbtn" value="Submit" />
</form>
Javascript(JQUERY) code for the upload and image add:
function jupload()
{
$(".imageholder").append('<img src="./images/loading.gif">');
}
function juploadstop(result)
{
if(result==0)
{
$(".imageholder").html("");
}
// the result will be the path to the image
else if(result!=0)
{
$(".imageholder").html("");
// imageplace is the class of the div where you want to add the image
$(".imageplace").append("<img src='"+result+"'>");
}
}
php code:
<?php
$target = "http://www.mockcourt.org.uk/user/htdocs/pics/2012/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
$result=$target;
}
else
{
$result=0;
}
?>
<script language="javascript" type="text/javascript">
window.top.window.juploadstop(<?php echo $result; ?>);
</script>
Suppose you have the form in HTML to submit the image.. make the submit button, not a submit button, but just a button.. e.g.
<input type='button' id='submit_form' value='upload' />
and in the javascript, use Ajax to submit the form and Jquery to display it in the web page
$('#submit_form')click(function(){
$.ajax({
type: 'POST',
url: path/phpfile.php,
data: image_input_name
});
//after submitting, get the url of the image form the server
$('#div_to_display_image').html("<img src='path/image_file.jpg' alt='this' />");
});
Hope this helps :-)