Download more then one file at the same time - javascript

I have a button and if I click on that button then there are more than one html file store in folder should be show matched with database.
My code are:
<?php
include("connection.php");
extract($_REQUEST);
$query=mysql_query("select * from fad_record where t_id='$word'") or die(mysql_error());
while($result=mysql_fetch_array($query))
{
extract($result);
ob_start();
include("3_day_notice_fad/$fad_html_name");
$html_content = ob_get_contents();
ob_end_clean();
echo $html_content;
}
?>
But when code runs then all files are showing in one file. But I want all different file open in different tab.

This cannot be done using only PHP, opening tabs is a browser option so you need a client side script. jQuery can do that. You should start by creating an ajax call to the PHP and open the result in a new tab. Although, users with spam blockers or with a high-security setting will block that. I would advise against such a feature and find a better way to do this. Perhaps use the jquery UI tab system?
https://jqueryui.com/tabs/
Take a look at it and see if you can use that in your logic
Convert HTML to PDF
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

Related

How to pass a string with special characters in php so I can display it on page

I have an index (fscrawler) of pdfs, docs and spreadsheets. I wrote a php script to search the index and display the contents of the documents (opens up in a modal). Below is the code to open the modal with the documents details. However I am unable to view the documents,
I would like to preserver the documents original format(indentations and bolds). kindly advice.
<button type="button" onclick="searchDetails('<?php echo $r['_source']['file']['filename']; ?>',
'<?php header('Content-Type: text/html; charset=UTF-8');
echo htmlentities( $r['_source']['content']); ?>',
'<?php echo addslashes($r['_source']['path']['real']); ?>',
'<?php echo $q ?>')"
class="btn btn-info btn-sm openBtn" data-toggle="modal" > Details </button>
Catching the syntax errors in the browser console is a good first step. Next, look at the source of the rendered page. As a PHP developer, your job is to output valid html, css, and in your case JavaScript to get your page to render. When you get a Syntax Error in the console, that means JavaScript. It runs browser side so it has to be debugged in the browser.
What you're trying to do here is write out a JavaScript invocation of the JavaScript searchDetails() function. But what are you hoping to accomplish with the php header call? I dont know what searchDetails does, but header applies to the page php is rendering. It wouldn't apply to the file content. You can have a Content-Type header for the webpage, but you can't put a header in a JavaScript string. You can put the string value of a header in JavaScript but that won't actually describe the content-type of anything to the browser.
I suppose htmlentities might be sufficient to expose the content of your files, but pdfs, docs, and spreadsheets are going to look very funky that way. not sure exactly what you want it to look like, but you're probably going to want to serve the content of these files with distinct http requests so they can have distinct headers (esp Content-Type). I can't make sense of how htmlentities(spreadsheet_content) would be a valuable string to display.
Generally speaking, rendering JavaScript from php (or any templating thing) is a pattern I suggest you avoid. Write static JavaScript and have a clear mechanism to expose data to JavaScript. It's fraught with difficulties, including being very difficult to write (quoting and escaping for js, php, html all in the same code ) and debug (eg your syntax error), and often fails to be robust in the face of further development.
I would probably generate a json file that described the file data and then would read that through JavaScript and render the page from it with a js library, probably Vue.js. As I mentioned I would build a separate php resource for serving the file content so I could add a ContentType header on that. If you do this, make absolutely sure you're not serving files outside of your index. It might be wise to request files from their position in the index if possible rather than by path to avoid requests exposing eg /etc/shadow.
If you want to make webpages think of that as primarily JavaScript centered development. Use PHP to generate data but try to keep your HTML and JS as static as possible. Choose a JavaScript library - do not fall into the trap of thinking raw js is "simpler" or "more straightforward"; it's not. If you don't have a preference I recommend Vue but Angular, React, even d3.js would all work here. Your data contracts will be more explicit and you'll be able to develop the backend and the frontend in isolation, providing some confidence that the backend works as you hack out JavaScript end. This might seem like a big complication to break things out this way, but if you give it a try, I think you'll experience pretty quickly how much easier it is.

Replace / write code in file by Query

Maybe a stupid question but it is possible to write a form sort of thing that you can fill in which either writes or replaces the code in the file?
For example I have a result table with possible results. Instead of using either a database or replace the code in my file manually I'd like to write a form which changes the code for me when I fill it in. Sort of like a database but then just in the file itself.
Is this possible?
Wit kind regards
Simple answer: Yes, it is possible, but not recommended.
Elaborating the answer: The reason it is not recommended is because you are opening your doors to hackers that could use XSS (Cross Site Scripting) attacks, unmasking your site, or many other possibilities.
If however you are just curious on how you would modify the code from a form, you can do it as follows.
$new_code = $_POST['newcode'];
$myFile = fopen('table.html', 'w');
fwrite($myFile, $new_code);
fclose($myFile);
A file called table.html would then be created in the same location as the page that is running the previous code. If you want to place the file in another page, you could just add a relative or absolute path to the name, for instance:
$myFile = fopen('../folderA/table.html', 'w');
$_POST is a php superglobal. It is very often used in forms, and if you aren't sure how to use it, there are many great tutorials online.
If you wanted a php file, the code would be the same, except you would change the name of the file from table.html to table.php.
Let me know if that helped!

Website design strategy: Change content or load different HTMLs

So this is kind of my first attempt at web design per se so it might be a newbie-ish question. Just to give a little background... I'm using the all time classic HTML + JS + CSS combo and Yii (PHP) as a backend with a MySQL database. I can't really tell what the site is about but the user will definitely interact with the backend and run some queries on the DB and stuff.
Right now my website is composed of 5 HTML files, each one of them has a common layout:
Header or menu with logo and user info
"Sub-Header" with a general info image and maybe some specific stuff
Content specific to that HTML file
Footer
Right now I find kinda annoying that each time I redirect the user to a different place of my site I have to check again if he's logged in, I make some use of cookies for that too, etc, etc.
I was thinking of moving my site to be a single page or template if you will and just append the (body)content of each of those files to the body of my master-page. That sounds pretty good at first thought, but are there any downsides to this or is this just how things should be done?
I've done web applications before using frameworks like Sencha and stuff and they all seem to work this way, but is this the way to go for this particular case?
EDIT
Also, what is the correct way to implement the single-page scenario?
Get all the code in one HTML file and hide the stuff I don't want to show
Remove from the view the stuff I want to hide and append the new stuff from some other HTML file.
I'm not sure I understand your situation exactly. But I think I would make another PHP file in a protected area with a function like is_logged_in() or even redirect_if_not_logged_in(). Then you can include (or require) that PHP file in the other ones and just call the function.
You definitely don't want to be rewriting the same code over and over again.

What is the best practice for the multiple use of the same link?

I'm trying to rationalize a website, and I have many links on it to the same document, so I want to create a JavaScript that return the URL of this document. This way, i could update the document and only have to change the URL in the function, not in all the occurrences of the link (it's a professional and internal website, with many links to official documents, that get updated often, out of my control, and each time i get to update links, i realize a while after that i forgot some, even by searching in all html files. the site is messy, was poorly written by many people, and that's why i'm trying to simplify)
My first idea was to use link, but everyone says it's a bad practice. i still don't see why, and I don't like to use the onclick as it doesn't work with middle click, and i want to let users decide how they open the doc.
Also, I want to use link to redirect to a specific page.
on top of this, what i tried so far is not working like I intend, so i would need some help, whether to come up with a better solution, or to make this work!
here is my js, with different versions:
function F_link_PDF() {
// i was pretty sure this would work
return "http://www.example.com/presentation.pdf" ;
}
function F_link_PDF_2() {
document.write("http://www.example.com/presentation.pdf");
}
function F_link_PDF_3() {
// i don't like this solution, as it doesn't open as user intended to
location.href = "http://www.example.com/presentation.pdf" ;
}
this example is for a pdf document, but i could also need this for html, doc, ppt...
and finally, i started with js because i'm used to, but I could also use other languages, php, asp, if someone says it's a better option
thanks in advance!
The hack way: Go about using JavaScript, however you run into potential issues with browsers not running it.
The better way: Use mod_rewrite / .htaccess to redirect previous (expired) requests to the new location of the resource. You could also use FallbackResource and provide a .php file that could provide the new resource based on criteria (you now have the power of PHP to decide where the Location header should go).
The best way1: Place those document references in a database table somewhere and reference them in the page using the table's current value. This creates a single place of "truth" and allows you to update the site from a global perspective. You could also, at a later date, provide search, tag, display a list, etc.
1 Not implying it's the abosolute best, but it is certainly a better way than updating hard-coded references.
A server side programming language like php is a better option.
Here's example code that helps:
<?php
$link="http://www.example.com/files/document.pdf";
if ($_GET['PAGE'] == "downloads")
{
?>
This is a download page where you can download our flyer.
<?php
echo "Download PDF";
}
if ($_GET['PAGE'] == "specials")
{
?>
This is our store specials page. check them out. a link to the flyer is below.
<?php
echo "Download PDF";
}
?>
The code isn't 100% perfect since some text needs adjusting but what it does is it takes a parameter PAGE and sees that it is "downloads" or "specials" and if it is, it loads the appropriate page and adds the link to the download file. If you try both pages, the link to the download is exactly the same.
If the above php script is saved as index.php, then you can call each page with:
index.php?PAGE=specials for the specials page
index.php?PAGE=downloads for the download page
Once that works, then you can add another "if" section for another page to create but the most important line in each section is the last line of...
echo "Download PDF";
...because it's taking a variable thats usable in every case in the script.
An advantage with using server side method is that people can view the site even with javascript disabled.

Display actual file size next to a hyperlink of a document or download

I've always been required show download size next to the file hyperlink. Only the file in question is rebuilt everyday and the file size can change often. So needless to say the size has been wrong for months. I'm not going to update our site daily to display needless info.
instead of
click here to download (20mb)
I'd prefer
click here to download [sizeof('file.xxx')]
The best solution would be javascript based or similar.
Since the file is on the server the solution would be best using ASP.NET. This blog post shows how to find the size of a file on the server. You may be able to adapt it to your needs.
javascript isn't really the best language to query the file system. There are ways to do it but they are all very hacky and you should stay away from them.
You can get the file size dynamically using server side code though :
long fileSize = (new FileInfo(# ".\file")).Length;
So in your markup, you could have something like :
<asp:Hyperlink runat="server" ID="hyperlinkFile" ...>
In your code behind, set it properly :
this.hyperlinkFile.Text = "Click here to download" + fileSize.ToString();
Use XMLHttpRequest to send a HEAD to the file and parse the HTTP Header that you get back, looking for the Content-Length field.
Something like:
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
if(this.readyState == 2) {
alert(client.getResponseHeader("Content-Length"));
}
}
client.open("HEAD", address);
client.send();
More information here:
http://ajaxpatterns.org/XMLHttpRequest_Call
The final solution will be a mix between server code (asp.net) and client code (js).
You can build a REST service, that based on the file name or path, returns the size.
You can implement a js function that updates the inner text of every with the result of the REST service call.
Do something like this
click here to download (<%= C# or VB code for file size %>)
Inside the <%= %> tag you can put C# or VB code to find the file size. The server will evaluate it and then put the result where that tag is.
Just create a column name 'FileSize' in your database and fill it with asp.net after your upload has finished. This makes sure you won't overload your server too much.
[edit]Sorry didnt see your file size changes every day[/edit]
In that case you could write a little FileSystem Watcher and let it run in the background on your server or you could just get the filesize by checking the FileSystem info, way easier.
I thought about this more...I read all your answers, then clicked on some links to download various files from other websites. The browser tells me the size after I click 'download' in the dialog box.
I'm going to change the mind set that it is even necessary to include in the link.
Our site has so many pointless...('well other sites have this feature')...and the person I replaced didn't realize or care he that those other sites were built with a CMS that does all that automatically. Example: He was hard coding at the bottom of each page 'last updated: 01/01/1900' every time he saved the document.
edit:
I don't like the way I phrased this answer the other day. I realized that it is unnecessary to include the file size in the hyperlink, when all the major browsers will indicate the file size once you click 'download'. Like in my example above, there are so many instances I can find where the developer or webmaster before me added additional work for themselves by including "features" like filesizes/timestamps/etc... In my opinion adding features like that have/are:
No ROI
Likely to always be wrong
Required to have constant maintenance
Cheap way to make your site look "dynamic"
The last thing you do

Categories