Sending data from an iframe with an interactive pdf to a php - php

I have an that displays an interactive pdf form. How do I create a button to get data from the pdf document. Need help please, been on this the whole day.
Here's the php file that supposed to get the pdf data
if(isset($_POST) && is_array($_POST) && count($_POST)){
$data=array();
$data['topmostSubform[0].Page1[0].Applicant_Surname[0]']=$_POST['topmostSubform_0__Page1_0__Applicant_Surname_0_'];
$data['topmostSubform[0].Page1[0].Applicant_FirstName[0]']=$_POST['topmostSubform_0__Page1_0__Applicant_FirstName_0_'];
// need the function definition
require_once'createFDF.php';
// some variables to use
// file name will be <the current timestamp>.fdf
$kui = time();
/*$kui = time();*/
$fdf_file=$kui.'.fdf';
// the directory to write the result in
$fdf_dir=dirname(__FILE__).'/results';
// need to know what file the data will go into
$pdf_doc='http://localhost/uniApp/results/fillsheet.pdf';
// generate the file content
$fdf_data=createFDF($pdf_doc,$data);
// this is where you'd do any custom handling of the data
// if you wanted to put it in a database, email the
// FDF data, push ti back to the user with a header() call, etc.
// write the file out
if($fp=fopen($fdf_dir.'/'.$fdf_file,'w')){
fwrite($fp,$fdf_data,strlen($fdf_data));
/* echo $fdf_file,' written successfully.';*/
system("pdftk fillsheet.pdf fill_form results/". $fdf_file. " output results/$kui.pdf flatten");
$_SESSION['message'] = 'Your application has been updated';
$message = 'written successfully.';
echo $kui,' written successfully.';
}else{
die('Unable to create file:'.$fdf_dir.'/'.$fdf_file);
}
fclose($fp);
}
It works well when it using pure php code, but doesn't work when i try it from the <iframe>

Related

Modal doesn't write the link of a PDF file generated with TCPDF, after an AJAX call

This code works. So far, I've only found one exception that breaks it, and it happens only on the live server, on localhost it still works fine all the time.
So, what's the problem.
Basically I generate a PDF file with TCPDF (note that the file is pretty big, over 700 pages) using AJAX and the call returns the link to the file, which I will then append to a modal to let the user choose whether he wants to go to the file, or download it.
This is the AJAX code.
$('#stampa-file').on('submit', function(event)
{
event.preventDefault();
$.ajax({
url:'stampa_file.php?act=stampa',
method: 'POST',
data: $('#stampa-file').serialize(),
success: function(data)
{
if($.trim(data) == 'query_error')
{
alert('Qualcosa è andato storto. Riprova.');
}
else if($.trim(data) == 'stampa_error')
{
alert('Seleziona almeno una sezione');
}
else
{
$('#stampa-file')[0].reset();
$('#loadingModal').modal('hide');
$('#document-link').empty();
$('#document-link-download').empty();
$('#document-link').append('<i class="fas fa-eye"></i> Visualizza PDF');
$('#document-link-download').append('</i> Scarica PDF');
$('#viewFile').modal('show');
}
}
});
});
This is the TCPDF code.
//I generate the PDF above this comment. Below only the link generation, PDF output and save the file into the database.
//Close and output PDF document
$replace = array(" ", "'");
$replacer = array("");
$nome = strtolower($query_ente['nome']);
$now = date("Y_m_d_H_i_s", time());
$link = trim(str_replace($replace, $replacer, 'RDAT_'.$nome.'_'.$now.'.pdf'));
ob_clean();
$pdf -> Output($path_stampa_file.$link,'F');
$output = '';
$timestamp = time();
$result_inserimento = mysqli_query($mysqli, "INSERT INTO files (link, nome, timestamp, categoria) VALUES ('$link', '$link', '$timestamp', 'stampa_rdt')");
if($result_inserimento)
{
/*Registro Attività*/
include 'connessione_multi.php';
session_start();
$user_check = $_SESSION['login_user'];
$result_user_info = mysqli_query($conn, "SELECT * FROM sessioni_login WHERE session_id='$user_check'");
$query_user_info = mysqli_fetch_assoc($result_user_info);
$session_user_id = $query_user_info['id_utente'];
$id_utente = $session_user_id;
$descrizione = 'ha eseguito la stampa del file: '.$link.'';
$timestamp = time();
$indirizzo_ip = $_SERVER['REMOTE_ADDR'];
$result_attivita = mysqli_query($mysqli, "INSERT INTO attivita (id_utente, descrizione, timestamp, indirizzo_ip) VALUES ('$id_utente', '$descrizione', '$timestamp', '$indirizzo_ip')");
$output = $link;
}
else
{
$output = 'query_error';
}
echo $output;
Like I said I have everything working fine, but I can't understand why in just one case, for one customer and only on the live server, not on localhost, it fails. Basically when it fails, what I get in the result of the AJAX call is an empty value and the link in the modal looks like this
www.mysite.com/files/customer_name/
instead of
www.mysite.com/files/customer_name/RDAT_customername_timestamp.pdf
I tried some stuff, but I still can't find a solution.
Things that I tried:
get the link from the database by calling another AJAX request inside the success of the first AJAX call, printed the link in a hidden DIV inside the page and get the link with jQuery .text() and then append it to the modal;
append the link in the "complete" event of the AJAX call instead of "success";
get the link from the database right after it gets saved on the TCPDF generation file, rather than using the same variable $link in the same file;
removed every action in the success event of the AJAX call and only leave the append events;
All of these tests work fine all the time, except for that one time that it fails on the live server.
I really have no other option at this point.

PHP: Returning string from server to client when json_encode fails

I'm writing an application that sends some data to my server in order to produce a PDF file. To do this I use shell_exec to call on the approapiate latex compilation command. I always show the output of log in the cliente by using the following code in the server(this is oversimpliefied to show the problem):
$log = shell_exec("cd ../../template; pdflatex $texinput;");
$ret["log"] = $log;
echo json_encode($ret);
However every once in a while the log will contain a chararcter that will break the json_encode. That is json_enconde($ret) will be false.
Is there any other way to send the information (as text or maybe as a file) to the client?
EDIT:
Since the output is the output of a Latex compilation it is very difficult to reproduce simply. However, as I've been asked to provide an example, I managed to create this minimal example using the log file (automatically saved by the pdflatex command) and this minimal php script.
This is the PHP script:
$trial = "trial.log";
$handle = fopen($trial,"r");
$data = fread($handle,filesize($trial));
if ($handle === false){
$errors = error_get_last();
$ret["error"] = "Could not open $trial for reading. Type: " . $errors["type"] . " MSG: " . $errors["message"];
return;
}
fclose($handle);
echo "Done reading<br>";
if (json_encode($data) === false){
echo "I've failed";
}
else{
echo "All good";
}
This is the file trial.log
https://www.dropbox.com/s/04ejx5s1mj0ojj2/trial.log?dl=0
I've tested it in my browser and I get the I've failed. However I have bypassed the problem. (See my answer)
So after trying a couple of different things, I went with trying to send the pdflatex generated log file to the client. So instead of returning the contents of the file (which are the same as the contents returned by the command) y returned the path to the log file. Then in my browser I used this code:
// Getting the base URL
var url = window.location.href;
var l = url.length;
while (l--){
if (url[l] == '/') break;
}
url = url.substring(0,l);
// Creating the URL for the log file.
var logfile = url + obj.logfile;
The obj.logfile was the relative path in my server to the log file. Then I used the following to load the file into a text area.
// Loading the log file.
$.ajax({
type: "GET",
url: logfile,
success: function(text) {
document.getElementById("pdflatex_out").value = text;
},
error: function() {
document.getElementById("pdflatex_out").value = "Error. please contact the administrator";
}
});

Session goes break in codeigniter

I have created a form in codeigniter. This form is displayed after login. When I fill form with upload an Image then my codeigniter site break session and goes to login form. But if I submit form without file uploading then this work fine. Please help me.
EDITED....
$result = $this->addcategory->addcategory($add_cat); //Save the data
if($result > 0){ //Check last inserted id
if(!empty($_FILES['HM_cat_image']['name'])){ //check file upload or not
$time = time();
$upImage = uploadImage($_FILES['HM_cat_image'],$time); //Helper function to upload image in folder
if($upImage == 1){ // if file upload then return 1
$catImage = $time . '_' . $_FILES['HM_cat_image']['name'];
$catImageData = array('category_id' => $result,'image' => $catImage);
$imgRes = $this->addcategory->addCategoryImage($catImageData); // Save image in database
if($imgRes > 0){
$this->session->set_flashdata('message', 'Information Has been Successfully Saved');
}else{
$this->session->set_flashdata('message', 'Information Has been Successfully Saved But Error In Image Saving.');
}
}else{
$this->session->set_flashdata('message', 'Information Has been Successfully Saved But Error In Image Upload.');
}
}else{
//$data['formMsg'] = 'Data Saved Successfully.';
$this->session->set_flashdata('message', 'Information Has been Successfully Saved');
}
redirect('folder/controller/allCategory','refresh');
}
New Edited........
When I upload small Images then this issue not come but when I try to upload large image like 450X250 or large then this issue come.
check the following points, hope this will help.
set your CI encryption_key into 'application/config.php' to use session.
load session library
check your form is set to accept 'multipart'.
Make sure your session is created, add this code on your login controller
$this->output->enable_profiler(true);
search and find your session you want in session section on output from codeigniter profiler.
or you can save session on your database, use
$config['sess_use_database'] = TRUE;
and setup that

download button - save file to disk instead of opening

I have a download button and when i click on it, instead of saving to disk it opens it in the browser. I tried a bunch of attempts to make it open in the browser but it doesnt seem to do anything
<?php
// make a connection to the database
require_once("connection/connection.php");
//retrieve the ID from the url to fetch the specific details
if ($_GET['id'] != ""){
$item_id = $_GET['id'];
$bad_id = FALSE;
}
else{
$item_id = "";
$bad_id = TRUE;
}
//select the specific item from the database
// run if statement to ensure valid id was passed
if (is_numeric ($_GET['id'])){
$query = "SELECT name FROM repository WHERE item_id = '$item_id'";
$result = mysql_query($query) or die(mysql_error());
// assign the values to an array
$row = mysql_fetch_assoc($result);
//assign the values from the array to variables
$name = $row['name'];
}
// define path to the xml file
$file = "xml/".$hud_name . "_cfg.xml";
// check to make sure the file exists
if(!file_exists($file)){
die('Error: File not found.');
} else{
// Set headers
header("Content-Type: application/xml");
header("Content-Disposition:attachment; filename=".basename($file)."");
readfile($file);
}
?>
That is download.php and it obviously finds the file because it doesnt give the error about it not existing. It also echos back the correct file path
Then on another page i have:
<img src="images/download.png" alt=""/>
Any ideas whats wrong?
Well the solution turned out to be simple in the end but i didnt see any documentation saying the header must be the very first line. If i placed:
header("Content-Type: application/xml");
as the first line and then the coding below it and the other header info at the end it works. Im not sure if that's the solution or a workaround but it fixed it for me

Check if form file exists on page load using PHP

So I have a simple form that takes a user input, passes it to a separate PHP script that does some processing on a different domain, and posts a txt file if successful. Example:
<form method="GET" action="inventory_check.php" target="_blank">
Part Number <input type="text" name="part" /><input type="submit" value="Check Inventory" />
</form>
<?php
$filename = $userInput;
if (file_exists('ftpMain/'.$filename.'')) {
$handle = fopen("ftpMain/".$filename."", "r");
$output = fread($handle, filesize('ftpMain/'.$filename.''));
fclose($handle);
$output = trim($output, '&l0O(10U');
$output = trim($output, 'E ');
echo $output;
}
else {
echo 'Failure.';
}
?>
So, inventory_check.php obviously is an inventory lookup for us, however, it's contained on another server (different domain) so it completes its processing and posts it to a file, that I read, cleanup, and display. Now my issue is twofold, I need to grab and keep the input from the user to find the filename and the second is I need to page to either reload or recheck if the file exists. What is the best approach to do this?
Note: We use an awful in house DBMS, so posting and retrieving from a DB is not an option, it took us a while to get it to read the input and FTP it correctly, so it looks like this is the only path.
Why don't you make the request in your server A? by using curl, so you could get the response right after the query.
Firstly, you'll need to get the user's input properly, and sanitize it. I'll leave out the details of the sanitize() method, as that's not really what you're asking.
<?php
if(isset($_POST)) {
$part_number = sanitize($_POST['part']);
$filename = "ftpMain/$part_number";
if (file_exists($filename)) {
$handle = fopen($filename, "r");
$output = fread($handle, filesize($filename));
fclose($handle);
/* Do things with output */
} else {
echo 'Failure.';
}
}
?>
However, you say that the file is on another server - looking for ftpMain/... is only going to look for a directory called ftpMain in your current directory. Is the file publicly available on the internet? If it is, you could do something like this:
<?php
$url = "http://yourserver.com/parts/$part_number.txt";
$response = get_headers($url, 1);
if ($response[0] == 'HTTP/1.1 200 OK') {
/* The file exists */
} else {
/* The file does not exist */
}
?>
I hope I've understood your question correctly - this assumes that the form action is pointing to itself. That is, your file with this code is also called inventory_check.php.

Categories