I am developing custom WordPress plugin. In this plugin, I am trying to upload files into wp-content\uploads\passports (folder path).
I don't face any error message when uploading file. Although it shows File has been uploaded successfully. message, but there is no any uploaded file in the folder.
Here is my code:
trip-form.php
<tr><td cospan="4">Please attach a scanned copy of your:</td></tr>
<tr>
<td>Passport: </td>
<td colspan="3"><input type="file" name="passport" id="passport"/></td>
</tr>
<tr>
<td></td>
<td colspan="3"><div id="dropBox">
<p>Select file to upload</p>
</div></td>
</tr>
script.js
// Add events
$j('input[type=file]').on('change', fileUpload);
// File uploader function
function fileUpload(event){
alert('fileUpload');
//notify user about the file upload status
$j("#dropBox").html(event.target.value+" uploading...");
//get selected file
files = event.target.files;
//form data check the above bullet for what it is
var data = new FormData();
var web_url = document.location + '';
var path = web_url.substring(0,web_url.lastIndexOf('/'));
path = path.substring(0,path.lastIndexOf('/'));
path = path + '/wp-content/plugins/trip-form/pages/uploadfile.php';
//file data is presented as an array
for (var i = 0; i < files.length; i++) {
var file = files[i];
var fileExtension = ['jpeg', 'jpg', 'pdf'];
if ($j.inArray($j('#passport').val().split('.').pop().toLowerCase(), fileExtension) == -1) {
$j("#dropBox").html("Only formats are allowed : "+fileExtension.join(', '));
}else{
//append the uploadable file to FormData object
data.append('file', file, file.name);
//create a new XMLHttpRequest
var xhr = new XMLHttpRequest();
//post file data for upload
xhr.open('POST', path, true);
xhr.send(data);
xhr.onload = function () {
//get response and show the uploading status
var response = JSON.parse(xhr.responseText);
if(xhr.status === 200 && response.status == 'ok'){
$j("#dropBox").html("File has been uploaded successfully.");
}else{
$j("#dropBox").html("Some problem occured, please try again.");
}
};
}
}
}
uploadfile.php
<?php
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
//generate unique file name
$fileName = time().'_'.basename($_FILES["file"]["name"]);
//file upload path, targetdir is correct
$targetDir = "../../../uploads/passports/";
$targetFilePath = $targetDir . $fileName;
//upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
//if (file_exists ( $targetDir."testing.txt" )){
$response['status'] = 'ok';
}else{
$response['status'] = 'err';
}
//render response data in JSON format
echo json_encode($response);
?>
I have no idea what is wrong. Any help would be appreciated.
Thanks.
Can you please change your uploads folder permission. Make it 755.
Related
is there anyway using move_uploaded_file which upload 2 file from 2 file input?
file.vue (template)
<input type="file" id="ob_ssm_document" ref="ob_ssm_document" required/>
<input type="file" id="ob_business_license" ref="ob_business_license" required />
<v-btn color="green darken-1" text #click="processSubmit()">Confirm</v-btn>
//file.vue (script)
processSubmit(){
this.ob_ssm_document = this.$refs.ob_ssm_document.files[0];
this.ob_business_license = this.$refs.ob_business_license.files[0];
this.axios.post('businessfile.php', formImage,{
headers: {
'Content-Type': 'multipart/form-data'
}
}).then((response) => {
if(!response.data){
this.fileError = true;
} else {
alert("submitted");
}
}
businessfile.php
<?php
// File name
$ob_ssm_document = $_FILES['ob_ssm_document']['name'];
$ob_business_license = $_FILES['ob_business_license']['name'];
// Valid file extensions
$valid_extensions = array("jpg","jpeg","png","pdf");
// File extension
$extension = pathinfo($ob_ssm_document, PATHINFO_EXTENSION);
$extension_two = pathinfo($ob_business_license, PATHINFO_EXTENSION);
// Check extension
if(in_array(strtolower($extension,$extension_two),$valid_extensions) ) {
// Upload file
if(move_uploaded_file($_FILES['ob_ssm_document']['tmp_name'], "uploads/".$ob_ssm_document) && move_uploaded_file($_FILES['ob_business_license']['tmp_name'], "uploads/".$ob_business_license)){
echo 1;
}else{
echo 0;
}
}else{
echo 0;
}
exit;
personalfile.php
<?php
// File name
$ob_ssm_document = $_FILES['ob_ssm_document']['name'];
// Valid file extensions
$valid_extensions = array("jpg","jpeg","png","pdf");
// File extension
$extension = pathinfo($ob_ssm_document, PATHINFO_EXTENSION);
// Check extension
if(in_array(strtolower($extension,$extension_two),$valid_extensions) ) {
// Upload file
if(move_uploaded_file($_FILES['ob_ssm_document']['tmp_name'], "uploads/".$ob_ssm_document)){
echo 1;
}else{
echo 0;
}
}else{
echo 0;
}
exit;
The code above is for 1 file from 1 single input file to database
What i really want is upload two file from 2 diffrernt file input into the folder name called "Uploads" with each file's name.
I want to be able to have a user drag and drop a pdf file and have a modal appear for the user to quickly fill out a form about the file. When the user clicks submit, the file and the form data are passed using Ajax to a php file to then have the file upload and the data processed into a DB.
script.js
// On drop calls uploadFile Function and appends to formData object
$("#dropzone").on ('drop', function (e) {
e.preventDefault();
$(this).removeClass('dropzone dragover').addClass('dropzone');
$("#myModal").removeClass("hidden").addClass("visible");
var file = e.originalEvent.dataTransfer.files;
uploadFile(file);
});
var uploadFile = function(files){
formData = new FormData();
formData.append("file", files);
var x;
for (x = 0; x < files.length; x = x + 1){
let file = files[x];
formData.append('files[]', file);
}
};
// On Form submit all data is saved to values and Ajax call to users.php
$("form").on('submit', function(e) {
// e.preventDefault();
var values = $(this).serialize();
$("#myModal").removeClass("visible").addClass("hidden");
url = 'app/forms/users.php'
$.ajax({
type: 'POST',
url: 'app/forms/users.php',
processData: false,
contentType: false,
cache: false,
data: { formData, values },
dataType: 'json',
success: console.log("Done")
});
});
This is where I run into issues. I am able to
console.log(Array.from(formData)) at all points of interaction before the user hits submit. But when the user submits the form it seems the formData vanishes from existence.
users.php
} else if ($_POST['dispatch'] == 'file_upload') {
// Upload File
var_dump($_FILES);
var_dump($_POST);
$errors = [];
$target_dir = 'F:\wamp64\www\blank\dev\uploads/';
$extensions = ['pdf', 'PDF'];
$all_files = count($_FILES['file']['tmp_name']);
for ($i = 0; $i < $all_files; $i++) {
$file_Name = $_FILES['file']['name'][$i];
$file_Tmp = $_FILES['file']['tmp_name'][$i];
$file_Type = $_FILES['file']['type'][$i];
$file_Size = $_FILES['file']['size'][$i];
$tmp = explode('.', $_FILES['file']['name'][$i]);
$file_ext = strtolower(end($tmp));
$file = $target_dir . date('U')."-".basename($file_Name);
if (!in_array($file_ext, $extensions)) {
$errors[] = 'Extension not allowed: ' . $file_Name . ' ' . $file_Type;
}
if ($file_Size > 9000000000000000000) {
$errors[] = 'File size exceeds limit: ' . $file_Name . ' ' . $file_Type;
}
move_uploaded_file($file_Tmp, $file);
if ($errors) print_r($errors);
}
// Process to DB
Currently, the only data I can find is the formData from the form itself. If there is any information that I missed that could be helpful just let me know. Either I need to go about this a different way or I'm just missing something.
Any help is appreciated. Thank you.
I'm not sure how to access the javascript object correctly I think. I'm trying to use ajax to upload a file to php and have the php file handle an unzip to specific directories.
I'm not sure how the unzip would go but I have have the following code so far:
HTML:
<form id="upload_header_modules_form1" enctype="multipart/form-data" method="post" action="" onsubmit="return false">
<label for="themes_edit_file_id1" class="themes_edit_file">Upload .zip file</label>
<input id="themes_edit_file_id1" style="visibility:hidden;" onchange="setfilename1(this.value);" type="file">
<label for="install1" class="normal_button" onclick="uploadZip()">Install</label>
<input id="install1" style="visibility:hidden;" type="submit">
</form>
AJAX:
function uploadZip()
{
formdata = new FormData(document.forms[0]);
if (formdata)
{
$.ajax
(
{
url: "http://localhost/IG_API_2/pages/default_upload/upload_php.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (data)
{
$(".modal").css("opacity", "1");$(".modal").css("visibility", "visible");$(".modal_mid").html("<pre>" + data + "</pre>");
alert(data);
}
}
);
}
}
and PHP (I haven't checked the PHP much so don't pay too much attention to this):
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
/* PHP current path */
$path = '../plugins/'; // absolute path to the directory where zipper.php is in
$filenoext = basename ($filename, '.zip'); // absolute path to the directory where zipper.php is in (lowercase)
$filenoext = basename ($filenoext, '.ZIP'); // absolute path to the directory where zipper.php is in (when uppercase)
$targetdir = $path . $filenoext; // target directory
$targetzip = $path . $filename; // target zip file
/* create directory if not exists', otherwise overwrite */
/* target directory is same as filename without extension */
if (is_dir($targetdir)) rmdir_recursive ( $targetdir);
mkdir($targetdir, 0777);
/* here it is really happening */
if(move_uploaded_file($source, $targetzip)) {
$zip = new ZipArchive();
$x = $zip->open($targetzip); // open the zip file to extract
if ($x === true) {
$zip->extractTo($targetdir); // place in the directory with same name
$zip->close();
unlink($targetzip);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
I'm just wanting to
a) get past the PHP error "Undefined Index zip_file in C:\etc"
b) extract the .ZIP file to location "temp/"
Thanks in advance.
Edit We know that the PHP error is an undefined index because the file type is not loading correctly in the $_FILES["zip_file"]. It's not getting the file because of ajax for some reason. I think it's to do with the formdata = new FormData(document.forms[0]); line.
Im currently prepairing a web page and i need to make a form to upload image. It must be possible user to,
1 upload image by url ,
2 upload image by computer ,
3 upload image by drag and dropping.
I found those code separately from the internet.
But problem is how to combine all of those.
Html Form has 2 input box.
1 image name.
2 image url, upload image button
When user upload image it must be save to folder as name in 1st input box.also it name need to save in sql with the extention.
Can any one help me!
--------------html------------------
<input name="file_name" placeholder="File Name" class="form-control" type="text">
--------------php----------------
if (isset($_POST['add'])){
$softname=$_POST['file_name'];
}
require_once('ImageManipulator.php');
if ($_FILES['fileToUpload']['error'] > 0) {
echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
}
else {
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png','.bmp');
$fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
$newNamePrefix = 'ddownload_';
$manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
$newImage = $manipulator->resample(250, 250);
if(isset($_POST['img_url'])){
$url=$_POST['img_url'];
if (!empty($url)) {
$data = file_get_contents($url);
$manipulator = new ImageManipulator( $data);
// resizing to 200x200 image from url
$newImage = $manipulator->resample(250, 250);
}
// saving file to uploads folder
$manipulator->save('uploads/img/' . $newNamePrefix . $softname);
echo 'Thank you! ...';
} else {
echo 'You must upload an image...';
}
}
$source=$_POST['directlink'];
$u_image=$softname;
$filesize=$_POST['size'];
$type=$_POST['type'];
$description =$_POST['description'];
$insert_data="INSERT INTO `softwarelist`(`sid`, `softname`, `image`, `type`, `source`,`description`,`rating`,`filesize`,`user`) VALUES ('','$softname','$u_image','$type','$source','$description','','$filesize','');";
-------------end php----------
------------script for drag AND drop image-------
<script>
var files = evt.target.files;
var files = evt.dataTransfer.files;
var result = '';
var file;
for (var i = 0; file = files[i]; i++) {
// if the file is not an image, continue
if (!file.type.match('image.*')) {
continue;
}
reader = new FileReader();
reader.onload = (function (tFile) {
return function (evt) {
var div = document.createElement('div');
div.innerHTML = '<img style="width: 200px;" src="' + evt.target.result + '" />';
document.getElementById('filesInfo').appendChild(div);
};
}(file));
reader.readAsDataURL(file);
}
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
I'm trying to upload files using php and I am copying and renaming files from other instances that are actually working (uploading pics). But for some reason the form is not passing (POST) any file that is NOT an image :-/
So, in resume, I am getting this (Google) 'request payload' for an image file:
------WebKitFormBoundaryrHOYostaC2KnUDlD
Content-Disposition: form-data; name="uploaded_file[]"; filename="image.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryrHOYostaC2KnUDlD--
But this for txt or pdf files:
------WebKitFormBoundaryc1RJOtSOpYKAZiBz--
Here is the form and script (functions are to avoid the user to click 'Submit', those work good):
echo '
<script language="JavaScript" type="text/javascript">
function HandleBrowseClick()
{
var fileinput = document.getElementById("uploaded_file");
fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("uploaded_file");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;
}
</script>';
echo '
<form enctype="multipart/form-data" target="_blank" name="send_file" id="send_file" method="post" action="file_upload.php">
<input type="file" class="hide button" id="uploaded_file" name="uploaded_file" onChange="Handlechange();"/>
<button type="submit" id="btn">Upload!</button>
</form>';
echo '
<div onclick="HandleBrowseClick();" id="fakeBrowse" >Load a file</div>
<input type="text" id="filename" size="50" readonly="true" />
';
So, since it's not passing anything, in my file_upload.php I get the "ERROR: Please browse for a file before clicking the upload button." or "Invalid argument supplied for foreach()" (if I expect an array) error.
I tried using application/x-www-form-urlencoded allowing the same result. Now for those who get mad if there is no question marks: Why the form works fine with images but not so with other kind of files? What am I dong wrong?
Here is the first few lines of file_upload.php (I don't think it's necessary but you never know):
$target = "../files/temp/";
foreach ($_FILES["uploaded_file"]["error"] as $key => $error) {
if ($error != UPLOAD_ERR_OK) { echo "error"; die;}
$fileName = $target . $_FILES["uploaded_file"]["name"][$key]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"][$key]; // File in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"][$key]; // The type of file it is
$fileSize = $_FILES["uploaded_file"]["size"][$key]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"][$key]; // 0 for false... and 1 for true last $key!!!
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename
$fileName = strtolower($fileName);
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occurred while processing the file. Try again.";
exit();
}
Finally, some more js:
if (window.FormData) {
formdata = new FormData();
document.getElementById("btn").style.display = "none";
}
input.addEventListener("change", function (evt) {
document.getElementById("response").innerHTML = "Loading . . ."
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if (formdata) {
formdata.append("uploaded_file[]", file);
}
}
}
if (formdata) {
$.ajax({
url: "file_upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false
}).done(function (res) {
document.getElementById("response").innerHTML = res;
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
});
}
}, false);
where changing contentType doesn't make any diference
THANKS!!!
You have to define the MIME types for your files. For example
.pdf application/pdf
.doc application/msword
Okay, my bad. The js file has an image filter. It started working right away after I removed it.