I am using easyupload jquery
Src: https://github.com/fater/jquery-easyupload
I am trying to upload files ( images,doc,docx uploaded perfectly) but pdf showing me error but its not explaning the error.
My CODE:
elseif ($type == "upload_file") {
$target_dir = $_SERVER['DOCUMENT_ROOT']."/admin2/uploads/images/";
$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
if (file_exists($target_file)) {$data['status'] = "error"; $data['msg'] = $BNL->msg("הקובץ עם השם הזה כבר קיים במערכת.");}
elseif ($_FILES["file"]["size"] > 5000000) {$data['status'] = "error"; $data['msg'] = $BNL->msg("המגבלה של העלאת קובץ היא 5MB");}
elseif($imageFileType != "pdf" && $imageFileType != "doc" && $imageFileType != "docx" ) {$data['status'] = "error"; $data['msg'] = $BNL->msg("הקבצים המותרים הם PDF, DOC, DOCX");}
else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
$data['msg'] = $BNL->msg("הקובץ ". basename( $_FILES["file"]["name"]). " הועלה בהצלחה.", true);
$_SESSION['file'] = basename( $_FILES["file"]["name"]);
} else {
//$data['msg'] = $BNL->msg("סליחה, הייתה בעיה בהעלאת הקובץ.");
$data['msg'] = $_FILES['file']['error']; // Print "1"
}
}
echo json_encode($data);
}
I cant figure it out what the problem I am trying to fix it for two days.
Any one can help me please, thanks in advance.
In this case, we need to check
upload_max_filesize and post_max_size.
http://php.net/manual/en/features.file-upload.php
<?php
try {
if (empty($_FILES)) {
new \Exception('$_FILES array is empty.');
} else {
if (isset($_FILES['file']) && !empty($_FILES['file'])) {
//Check error code
#https://github.com/zendframework/zend-validator/blob/master/src/File/Upload.php#L25
};
}
} catch (Throwable $exception) {
echo $exception->getMessage();
}
https://github.com/zendframework/zend-validator/blob/master/src/File/Upload.php#L25
Read more: $_FILE upload large file gives error 1 even though upload_max_size is bigger than the file size
Related
I want to transfer PHP echo text into HTML through JavaScript.I've seen that it can be done with the function document.getelementbyid() and innerHTML but I tried and it did not work.
This PHP Code:
<?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 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;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "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 "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
I want to echo the text displays in HTML Without switching to upload.php!!
On id statusbar I want to show echo text!
This HTML code:
<form action="../assets/php/upload.php" method="post" enctype="multipart/form-data">
<label>Izaberi fotografiju:</label>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit" onClick="info()">
<p id="statusbar"></p>
</form>
let's say you have to print this in your uploading html page
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}
change this to below
if ($uploadOk == 0) {
$message = "Sorry, your file was not uploaded.";
header("Location: /index.php?message="$message);
// if everything is ok, try to upload file
}
then get the message and print in your html page
You have to write code inside <?php ?> tag.Like this.
<script type="text/javascript">
//js code..
<?php echo "Sory, only PNG, JPG, GIF"; ?>
</scrip>
You can directly echo things to html. You can also echo things to a js variable directly like this, then set the html content with js.
<script>
var string = <?php echo "Sory, only PNG, JPG, GIF"; ?>
document.getElementById("notify-container").innerText = string;
</script>
Say your HTML element was the following:
<div id="error"></div>,
you'd assign the error message to a JavaScript variable like so: <script>
var errorMsg = <?php echo "Sory, only PNG, JPG, GIF"; ?>
</script>
Then you can show the message like so:
document.getElementById('error').innerHTML = errorMsg;
<?php
include 'model.php';
$rs=new database();
if(isset($_POST["Import"])){
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$res=$rs->insert($emapData[0],$emapData[1],$emapData[2],$emapData[3],$emapData[4],$emapData[5]);
$result=mysql_fetch_array($res);
if(! $result )
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"result.php?msg=valid\"
</script>";
}
}
fclose($file);
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"result.php?msg=valid\"
</script>";
mysql_close($conn);
}
}
?>
this code only uploads csv file but i want to upload xls too with this code. if possible i want to upload all format of excel . and the rest of code is working fine and also i dont want to change the method.
Download PHPExcel
https://github.com/PHPOffice/PHPExcel
and create this function
function getDataFromExcel($filename)
{
$excel = PHPExcel_IOFactory::load($filename);
$sheet = $excel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$sheetData = $sheet->toArray(null, true, true, true);
return $sheetData;
}
It will return data in array
if you want to know the type of file use this method
function getFileType($key)
{
//Define type
$type = 'unknow';
if(isset($_FILES[$key])) {
$file = $_FILES[$key];
$fileType = $file['type'];
if (strrpos($fileType, 'csv')) {
$type = 'csv';
} else if (($fileType == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || ($fileType == 'application/vnd.ms-excel')) {
$type = 'excel';
}
}
return $type;
}
I have this simplified situation :
<form action='process.php' method='post'>
<div class="dropzone no-margin">
<div class="fallback">
<input name="file" type="file" multiple/>
</div>
</div>
</form>
$(".dropzone").dropzone({
url: "/test2.php",
maxFilesize: 2,
maxFiles: 5
});
test2.php works just fine, it upload files dropped on the dropzone immediately. but, the problem is, I need to pass those file names of uploaded files to the form as hidden text input.
here's test2.php looks like :
<?php
$target_dir = "user/product/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$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["fileToUpload"]["size"] > 500000) {
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 ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
I'm a beginner in javascript or jquery world. So, I really need your help to give me a clue how to pass the file names to the form as hidden text input so it can be written into database later on.
thank you so much and I really appreciate you help.
Try this :
there is method in Dropzone i.e sending that will use to send data before file is sent.if multiple files are uploaded then use sendingmultiple method.
$(".dropzone").dropzone({
url: "/test2.php",
maxFilesize: 2,
maxFiles: 5,
sending:function (data, xhr, formdata) {
console.log("data :",data);
//here you can get file name from data variable.you can add that to your form by following line.
formdata.append('hidden field name', 'file name');
//you can add as much parameter you want to pass to your post data by formdata.append() function. That will add data to your form data.you can refer that value by using $_POST['hidden_field_name'] at PHP side.
}
});
Please check following link for detail :
http://www.dropzonejs.com/#events
So I'm trying to do a file upload using JQuery's AJAX thing, and it keeps giving me the error 500.
$(function() {
$( 'form' ).submit
(
function()
{
$.ajax({
type: 'POST',
url: 'photochallenge/submit.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function(data) {
Materialize.toast(data, 4000);
}
});
return false;
}
);
});
I am also using this PHP code to process the file upload:
<?php
$target_dir = "uploads/";
$target_file = null;
$uploadOk = 1;
$response = "Please choose an image";
// Check if image file is a actual image or fake image
if(isset($_POST["pic"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
$response = "File is not an image.";
$uploadOk = 0;
}
// Check file size
if ($uploadOk == 1 && $_FILES["fileToUpload"]["size"] > 500000) {
$response = "Sorry, your file is too large.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
// if everything is ok, try to upload file
} else {
//find target file
$found = false
$tmp = 0
while(!$found) {
$target_file = $target_dir . $tmp . ".png";
if(file_exists($target_file)) {
$tmp = $tmp + 1;
} else {
$found = true;
}
}
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$response = "Thank you for your submission!";
shell_exec("python log.py ".$_POST["firstname"]." ".$_POST["lastname"]." ".$target_file);
} else {
$response = "Sorry, there was an error uploading your file.";
}
}
}
echo $response;
?>
Unfortunately, I cannot release the link to where the actual problem is, but hopefully this code is enough to help solve the problem. If any other details are needed, please do not hesitate to let me know.
If you are not using ".htaccess", the issue may be in the shell_exec that may be crashing the application, if you are using something as fast-cgi.
Comment this line and perfom your script:
shell_exec("python log.py ".$_POST["firstname"]." ".$_POST["lastname"]." ".$target_file);
Using comments in PHP:
//shell_exec("python log.py ".$_POST["firstname"]." ".$_POST["lastname"]." ".$target_file);
I've got a problem with an image upload in AngularJS. I found this question on here: Angularjs - File upload with php
As in the other question I try to use https://github.com/danialfarid/angular-file-upload
My problem is that my image that I try to upload isn't send to my php file.
Here is the code that I use.
PlayerController.js
angular.module('lax').controller('PlayerController', function($scope, $http, $upload) {
$scope.onFileSelect = function($files) {
$scope.message = "";
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
console.log(file);
$scope.upload = $upload.upload({
url: 'php/upload.php',
method: 'POST',
file: file
}).success(function(data, status, headers, config) {
$scope.message = data;
}).error(function(data, status) {
$scope.message = data;
});
}
};
});
HTML
<div ng-show="newplayer.functie == 'update'">
<h3>Profile Pic</h3>
<div>
<input type="file" name="image" id="image" ng-file-select="onFileSelect($files)">
<br/>
<span class="errorMsg">{{ message}}</span>
</div>
</div>
upload.php
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"../../Img/PlayerAvatar/".$file_name);
echo $fname . " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
else{
$errors= array();
$errors[]="No image found";
print_r($errors);
}
?>
So the "if(isset($_FILES['image']))" gives false as a result. I'm new to stackoverflow and angularJS so sorry for any noob questions.
I had a problem in my PHP. The problem was with the $_FILES['image'] image should have been file
It should have been:
<?php
if(isset($_FILES['file'])){
$errors= array();
$file_name = $_FILES['file']['name'];
$file_size =$_FILES['file']['size'];
$file_tmp =$_FILES['file']['tmp_name'];
$file_type=$_FILES['file']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"PlayerAvatar/".$file_name);
echo " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
else{
$errors= array();
$errors[]="No image found";
print_r($errors);
}
?>