Filedrop.js no success Message - javascript

i am using filedrop.js fo an Image Upload Script.
I fund a script here : https://tutorialzine.com/2011/09/html5-file-upload-jquery-php
In the Prject is a file_post.php which i wanted to change to save some informations (like the Filename) into a Database.
This is my post_file.php :
<?php
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'uploads/tmp/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
//My added code
include('/var/www/html/board/SSI.php');
$userName = $context['user']['name'];
$content_id = $_COOKIE["contentid"];
$pic_name = $pic['name'];
$pic_code = $content_id;
$pic_path = $pic_name;
$db_host = "******";
$db_name = "******";
$db_user = "******";
$db_pass = "******";
$db = mysqli_connect("$db_host","$db_user","$db_pass","$db_name") or die("Error " . mysqli_error($db));
$stmt = $db->prepare("INSERT INTO `User_pics` (content_id, path, user_id, user_name) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $pic_code,
$pic_path,
$context['user']['id'],
$context['user']['name']);
$stmt->execute();
$stmt->close();
//end of my added code
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
After i added the mysqli part the Success message is not shown anymore.
On the Image Upload the Progressbar stops at about 50%. The files are Uploaded and the informations are ssaved into the DB, but i got no success respons and this i need to handle the next steps. pleas help!
Thanks.

thanks for interrests,
two days i worked fo a soulution, after i asked here i found the Answer ;)
The Problem was the Include of the SSI.php which is encoded in UTF-8.
This was the reason for an Error in the Json encoded Response.
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
My soulution was:
I created a cookie for User ID and User name so i was able to remove the Include. After this every thing works great. If someone has the Same Error simply create a cookie where you are showing your Upload Form, after Upload delet them.
Thanks to the Community and have a nice Day ;)

Related

Imagick format conversion

I am trying to create thumbnails from pdf uploads using Imagick. I wrote a script that's supposed to do it, but, it only uploads the file without creating a thumbnail.
This will certainly make some of you roll your eyes, but, PHP is completely uncharted territory to me. Could anyone help me out? Thanks!
<?php
include 'includes/session.php';
include 'includes/slugify.php';
if(isset($_POST['add'])){
$name = $_POST['name'];
$slug = slugify($name);
$category = $_POST['category'];
$price = $_POST['price'];
$description = $_POST['description'];
$filename = $_FILES['photo']['name'];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$allowed = array('pdf', 'doc', 'docx', 'odc', 'jpg');
$conn = $pdo->open();
$stmt = $conn->prepare("SELECT *, COUNT(*) AS numrows FROM products WHERE slug=:slug");
$stmt->execute(['slug'=>$slug]);
$row = $stmt->fetch();
if($row['numrows'] > 0){
$_SESSION['error'] = 'document already exists';
}
else{
if(!in_array($ext, $allowed)) {
$_SESSION['error'] = 'Filetype not allowed';
}
else{
if(!empty($filename)){
$new_filename = $slug.'.'.$ext;
copy($_FILES['photo']['tmp_name'], '../documents/'.$new_filename);
}
else{
$new_filename = '';
creating a thumbnail
$img = new Imagick($filename[0]);
$img-> setImageFormat('jpg');
$convert = $slug. '.' .$jpg;
$img-> writeImages($_FILES['photo']['tmp_name'], '../images/'.$convert);
}
try{
$stmt = $conn->prepare("INSERT INTO products (category_id, name, description,
slug, price, photo) VALUES (:category, :name, :description, :slug, :price, :
photo)");
$stmt->execute(['category'=>$category, 'name'=>$name,
'description'=>$description,
'slug'=>$slug, 'price'=>$price, 'photo'=>$new_filename]);
$_SESSION['success'] = 'document added successfully';
}
catch(PDOException $e){
$_SESSION['error'] = $e->getMessage();
}
}
}
$pdo->close();
}
else{
$_SESSION['error'] = 'Fill up product form first';
}
header('location: documents.php');
?>
It looks like your call to $img->writeImages($_FILES['photo']['tmp_name'], '../images/'.$convert) is incorrect: you're passing two strings (the filename of an uploaded image and what looks like a destination filename) but the Imagick documentation indicates you should be passing only a destination filename (along with an optional Boolean).
So this:
$img-> writeImages($_FILES['photo']['tmp_name'], '../images/'.$convert);
Should probably be:
$img-> writeImages('../images/'.$convert);
Also, it's hard to tell whether the two chunks of PHP that you posted come one after the other, but if they do, then your logic for when to create the images looks faulty:
if(!empty($filename)){
// Do some stuff
} else {
// Write the images
}
The problem here is that the block of code that writes the images only executes when $filename is empty. Shouldn't it write the images if $filename is not empty?
Last but not least, the Imagick writeImages() function returns a Boolean indicating whether it was successful. You should store this result and log it to see what the result is. You should also confirm that your destination filename ('../images/'.$convert) is correct, and that the path exists and is writable.

ajax call download fails on chrome works on firefox

Hello I am using spout to run some excel reports. I have a user interface where they input date, model, and other information then I do a GET to send it to a php script where I run a query and then put all the results into an excel file like this:
ini_set('max_execution_time', 600); //300 seconds = 5 minutes
require_once 'spout-2.7.2/src/Spout/Autoloader/autoload.php'; // don't forget to change the path!
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
$reportDate=date("Ymd_hhmmss");
$filename="combined_report".$reportDate.".xlsx";
include ("../log/connectionToDb.php");
$conn = connectionSQL();
//provide error if connection fails
if (!$conn) {
echo "An error occurred.\n";
exit;
}
//connected successfully to db. Do not echo anything otherwise it will not show up on dropdown.
else {
//echo "connected";
}
//From date and to date static in case not provided by user
$fromDate = $_GET['convertedFrom'];
$toDate = $_GET['convertedTo'];
$line= $_GET['selectedLine'];
$model_num=$_GET['modelNumber'];
$writer = WriterFactory::create(Type::XLSX);
ob_start();
$writer->openToBrowser($filename);
$sheet = $writer->getCurrentSheet();
$sheet->setName('Production Data');
$rowCount = 2;
$flag=false;
$production = "query";
//echo memory_get_usage() ;
$result1 = sqlsrv_query($conn, $production);
if($result1 === FALSE){
die(print_r(sqlsrv_errors(), TRUE));
}
do{
if(!$flag) {
$headerRow = ['line', 'Work order','Model number', 'Revision','Serial number','Lpn','Date created','Date completed'];
$writer->addRow($headerRow);
$flag = true;
}
else{
$reportRow = [$row['line'], $row['work_order'], $row['model_num'], $row['revision'],$row['serial_num'],$row['LPN'],$row['date_created'],$row['date_completed']];
$writer->addRow($reportRow);
$rowCount++;
}
}
while ($row = sqlsrv_fetch_array($result1));
$writer->close();
$xlsData = ob_get_contents();
ob_clean();
$response = array(
'op' => 'ok',
'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
);
}
die(json_encode($response));
Then on the AJAX call I have the following:
$.ajax({
url: 'modelData/excel-export.php',
method: "GET",
data: {'modelNumber':modelNumber,'convertedFrom':converted_from_UTC,'convertedTo':converted_to_UTC,'selectedLine':selectedLine},
dataType:'json',
success: function(fileCreated){
}
}).done(function(data){
console.log(local);
var $a = $("<a>");
$a.attr("href",data.file);
$("body").append($a);
$a.attr("download","combined_report_"+local+".xlsx");
$a[0].click();
$a.remove();
});
now if I run this in Firefox everything works I am able to download up to 4 months of data which is >60,000 records this has no problem. If I run this in google chrome I cannot download more than 1 week about 20,000 records and U get a "download failed -network error" I was using PHPExcel but then found out it didn't support too many records so I switched to spout but I find the same issue only in google chrome but I don't understand where this limitation is coming from. I have read multiple posts and I have tried setting headers, lengths etc but nothing has worked also I chatted with a spout forum and they said none of the headers were necessary but they were still unable to help me.
I think this question Download failed - network error in google chrome but working in firefox may be going close to the same direction as my issue.
Also I have tried running incognito mode chrome I have tried disabling all extensions
As a side note...The firefox download appears to work fine but we don't "support" firefox so it would be hard for customers to go to multiple browsers specially when they're not tech savy
Any help will be greatly appreciated! :)
I was able to solve this issue by doing the following:
JS
window.open("modelData/excel-export.php?modelNumber="+modelNumber+"&convertedFrom="+converted_from_UTC+"&convertedTo="+converted_to_UTC+"&selectedLine="+selectedLine,
'_blank'// <- This is what makes it open in a new window.
);
then on the PHP side:
ini_set('max_execution_time', 600); //300 seconds = 5 minutes
require_once 'spout-2.7.2/src/Spout/Autoloader/autoload.php'; // don't forget to change the path!
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
$reportDate=date("Ymd_hhmmss");
$filename="combined_report".$reportDate.".xlsx";
include ("../log/connectionToDb.php");
$conn = connectionSQL();
//provide error if connection fails
if (!$conn) {
echo "An error occurred.\n";
exit;
}
//connected successfully to db. Do not echo anything otherwise it will not show up on dropdown.
else {
//echo "connected";
}
//From date and to date static in case not provided by user
$fromDate = $_GET['convertedFrom'];
$toDate = $_GET['convertedTo'];
$line= $_GET['selectedLine'];
$model_num=$_GET['modelNumber'];
$writer = WriterFactory::create(Type::XLSX);
$writer->openToBrowser($filename);
$sheet = $writer->getCurrentSheet();
$sheet->setName('Production Data');
$rowCount = 2;
$flag=false;
$production = "query";
//echo memory_get_usage() ;
$result1 = sqlsrv_query($conn, $production);
if($result1 === FALSE){
die(print_r(sqlsrv_errors(), TRUE));
}
do{
if(!$flag) {
$headerRow = ['line', 'Work order','Model number', 'Revision','Serial number','Lpn','Date created','Date completed'];
$writer->addRow($headerRow);
$flag = true;
}
else{
$reportRow = [$row['line'], $row['work_order'], $row['model_num'], $row['revision'],$row['serial_num'],$row['LPN'],$row['date_created'],$row['date_completed']];
$writer->addRow($reportRow);
$rowCount++;
}
}
while ($row = sqlsrv_fetch_array($result1));
$writer->close();
The library I am using just doesn't work very well with AJAX so this approach solved my issue. Thanks for all the help :)
I used Blob Javascript for the same problem.
this link maybe help someone :
Blob

Is it possible to access the Prestashop's Web service by client (customer) login instead the key?

I'm studying Prestashop's development. And I trying to create a "third part" side application with react.js (React Native for more precision) and catch Json data in the prestashop's webservice. But I want to let the "customer" make login with his own account and only his account. With CRUD also.
in advance; Very thank you for your patience and attention.
Best Regards.
Michel Diz
Prestashop backoffice login give no access to webservices. Webservices must be enabled and a key generated. So, I recommend you that change your "login" way. Customers accounts are not related with webservices and webservices are only used to access stored data un Prestashop (more like Backoffice than Frontoffice).
What exactly do you need to do?
I hope it helps you.
I don't know if you're still searching for a solution but there is a way actually.
DO MAKE SURE IT IS A SECURE LOGIN.
Since you're giving access to all prestashop data do make sure the login is very secure. I've been able to recreate it with PHP I think that with some additions you're able to recreate it the way you want it. See it as a guideline.
To create a login system by using the prestashop webservice you'll need three things
Access through webservice to the customers table
The COOKIE_KEY, defined in app/config -> parameters.php:: 'cookie_key' => '12321test';
Some expierence with PHP
The first thing is to get the customers table from the webservice.
// code placeholder
require_once('./../PSWebServiceLibrary.php');
/**
* get information from PrestaShop
*/
$webService = new PrestaShopWebservice($url, $key, $debug);
$COOKIE_KEY = 'CookieKey';
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
$optUser = array(
'resource' => 'customers',
'filter[email]' => '[' . $email . ']',
'display' => '[id,email,lastname,firstname,passwd]'
);
$resultUser = ($webService->get($optUser));
$json = json_encode($resultUser);
The second and most important thing is to Check the user input
// code placeholder
foreach ($resultUser->customers->customer as $info) {
// Prestashop uses the cookie_key in combination with a salt key. To check the password use the php function: password_verify();
$salt = substr($info->passwd, strrpos($info->passwd, ':') + 1, 2);
$ZCpassword = md5($COOKIE_KEY . $password) . ':' . $salt;
// Check if password comparison is true or false
if (password_verify($password, $info->passwd) == true) {
session_start();
$response = array();
$response['status'] = 'succes';
$response['message'] = "You did it!";
setcookie("userId", $info->id);
header('Content-type: application/json');
echo json_encode($response);
} else {
$response = array();
$response['status'] = 'error';
$response['message'] = 'Wrong password';
header('Content-type: application/json');
echo json_encode($response);
}
}
This is how to reproduce the issue to a working example.
Hope this helps!
For those who are still searching for this answer,
<?
if (isset($_GET["email"]) && isset($_GET["password"]) )
{
$email = $_GET["email"];
$password = $_GET["password"];
$COOKIE_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$jsonurl = "https://XXXXXXXXXXXXXXXXXXXX#example.com/api/customers?filter[email]=".$email."&display=[passwd]&output_format=JSON";
$json = file_get_contents($jsonurl);
$json_a = json_decode($json, true);
$loopone = $json_a['customers'];
$looptwo = $loopone[0];
$loopthree = $looptwo['passwd'];
$ZCpassword = md5($COOKIE_KEY . $password);
if (strcmp($loopthree, $ZCpassword) == 0) {
echo "sucess";
} else {
echo "fail";
}
}
else
{
echo "Send something with url dude";
}
?>

using phpfile output inside js file file as variable

Recently I am learning single page application, but I got a problem, the project I am working on is inside a folder that contain many folders, php js are folders in side the main folder, and each contain its type of files, the problem is that one of the php file called getmax.php gives me the maximum id ,I want to use this max(id) in a js file called module.js in order to give the new module the next id , the module.js should gives this id to another php file called insert.php ,the connection between the module.js and insert.php is working properly if I set the id manually . but I could not figure out how can I make it use the max(id) from the getmax.php file.
note: I noticed lately I'm using MySQL and I should used mysqli I will fix it later.
the getmax.php is:
<?php
// alle relevanten Tabellen abfragen und als json zurückgeben.
$json["status"] = "running";
$details[] = "started get_tables ";
// Include confi.php
include_once('confi.php');
//var_dump($_POST);
$request_body = file_get_contents('php://input');
// first store the given set of data to keep it for future analysis
$statement = "INSERT INTO tbl_archive (content) VALUES ('$request_body' );";
mysql_query($statement);
$input = json_decode($request_body, true);
// now check if valid user
$user = $input["user"];
$username = $user["username"];
$password = $user["password"];
if($password and $username){
$mySQLstring = "SELECT username, password, id, create_user FROM tbl_user where username = '$username' ;";
$json["statement"][] = $mySQLstring;
$qur = mysql_query($mySQLstring);
//var_dump ( $qur );
if ($qur){
$max = mysql_fetch_assoc($qur);
}
if ($max){
$json["max"] = $max;
if ($max["password"] == $password){
$json["username"] = $username;
$json["id"] = $max["id"];
$json["create_user"] = $max["create_user"];
$json["status"] = "ok";
$tables = array("class", "class_user", "module", "module_class", "module_user", "rating", "student", "student_class");
//$tables = array("class");
foreach($tables as $table){
if ( $table == 'module' ){
$statement ='SELECT create_user, MAX(id) FROM tbl_'.$table;
//$statement .= ' GROUP BY create_user' ;
$statement .= ' WHERE create_user = 19 ' ;
$qur = mysql_query($statement);
if ($qur){
while($r = mysql_fetch_array($qur, MYSQL_ASSOC)){
//var_dump($r);
//echo (json_encode($r));
$result[$table][] = $r;
}
}
}
}
$json = array("status" => "ok", "data" => $result);
}
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
PHP and JS are run on the server and client respectively, and as such you cannot call methods/functions of one from the other. AJAX exists to pass values between JS and serverside code.

canvas.toDataURL() From a live video feed capture then save to fileserver with reference in DB

I am working on a database where we need to have user form data and an image captured from a web cam then send the user data to the DB with a link to the photo on a file server. I am using the code found here http://davidwalsh.name/demo/camera.php (with added dataurl and base64 coding) for the image capture to canvas. I have searched for the past 2 weeks (unknown separate pieces of code changes and reversions) prior to posting here and have read a few people stating that a similar question has been asked about the Canvas.toDataURL() but it is just not working for me.
I am getting a file uploaded as a png but the file has a size of 0. I have no experience with other forms of coding (ruby/api/ajax/python) so I am not able to code with those. If those are mandatory then I will have to find another method (action script through Flash possibly) to make this work or abandon this until those scripts are learned.
Any info if this is even possible using PHP and mySQL would be helpful so I am not trying to create something that is not possible. The platofrm/delivery system will be an in house server on our intranet. currently testing on the web host server on windows computers running google chrome (also tested on firefox, opera and IE) Thanks in advance for taking the time to read through.
In my form.php
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var C = canvas.getContext('2d');
}
$('#canvas').submit()(function(event) {
// feel free to choose your event ;)
// just for example
// var OFFSET = $(this).offset();
// var x = event.pageX - OFFSET.left;
// var y = event.pageY - OFFSET.top;
// standard data to url
var imgdata = canvas.toDataURL('image/png');
// modify the dataUrl so the browser starts downloading it instead of just showing it
var newdata = imgdata.replace(/^data:image\/png/,'data:application/octet- stream');
// give the link the values it needs
$('a.linkwithnewattr').attr('download','your_pic_name.png').attr('href',newdata);
});
In my addcontent.php
<?php
include("connectionInfo.php");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$name = $_POST['name'];
$phone = $_POST['phone'];
$duedate = $_POST['duedate'];
$employee = $_POST['employee'];
$address = $_POST['address'];
$email = $_POST['email'];
$estimate = $_POST['estimate'];
$dataURL = $_POST["canvas"];
//input file into images folder
$image = str_replace('data:image/png;base64,', '', $dataURL);
$image = str_replace(' ', '+', $dataURL);
$image = base64_decode($dataURL);
$filename = "$duedate$name.png";
file_put_contents('images/' . $filename, $dataURL);
// create path for image upload
$path = "images/" . $filename;
move_uploaded_file($_FILES["file"]["tmp_name"],$path);
//show file location
echo "Stored in: ". $path;
//store file path in database
if(mysql_query("INSERT INTO JobBags (image) VALUES ('$path')")){
echo "Successfull!!";} else {
echo '---fail-sadface---';}
// put customer info into job bag database
$sql = "INSERT INTO JobBags (name, phone, duedate, employee, address, email, estimate, image)
VALUES ('$name', '$phone', '$duedate', '$employee', '$address', '$email', '$estimate', '$dataURL')";
//check if jobbag created correctly
if ($conn->query($sql) === TRUE) {
echo "New record created successfully.";
} else {
echo "Error: " . $mysqli . "<br>" . $conn->error;
}
// close connection to database
$conn->close();
?>

Categories

Resources