generate document and then zip with php - javascript

I have an issue.
I have an index.php with several checkboxes.
Every checkbox represents a piece of code.
I am trying to create some generating tool.
For example: if I select four checkboxes, I want that four specific parts of code to generate in one php file, then zip it and download on my computer.
I know I can do it something like this:
$files = array('list.php', 'one-image.php', 'gallery.php', 'pdf.php');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
but, at the moment i am pretty lost.
Thanks in advance.

Copied from comments:
Read the files yourself using file_get_contents, concatenate using +, write to zip with ZipArchive::addFromString.

Related

how to save tensorflow save model multiple files in php

I have developed a neural network model with tensorflow. I want to save weights of my model on each time they update. So i though of updating a file on the server every time it learns. but the documentation on tensorflow js website on saving model using http server is really confusing. So i did some research and found some code. Still it is not working. I know i am missing the "multipart/form-data" and fact that there are two files, "The body consist of two files, with filenames model.json and model.weights.bin". Could not find anything that could help me. link to tensorflow documentation!
javascript to save
model.save('http://example.com/save.php');
save.php
<?php
$putdata = fopen("php://input", "r");
$fname = "weights.json";
$file = fopen("../static/" .$fname, 'w');
while ($data = fread($putdata, 1024)){
fwrite($file, $data);
}
fclose($file);
fclose($putdata);
?>
http://php.net/manual/en/function.file-put-contents.php
I don't see the input section with php stdin. This makes me feel like the connection isn't sending a stream like a socket connection, but rather a standard HTTP payload with a body attribute. But wait, theirs caveats. If it is a JSON payload you'll need the second two lines (like you had in your code, but not as a resource). The first two are my guess as to what may be going on. Remember you can debug through your browsers console to see the data payload, request method, ect...
$data = '<pre>' . json_encode($_POST) . '</pre>';
file_put_contents('stdPost.html', $data);
$data = file_get_contents('php://input');
file_put_contents('stdInput.json', $data);

How to generate a .doc using AJAX and PHP

today i need some help, i know its not that hard and there is a lot of help for doing this in php in this site but i couldn't find nothing with AJAX, the technology im learning now and i want to master some day.
My code is the following.
$(".descarga").click(function(){
var paquete={idArchivo:$(this).val()};
$.post("includes/descargarPublicacion.php",paquete,procesarDatos);
});
So when a buttom from the "descarga" class i make a "packet", which i use it with the post method to send the data to the php file called descargarPublicacion.php
This is how it looks the php file:
<?php
session_start();
$mysqli = new mysqli("localhost", "root", "", "registroflashback");
if (isset($_GET['idArchivo'])) {
header("Content-type: application/vnd.msword");
header("Cache-Control: must-revalidate,post-check=0, pre-check=0");
header("Content-disposition:attachment;filename=yeaboi.doc");
header("Expires: 0");
$idPubliGet=$_GET['idArchivo'];
$resultadoBusqueda=$mysqli->query("SELECT * FROM publicaciones WHERE idPubli='$idPubliGet'");
if ($resultadoBusqueda->num_rows>0) {
//$resultadoBusqueda['titulo'];
echo 'descarga exitosa';
}else{
echo 'descarga no exitosa';
}
}else{
echo 'descarga no exitosa';
}
?>
I made a little research and people told me to use the headers to convert the file and download it, but it dosnt works for me, it dosnt generates any file, however it executes the "echo descarga exitosa" which i use as return value for the following function in the js file.
function procesarDatos(datos_devueltos){
alert(datos_devueltos);
if(datos_devueltos=="descarga exitosa"){
$("#alertaDescarga").show(1000);
}
if(datos_devueltos!="descarga exitosa"){
$("#alertaDescargaError").show(1000);
}
}
How i could generate a .doc file from html using ajax and jquery? I know i have it almost, it should be some detail but i dont know which one is, thats why im asking some experienced help! Thank you !
I do not understand why you want to to serve the .doc file via ajax. In my opinion it's easier to just provide valid .doc over a normal GET Request.
$(".descarga").click(function(){
//onClick transfer id via Get-Param and download file
window.location = "includes/descargarPublicacion.php?idArchivo="+$(this).val();
});
php part (descargarPublicacion.php)
<?php
if (isset($_GET['idArchivo'])) {
header("Content-type: application/vnd.msword");
header("Cache-Control: must-revalidate,post-check=0, pre-check=0");
header("Content-disposition:attachment;filename=yeaboi.doc");
header("Expires: 0");
//ID is available via GET because we send it as Url Param
$idPubliGet=$_GET['idArchivo'];
//#TODO fetch relevant data with given ID
//#TODO generate valid(!) doc File output
//- just echo'ing something will not result in an valid document for Word
echo $coumentContent;
}
?>
To provide/generate a valid Word document is a little bit more complicated. I would recommend you to look into a libary which does all the work for you.
E.g. https://github.com/PHPOffice/PHPWord
If you instead want to serve just some simple .txt File - change your header Content-Type to text/plain and the filename to yeaboi.txt and print/echo out the text-content

get specific parts of my file name as links

this is how i want my file name looks like : 55478_john_toyota_red.pdf
i have to file in a table of those informations
and this is how i get my file name for the moment :
echo ''.$file.'';
i want to know how can i get the number in an echo and name in another one ...as links to the same file.
my files will change all the time.
should i change the name of my file? can it be done like that?
it worked with this :
$data = "$file";
list($numero,$nom,$marque,$couleur) = explode("_", $data);
echo ''.$numero.'';//in the same way i can get anything i want from the title
echo ''.$nom.'';
I would use explode function .. and then implode function to rebuild the file name like this:
$tempArray = explode('_', $file);
array_shift($tempArray);
$newFileName = implode(' ', $tempArray);
echo ''.$newFileName.'';
Try this version .. it should work now

PHP - how to give path to read pdf?

Select file name and redirect..
index.php
<?php
$book_name = ["Jenkins_Essentials","Asterisk","phalcon"];
echo "<select><option selected>Book Name</option>";
foreach ($book_name as $key => $value) {
echo "<option name='$key'>$value</option>";
}
echo "</select>";
?>
<script type="text/javascript">
$(document).ready(function(){
$("select").on("change",function(){
location.href = "reading.php?title="+$(this).val();
});
});
</script>
reading.php
$title = $_GET["title"];
header("Content-type: application/pdf");
header('Content-Disposition: inline; filename="$title.pdf"');
#readfile('D:\Learning\$title.pdf');//this is my issue
When I redirected it show Failed to load PDF document..
My running script file location is as we know C:\xampp\htdocs But pdf file place is as shown in above D: drive !How to give path to it?
On your last two lines, PHP isn't including the $title variable, as you are using single quotes and you are using backslashes. Try one of these:
header('Content-Disposition: inline; filename="'.$title.'.pdf"');
#readfile('D:/Learning/'.$title.'.pdf');
or:
readfile("D:/Learning/$title.pdf");
Backslashes are used for escaping characters, so use forward slashes as much as you can. On Windows, you can use both in file paths. Also, for outputting the file, try using this instead of #readfile:
$pdf = file_get_contents('D:/Learning/'.$title.'.pdf');
echo $pdf;
Another note - you should check if the file exists before accessing it. Place at the top of your script:
if(!file_exists('D:/Learning/'.$title.'.pdf')) {
echo "File doesn't exist.";
exit();
}
Hope this helps. Wish you the best.
Is the file name 'D:\Learning\$title.pdf' literally $title.pdf with the dollar ($) sign.
PHP variable interpolation works on the " double quote meaning that your variable is literally a string and not recognized as a variable by php.
You'll most likely want to change that to
readfile("D:\Learning\$title.pdf");
OR ( personally I would avoid this because of the back slash escaping ) However it's worth noting that windows will accept the forward slash ( Unix style )
readfile('D:\Learning\\'.$title.'.pdf');
readfile('D:/Learning/'.$title.'.pdf'); //this works fine on windows and avoids escaping the \
OR what I prefer.
readfile("D:\Learning\{$title.pdf}");
Otherwise it's looking for a file named $title.pdf literally

PHP capture form data and image upload, save to server

I know that this should not be a difficult thing to accomplish in PHP however it is giving me the hardest time!
I am trying to do this:
1) Capture form string data AND an image upload in a single form
2) Upload both types of data to the server with a single non-ajax/traditional POST to a simple PHP script (process.php in this case)
3) Take the image the user uploaded, save it in as a text file in a directory named dynamically by the first letter of the first name and the entire last name concagnated together so for me the directory structure would be as follows: /home/uploads/nabrams/image.jpg, /home/uploads/nabrams/userdata.txt,
*The text file will contain the text strings from the client side form, the image from the input[type="file"], once again contained in the same form, sent to the server with 1 submission.
I am using a text file in order to provide the simplest case possible.
Here is the code I am working with currently:
<?php
$uploaddir = '/home/nicholasabrams/public_html' + '/newprofiledata/' + $lname + '/' + $_FILES['userfile']['name'];
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_POST);
print_r($_FILES);
print "</pre>";
However when attempting to upload an image of several formats and sizes (multiple attempts), I am stuck at an error-less blank window. To no surprise, the script did not upload or rename the image as desired.
Also - when trying to add the post data directly into the file name like so:
$uploaddir = '/home/nicholasabrams/public_html/' + $_POST['lname'] + '/' + $_FILES['userfile']['name']; $uploadfile = $uploaddir . basename($_FILES['userfile']['name']); if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))...
I get filenames with 0pictureNameHere.jpg instead of NAbrams.jpg or if using post data to set the directory, I will never get the image or data in this way.
Side note:
I am a Javascript and jQuery ( <- mainly) developer, would it be worth it for me to attempt doing this with express or some other node module? I am not experienced with node although I have been "using it" for the last few months.
Thanks for the help!

Categories

Resources