Krajee file input invalid json response - php

I tried to integrate krajee file-input into my existing form. DEMO SITE
When i browse a file from my computer and click upload button (built-in with the plugin), i got this error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
The author of this plugin told me that i have to write valid json response in my php file for this to work but he did not have time to help individual case like mine. So I read the documentation from the website, it has this part:(you can find it on the demo site above)
Sending Data (from server)
Your server method as set in uploadUrl must send data back as a json encoded object. The only key you must send is the error which will be the error message for the upload and will help the plugin to identify error in the file upload. For example the response from server would be sent as {error: 'You are not allowed to upload such a file.'}. Note: The plugin will automatically validate and display ajax exception errors.
IMPORTANT
You MUST send a valid JSON response from your server, else the upload process will fail. Even if you do not encounter any error, you must at least send an empty JSON object {} from your server.
To trap and display a validation error, your JSON response data must include the error key, whose value will be the error HTML markup to display. This is to be setup as mentioned above.
Unfortunately, I can't understand it because I am just a new php learner and this is out of my scope. But I have my php file here, hope some expert can help me to add the json response to it as the documentaion explained above. Thank you very much in advance!
Here is my php file:
<?php
if(isset($_POST["submit"])){
require("../configs/dbconnect.php");
/*Form variable */
$owner = mysql_real_escape_string($_POST["owner"]);
$title = mysql_real_escape_string($_POST["title"]);
$description = mysql_real_escape_string($_POST["description"]);
$city = mysql_real_escape_string($_POST["city"]);
$brand = mysql_real_escape_string($_POST["brand"]);
$marketprice = mysql_real_escape_string($_POST["marketprice"]);
$price = mysql_real_escape_string($_POST["price"]);
$phone = mysql_real_escape_string($_POST["phone"]);
/*** the upload directory ***/
$upload_dir= 'uploads';
/*** numver of files to upload ***/
$num_uploads = 5;
/*** maximum filesize allowed in bytes ***/
$max_file_size = 5000000;
/*** the maximum filesize from php.ini ***/
$ini_max = str_replace('M', '', ini_get('upload_max_filesize'));
$upload_max = $ini_max * 1024;
/*** a message for users ***/
$msg = 'Please select files for uploading';
/*** an array to hold messages ***/
$messages = array();
$err=array();
/*** check if a file has been submitted ***/
if(isset($_FILES['file']['tmp_name']))
{
/** loop through the array of files ***/
for($i=0; $i < count($_FILES['file']['tmp_name']);$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
/*** check if the file is less then the max php.ini size ***/
//elseif($_FILES['image']['size'][$i] > $upload_max)
//{
// $messages[] = "File size exceeds $upload_max php.ini limit";
//}
// check the file is less than the maximum file size
elseif($_FILES['file']['size'][$i] > $max_file_size)
{
$messages[] = "File size exceeds $max_file_size limit";
}
else
{
//$temp = explode(".", $_FILES["file"]["name"][$i]);
//$extension = end($temp);
//$name[$i] = sha1(microtime()) . "." . $extension;
$name[$i]=$_FILES["file"]["name"][$i];
// copy the file to the specified dir
if(move_uploaded_file($_FILES['file']['tmp_name'][$i],$upload_dir.'/'.$name[$i]))
{
/*** give praise and thanks to the php gods ***/
$messages[] = $name[$i].' uploaded';
$image_path[$i]=$upload_dir.'/'.$name[$i];
}
else
{
/*** an error message ***/
$messages[] = 'Uploading '.$name[$i].' Failed';
}
}
}
}
$image_path_string=serialize($image_path);
$sql = "INSERT INTO memberpost(owner, title, description, city, brand, marketprice, price, phone, image) VALUES ('$owner', '$title','$description','$city','$brand','$marketprice','$price','$phone', '" . $image_path_string . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
if(sizeof($messages) != 0)
{
foreach($messages as $err)
{
echo $err.'<br />';
}
}
}
?>

Your echo i think...
Put your error on any variable then echo json_encode(variable name). That's how to send JSON object.

Related

PHP Fatal error: Uncaught ValueError: Path cannot be empty on PHP8

This code is attached to a Gravity form, there is a file upload field on the form, and this code (although poorly written) grabs each file from the file upload field and uploads it to the server. My problem is, now that we have upgraded to PHP8, it's throwing an error:
//$entry[35] is the file upload field in the form.
//This grabs the uploaded file whatever it may be, and uploads it to the server
$newest_again = str_replace('[',"",$entry[35]);
$newest_final = str_replace(']',"",$newest_again);
$newest_fin = str_replace('"',"",$newest_final);
$entryArr = explode(",",$newest_fin);
if(!empty($entry[35])){
if(count($entryArr) > 1){
//multiple files have been added to the upload field
$count = 0;
$token = "";
$fileArr = array();
$binArr = array();
$extens = array();
foreach($entryArr as $file_entry){
//processing string to grab the file name only for each file
$new = str_replace('\\',"",$file_entry);
$new_again = str_replace('[',"",$new);
$new_final = str_replace(']',"",$new_again);
$new_fin = str_replace('"',"",$new_final);
$binFile = file_get_contents($new_fin);
$ext = pathinfo($new_fin, PATHINFO_EXTENSION);
array_push($fileArr, $new_fin);
array_push($binArr, $binFile);
array_push($extens, $ext);
}
//upload each file to server
while($count < (count($fileArr))){
$upload = curlUpload("/uploads.json", $binArr[$count], 'screenshot-'.$count.".".$extens[$count], $fileArr[$count],$token); // Attachments will have the prettyname screenshot.[$ext]
if($token == ""){
$token = $upload->upload->token;
}
else{
$token = $token;
}
$count ++;
}
print_r($uploads);
}
else{
//just one file was added to the form, so upload it
$fileArr = array();
$placeholder ="";
$new = str_replace('\\',"",$entry[35]);
$new_again = str_replace('[',"",$new);
$new_final = str_replace(']',"",$new_again);
$new_fin = str_replace('"',"",$new_final);
$binaryFile = file_get_contents($new_fin);
$ext = pathinfo($new_fin, PATHINFO_EXTENSION); // Upload field ID
$upload = curlUpload("/uploads.json", $binaryFile, 'screenshot.'.$ext, $new_fin, $placeholder); // Attachments will have the prettyname screenshot.[$ext]
$token = $upload->upload->token;
}
}
The error is:
PHP Fatal error: Uncaught ValueError: Path cannot be empty in /wp-content/themes/blankslate/functions.php:31483
Stack:
#0 /wp-content/themes/blankslate/functions.php(31483): file_get_contents('')
This error is ONLY thrown if a file is not added to the upload field on the form. If a file or files are added, the error is not thrown. It seems to be calling file_get_contents(); and throwing the error message when nothing has been added to the upload field in the form. This is the line that is throwing the error message:
$binFile = file_get_contents($new_fin);
I wrapped everything in this block:
if(!empty($entry[35])){
So that this code ONLY runs if the file upload field is not empty, but it is still throwing the error message even when no files are added to the file upload field in the form.
Is there anything I can add to this code that will prevent the error?

How can I validate multiple files first and add the rest of the form data to the database only if they're valid?

I'm not very experienced in coding PHP and MySQL, and am therefore looking for help. I'd like to do the following:
I have a form where users enter their contact details and at the end of the form there is a multiple file upload button.
Now if they submit the form, the following should happen:
First, I wanna check if all of the uploaded files are valid (file types are ok), if this is true, then the contact details should be entered to table_X of db_Z.
Then, all files should be moved/uploaded to the server and in table_Y of db_Z the file name, the (let's call it) eventID and date and time of the upload should be inserted, whereas the eventID is a foreignkey of the ID of the entry of the contact details.
The code I have until now is close, but the final step is missing. It adds the contact details to the database regardless of the result of the validation of the files.
How can I change it, so that it only adds something to the database if all files are valid? And also that it adds the contact details only once to database regardless of how many files are being uploaded?
Thanks in advance
Here's my code:
<?php
if(isset($_POST['submit'])){
$obs_fname = filter_input(INPUT_POST, 'firstname');
$obs_lname = filter_input(INPUT_POST, 'lastname');
$obs_address = filter_input(INPUT_POST, 'adresse');
// Include the database configuration file
include_once 'dbConfig.php';
$query = "INSERT INTO bear (obs_fname, obs_lname, obs_address)
values ('$obs_fname','$obs_lname','$obs_address')";
$result=$db->query($query);
// verify results
if(!$result) {
$message = "ERROR SAVING POST : ".$db->error . "\n";
$db->close();
echo ($message);
return false;
}
/**
* get the last inster id of the Post
**/
$post_id = $db->insert_id;
echo "Post id=".$post_id ."<br>\n";
// File upload configuration
$targetDir = "uploads/";
$allowTypes = array('jpg','png','jpeg','gif');
if(isset($_FILES['files'])) {
foreach($_FILES['files']['name'] as $key => $name) {
$image_tmp = $_FILES['files']['tmp_name'][$key];
move_uploaded_file($image_tmp, './uploads/' . $name);
/**
* now insert the image with the post_id
**/
$query = "INSERT INTO images (eventID, file_name, uploaded_on)
VALUES ('$post_id', '$name', NOW())";
$result=$db->query($query);
// verify results
if(!$result) {
$message = "ERROR INSERT IMAGE : ".$db->error . "\n";
$db->close();
echo ($message);
return false;
}
}
}
header("Location: upload-complete.php");
}
You need to validate the MIME type on the server-side using mime_content_type() or using an image function that will return FALSE if it is not an image such getimagesize()
you gonna need a function like this + you need to validate the size $_FILES['files]['size] and the file extension $file_ext = strtolower(pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION))
function validate_images($image_tmp){
foreach($_FILES['files']['tmp_name'] as $key => $name) { // you need the tmp_name here and not "name" name is the one was when the file was in the client computer, After the form sent, the file will be in `/tmp` on the server and that is where php is accessing it.
$image_tmp = $_FILES['files']['tmp_name'][$key];
if(strpos(mime_content_type($image_tmp),"image")){
return true;
}else{
return false;
}
}
if(validate_images($image_tmp)){
// do the rest
}else{
die("no no no");
}
Also look here w3school image upload

Uploading 1000 images via url using PHP

I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress

How can I check that at-least one file is selected for upload

how can I check that user has selected at-least one file for upload in below code ?
i have tried with in_array, isset, !empty functions but no success
please note that userfile input is array in html
if(!empty($_FILES['userfile']['tmp_name'])){
$upload_dir = strtolower(trim($_POST['name']));
// Create directory if it does not exist
if(!is_dir("../photoes/". $upload_dir ."/")) {
mkdir("../photoes/". $upload_dir ."/");
}
$dirname = "../photoes/".$upload_dir;
for($i=0; $i < count($_FILES['userfile']['tmp_name']);$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i]))
{
$messages[] = 'No file selected for no. '.$i.'field';
}
/*** check if the file is less then the max php.ini size ***/
if($_FILES['userfile']['size'][$i] > $upload_max)
{
$messages[] = "File size exceeds $upload_max php.ini limit";
}
// check the file is less than the maximum file size
elseif($_FILES['userfile']['size'][$i] > $max_file_size)
{
$messages[] = "File size exceeds $max_file_size limit";
}
else
{
// copy the file to the specified dir
if(#copy($_FILES['userfile']['tmp_name'][$i],$dirname.'/'.$_FILES['userfile']['name'][$i]))
{
/*** give praise and thanks to the php gods ***/
$messages[] = $_FILES['userfile']['name'][$i].' uploaded';
}
}
}
}else{
$messages[] = 'No file selected for upload, Please select atleast one file for upload';
dispform();
}
Here's how I do it its a couple of if's and I use a for loop as I allow multiple file uploads from a single drop down but its the if's that are more important to you
$uploaded = count($_FILES['userfile']['name']);
for ($i=0;$i<$uploaded;$i++) {
if (strlen($_FILES['userfile']['name'][$i])>1) {
// file exists so do something
} else {
//file doesn't exist so do nothing
}
}
You'll note I compare against the name element of the global $_FILES this is because you should never be able to upload a file without a name which also applies for no file uploaded
Don't do it client side thats a dumb place to do validation as the user can simply turn js processing off in the browser or it can be blocked by certain addons etc or intercepted and altered via firebug and various browser search hijacking toolbars etc.
Anything like this should always be done server side!
finally I found the answer, I am giving it here for other users,
I have 5 keys in html input array so array index is up to 4
if(!empty($_FILES['userfile']['tmp_name'][0]) or !empty($_FILES['userfile']['tmp_name'][1]) or !empty($_FILES['userfile']['tmp_name'][2]) or !empty($_FILES['userfile']['tmp_name'][3]) or !empty($_FILES['userfile']['tmp_name'][4])){
//at-least one file is selected so proceed to upload
}else{
//no file selected, notify user
}
There are several methods of doing this with PHP (e.g. Check if specific input file is empty), but with JS it's faster and less expensive on the server. Using jQuery you can do this:
$.fn.checkFileInput = function() {
return ($(this).val()) ? true : false;
}
if ($('input[type="file"]').checkFileInput()) {
alert('yay');
}
else {
alert('gtfo!');
}

Set File Size Limit Message

I wonder whether someone could help me please.
I have to admit I'm relatively new to writing PHP so please bear with me.
Through articles I've read on the internet and some first class tutition from one #Marcio on this site, I've put together a script that allows users to save Image Files to a mySQL database.
I've now gone a little further by restricting the size of the file that can be uploaded, but I I'd like to add a warning message that tells why the file cannot be uploaded i.e. because it's size is greater than the limit set.
I've made an attempt at this, as seen in the code below. But unfortunately I receive an error message stating that there is an unexpected '>' which I know relates to the line I've added, but not sure how to code this another way.
Revised Cut Down Code
<?php
// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
return mysql_real_escape_string($s);
}
// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!isset($_POST["action"]))
{
// cleaning title field
$title = trim(sql_safe($_POST['title']));
if ($title == '') // if title is not set
$title = '(No title provided';// use (empty title) string
if (isset($_FILES['photo']))
{
#list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
// We use # to omit errors
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
if($_FILES["fileupload"]["size"]/1024000 >= 10) // 10mb
{
$fileErrMsg = "<br />Your uploaded file size:<strong>[ ". $_FILES["fileupload"]["size"]/1024000 . " MB]</strong> is more than allowed 10MB Size.<br />";
}
if (!isset($msg)) // If there was no error
{
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO {$table}
SET ext='$ext', title='$title',
data='$data'");
$msg = 'Success: Image Uploaded';
}
}
I just wondered whether someone could perhaps take a look at this and let me know what I'm doing wrong.
Many thanks and kind regards
You can use this
if($_FILES["fileupload"]["size"]/1024000 >= 10) // 10mb
{
$fileErrMsg = "<br />Your uploaded file size:<strong>[ ". $_FILES["fileupload"]["size"]/1024000 . " MB]</strong> is more than allowed 10MB Size.<br />";
}
getfilesize() returns image dimensions in pixels, not file size. You need something along the lines of this:
if (filesize($_FILES['tmp_name']) >= 100000)

Categories