Replace / write code in file by Query - javascript

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!

Related

Preventing JavaScript Injection

Say i have a form with which user inputs some information and is submited to server using php and in PHP code i have say
$data = $_POST['data'];
// or
$data = strip_tags(#$_POST['data']);
I want to know of the strip_tags() is enough to stop javascript injection through html forms. If not how else can this be prevented. I have read here.
And also say i input javascript:void(document.bgColor="blue") in the browser address bar, this changes the whole site background color to blue. How can javascript injection through the address bar be prevented.
Thanks.
i suggest to use htmlspecialchars when ever you want to output something to browser
echo htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
checkout this
For question 2, I'm not sure if that's even possible to prevent. It's not something I've ever considered before. It sounds like you're trying to prevent executing any javascript that wasn't included by you on the page, which would also mean blocking the devtools in the browser from executing anything in the console. This could potentially be hostile to your users, e.g. if they wanted to use a bookmarklet from Instapaper.
For 1, ultimately your goal is to avoid including this injected javascript from the form when you generate a new page. When you output the data from the form, you can wrap it in htmlspecialchars.
It's depend which output you are trying to get.
In some cases , you'll want to leave the HTML tags including script tags ,but you want that those elements will not run when you output them, in that case you should use htmlspecialchars($_POST['data']), (It's suggested to define also utf8 as the third parameter).
But if you want to remove entierly the tags than strip_tags will prevent XSS
One function cannot fully protect you from script injection. Consider the following program:
<?php
if(isset($_POST['height']))
$height=htmlspecialchars($_POST['height'], ENT_QUOTES, 'UTF-8');
else $height=200;
if(isset($_POST['width']))
$height=htmlspecialchars($_POST['width'], ENT_QUOTES, 'UTF-8');
else $width=300;
echo("
<!DOCTYPE html>
<html>
<body>
<iframe src='whatever' height=$height width=$width>
</iframe>
</body>
</html>
");
The input is sanitized, but javascript will still be executed through a simple injection vector like:
300 onload=alert(String.fromCharCode(88)+String.fromCharCode(83)+String.fromCharCode(83))
You still need to quote your attributes or you are vulnerable like this example.
Another semi-common injection vector exists when user input is echoed into javascript comments, and you can inject new lines or close the comment. I blame it on the 'this shit doesn't work as it should, but let's keep it around in a comment'-style of development.
Note: The XSS protection of many browsers will not run my simple example. If you want to try it use one without protection, or find a vector that defeats it (not sure if there is one for e.g. Chrome).

Download more then one file at the same time

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.

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.

How can I make a web page show the contents of a file even after I change the file?

Hey everyone I got a wiki question. We store files in *.7z in one server and have a wiki on another. I need to make a script that pulls the file names from one script and adds the code behind it so I can post it in the wiki. We do a ton of files a month and typing them all by hand won't cut it.
Here is what I need.
Var filename or string
For each file in the list {
Filename= File
Write ('<br><file>SERVERNAME\C$\VideosArchive\ '+Filename+ '|' +Filename+ </file> <br/>)
So when the output comes out it has to look like.
<file>\\SERVERNAME\c$\VideoArchive\FILENAME.7z|FILENAME</file>
but i need something that auto generates that if that makes since.
Something like this?
pushd \\servername\C$\VideosArchive
rem by the way, you should make that a share instead of using C$. Plays nicer with privileges and stuff
for %%f in (*) do (
echo ^<br^>^<file^>SERVERNAME\C$\VideosArchive\%%~nxf^|%%~nxf^</file^>^</br^>
rem do I need to ask why you are using "br" as if it had content? It's a tag without content ...
)
popd
Sounds like a very simple task.
You could create an app or PowerShell script to perform the dynamic creation of this file.

Javascript redirect to dynamically created HTML

I have a javascript routine that dynamically creates an HTML page, complete with it's own head and script tags.
If I take the contents of the string and save it to a file, and view the file in a browser, all is well, but if I try document.write(newHTML), it doesn't behave the same. The javascript in the header of the dynamic newHTML is quite complicated, and I cannot include it here... But please believe me that it works great if I save it to a file, but not if I try to replace the current page with it using document.write. What possible pitfalls could be contributing to this that I'm not considering? Do I possibly need to delete the existing script tags in the existing header first? Do I need to manually re-call onLoad??
Again, it works great when the string is saved to, for example, 'sample.html' and browsed to, but if I set var Samp="[REAL HTML HERE]"; and then say document.write(Samp); document.close(); the javascript routines are not executing correctly.
Any hints as to what I could be missing?
Is there another/better way to dynamically replace the content of the page, other than document.write?
Could I somehow redirect to the new page despite the fact that doesn't exist on disk or on a server, but is only in a string in memory? I would hate to have to upload the entire file to my server simply to re-download again it to view it.
How can I, using javascript, replace the current content of the current page with entirely new content including complex client-side javascripting, dynamically, and always get exactly the same result as if I saved the string to the server as an html file and redirected to it?
How can I 'redirect' to an HTML file that only exists as a client-side string?
You can do this:
var win=window.open("") //open new window and write to it
var html = generate_html();
win.document.write(html)
win.document.close();
Maybe eval() function would help here? It's hard to give ansver without seeing the code.
Never tried this, but i think it should be possible. Some thoughts on what might make it work:
Make sure the document containing your js is sent with the correct headers / mimetype / doctype
Serve the javascript in a valid way, for example by sending a w3c valid page containing the script tag.
Maybe then it works. If not, try to erase the current html before writing the new one.
Also, it might be helpful to look how others managed to accomplish this task. If i remind it correctly, the google page is also essentially a short html page with a bunch of js.

Categories