How to delete a file with javascript? - javascript

Did not have luck with these examples:
Javascript File remove
Javascript FSO DeleteFile Method
Deleting a File
There are no special permissions on the file.
Is there a way to do this in JQuery?
The requirement is - a certain file must be deleted from the web directory when another page is loaded. There is no security issue as this is on a closed network.
Any help is appreciated.
Thanks.

With pure JavaScript, it can't be done. Using an AJAX call to a server side script that deletes the file would work though.

Javascript cannot delete files, it is prevented as it would lead to HUGE security vulnerabilities. THose links are for ActiveX controls that are handled through JS. Use a server side language.

You can't delete files over HTTP (well in theory you can, but it's not implemented.)
The easiest way is to set up a tiny server side script (e.g. in ASP or PHP) and to call that from JavaScript. The server side script needs the proper permissions to do the deletion, but otherwise there is no problem.
In PHP the start would look like this: (Not expanding solution to a fully secure one because you're not saying what platform you are on)
<?
// STILL INSECURE!!!!
// Do not use in any public place without authentication.
// Allows deletion of any file within /my/files
// Usage: filename.php?file=filename
$basedir = "/my/files";
$file_to_delete = $_REQUEST["file"];
$path = realpath($basedir."/".$file_to_delete);
if (substr($path, 0, strlen($basedir)) != $basedir)
die ("Access denied");
unlink($path);
?>
you would call the script like this:
http://yourserver/directory/delete_file.php?file=directory/filename

You cannot delete a file on a remote server using only JavaScript running in a visitor's browser. This must be done with a server-side script.

If you are doing this in a RESTFUL way, you would send an HTTP DELETE request.
jQuery's ajax method states that you can use the method parameter to specify 'DELETE' but notes that some browsers may not support it.
Obviously you will need a webserver which will accept a DELETE request, and apply some sort of authentication/authorization so that joe random visitor can't delete your files. I believe Apache's mod_dav will get you started here.

Javascript is a client side language. So you are not able to delete file on server directly. All examples that you provide may be used only for deleting files on your local machine but not into server.
But you may call some server page function that will delete file.

You can't delete files with JavaScript as it is run locally. So, it doesn't even touch external files.
You need to use a server side language that has access to editing the files such as PHP, RoR, or ASP.
You can however use jQuery to call the server side code via AJAX such as $.get or $.post and then the server side code deletes it and it would seem as though JS is deleting the files.

Related

How i can use PHP Session in React?

I have a question of session PHP in React. I have to create an online shop in React and PHP. I currently programming a shopping cart. To do this, I have to use PHP Session. I can't use JWT, so my questions are:
How to start a Session if I can't include PHP code in index.html (react-create-app, MVC, I can't include start_session() at the beginning of the page)
How to retrieve data from Session (is it possible by ajax?)
I have never used PHP and React. So far I have only used restful API.
Please help.
Yes i think you can. Check this question and the most voted answer:
The answer is yes:
Sessions are maintained server-side. As far as the server is concerned, there is no difference between an AJAX request and a regular page request. They are both HTTP requests, and they both contain cookie information in the header in the same way.
From the client side, the same cookies will always be sent to the server whether it's a regular request or an AJAX request. The Javascript code does not need to do anything special or even to be aware of this happening, it just works the same as it does with regular requests.
Do AJAX requests retain PHP Session info?
What you can do is initialize a Javascript variable with your PHP variable. This is possible because PHP, a server-side language executes on the page before Javascript, so it's almost like entering plain text where the right-hand side of the JS line is.
An example would be something like this in your index.html file:
index.php (you must rename your index.html file to index.php so the computer knows there's some PHP in there). Also, must ensure PHP is installed in your local environment hosting this. Something like npm install PHP, brew install PHP, or yum install PHP will do.
<script>
// Note here: we must ensure name is set,
// otherwise it would look something like
// let name = ;
// this would cause an error
// that is why I check the value is present with isset()
let name = <? echo isset($name) ? $name : "Air"; ?>;
</script>
Therefore, I think you would just need to ensure your environment supports PHP. You can also use a subroutine/webservice/ajax call to do the same; however, this is a little bit more complex in regards to its setup.

Create folder in web server javascript

I'm looking to dynamically create folders in my web server using JavaScript. After doing some research, I've found that this isn't usually accomplished without a server side extension like Node.js, but I was wondering if their were any APIs out their that would provide something like this.
I heard that ASP might be a good idea too, so I might give that a try, but I'd like to know from you guys.
Basically to give you an idea of what I am looking to achieve.
When I have a user visit my page, a random number is generated and stored in a variable, let's say: 1234
I want to create a folder in my webserver called users and within that folder, create a 1234.html content-filled file.
Web Server
------users\1234.html
Thanks
If you are using PHP then you can send request to server and php script does the rest
function makedirs($dirpath, $mode=0777) {
return is_dir($dirpath) || mkdir($dirpath, $mode, true);
}
I have copied this function..

Is it possible to use inject $.post() from address bar?

I have a javascript in which I use $.post() command to post variables to a php file, I have the URL of the php file hardcoded in the same .js file.
I just want to know if it's possible for someone to inject $.post() command from address bar and send invalid data to the PHP file?
if yes, how to prevent or how to detect those invalid data?
Yes, anybody who knows how to code in JavaScript could send an AJAX POST request to your PHP file.
As for how to detect the invalid data, that depends entirely on what makes the data invalid. You'll simply need to check the POST values against whatever criteria you're expecting valid data to meet, and then ignore any requests that don't meet those criteria.
Yes, it's very simple. Attacker can modify, add or remove any JavaScript running in the browser, modify DOM, etc. Tools like Firebug allow anyone to call arbitrary JavaScript from the console. Moreover one can simply use curl to run your server and send arbitrary data.
if yes, how to prevent or how to detect those invalid data?
You must ensure data validity and integrity on the server side. Also you might want to add some security on the server side and do not depend on some JavaScript function being "hidden".
Sure, by prepending the script with the javascript: scheme you can do pretty much anything you want to a site:
javascript:$.post(/* stuff here */)
You should always validate your incoming data on the server side, because not only may someone use the javascript on your site to do this, but they may use other tools, like curl or whatever else that will let you make http requests.

With JS, jQuery, how do I save an AJAX response to a (text) file?

It seems like this question is asked periodically and the common response is "You shouldn't do that with AJAX anyway. Just set the window location to the file."
But I'm trying to request a file that doesn't actually exist out on the server anywhere. It's dynamically generated (by a Django view) given the GET/POST context parameters. The file I want to retrieve via AJAX, and then save to the client machine, is a text file (csv).
I can currently get the text to the client machine (and can verify this by seeing it in logging or an alert) but cannot then figure out how to save this text to a file inside of the AJAX success callback fn.
Essentially, is this possible, is it something JS can do? That is, to open file save dialogs for "files" that are actually AJAX response text?
From the browser's point of view, it doesn't matter if the file exists or not, it's just a resource on a server that it's requesting. I think you're going to need to do some version of "Just set the window location to the file". If you set the content type in the header to something that the browser doesn't recognize, I believe it will ask the user if they want to save it.
As others mentioned, you can't do it only with JavaScript.
IMO the best option would be the Flash 10+ FileReference API.
There are some good JavaScript wrapper libraries like Downloadify that provide a JavaScript API to access those methods.
Give a look to this demo.
This isn't something JavaScript (and therefore jQuery or anything other JS framework) is allowed to do, for security reasons. You may be able to do what you want to flash or another route, but not JavaScript. Bear in mind Flash has it's own slew of security restrictions for this as well.
(Yes, IE can do this via an ActiveX object, but I'm not counting that as a "solution" here)
Basically, no. Javascript cant save anything to the local machine due to security restrictions. Your best bet may be to have a signed applet that the user can trust to write the file, or put it in a textarea that they can then easily copy and paste into a new file.
Could you not use the PHP rename() function for this, instead of just Javascript? Call to a PHP file and pass the name of the file you want to copy along with where as parameters?
I have the same problem. You can try this
<button id="Save">Save</button>
<img src="MakeThumbnail.ashx?Image=1.jpg" id="imgCrop">
$("#Save").click(function (e) {
url = $("#imgCrop").attr("src")+"&Action=Save"
e.preventDefault(); //stop the browser from following
window.location.href = url;
});

How far can I go with JavaScript?

I need to do as much as possible on the client side. In more details, I would like to use JavaScript to code an interface (which displays information to the user and which accepts and processes response from the user). I would like to use the web serve just to take a date file from there and then to send a modified data file back. In this respect I would like to know if the following is possible in JavaScript:
Can JavaScript read content of a external web page? In other words, on my local machine I run JavaScript which reads content of a given web page.
Can JavaScript process values filled in a HTML form? In other words, I use HTML and JavaScript to generate an HTML form. User is supposed to fill in the form and press a "Submit" button. Then data should be sent to the original HTML file (not to a web server). Then this data should be processed by JavaScript.
In the very end JavaScript will generate a local data-file and I want to send this file to a PHP web server. Can I do it with JavaScript?
Can I initiate an execution of a local program from JavaScript. To be more specific, the local program is written in Python.
I will appreciate any comments and answers.
It could technically, but can't in reality due to the same origin policy. This applies to both reading and writing external content. The best you can do is load an iframe with a different domain's page in it - but you can't access it programmatically. You can work around this in IE, see Andy E's answer.
Yes for the first part, mmmm not really for the second part - you can submit a form to a HTML page and read GET arguments using Javascript, but it's very limited (recommended maximum size of data around 1024 bytes). You should probably have all the intelligence on one page.
You can generate a file locally for the user to download using Downloadify. Generating a file and uploading it to a server won't be possible without user interaction. Generating data and sending it to a server as POST data should be possible, though.
This is very, very difficult. Due to security restrictions, in most browsers, it's mostly not possible without installing an extension or similar. Your best bet might be Internet Explorer's proprietary scripting languages (WScript, VBScript) in conjuction with the "security zones" model but I doubt whether the execution of local files is possible even there nowadays.
Using Internet Explorer with a local file, you can do some of what you're trying to do:
It's true that pages are limited by the same origin policy (see Pekka's link). But this can be worked around in IE using the WinHttpRequest COM interface.
As Pekka mentioned, the best you can manage is GET requests (using window.location.search). POST request variables are completely unobtainable.
You can use the COM interface for FileSystemObject to read & write local text files.
You can use the WScript.Shell interface's Exec method to execute a local program.
So just about everything you asked is attainable, if you're willing to use Internet Explorer. The COM interfaces will require explicit permission to run (a la the yellow alert bar that appears). You could also look at creating a Windows Desktop Gadget (Vista or Win 7) or a HTML Application (HTA) to achieve your goal.
Failing all that, turn your computer into a real server using XAMPP and write your pages in PHP.
see i got what you want to do
best things is do following
choose a javascript library (eg:jquery,dojo,yui etc), i use jquery.this will decrease some of your load
inspite of saving forms data in in a local file, store them in local variables process them and send them to server (for further processing like adding/updating database etc) using XMLHttp request, and when webservice returns data process that data and update dom.
i am showing you a sample
--this is dom
Name:<input type='text' id='name' />
<a href='javascript:void(0)' onClick='submit()'>Submit Form</a>
<br>
<div id='target'></div>
--this is js
function submit()
{
var _name=$('#name').val();// collect text box's data
//now validate it or do any thing you want
callWebservice(_name,_suc,_err);
//above call service fn has to be created by you where you send this data
//this function automatically do xmlHttprequest etc for you
//you have to create it ur self
}
//call this fn when data is sucessfully returned from server
function _suc(data)
{
//webservice has returned data sucessefully
//data= data from server, may be in this case= "Hello user Name"; (name = filled in input box);
//update this data in target div(manipulate dom with new data);
$('#target').html(data);
}
function _err()
{
//call this fn when error occurs on server
}
// in reality most of the work is done using json. i have shown u the basic idea of how to use js to manipulate dom and call servcies and do rest things. this way we avoid page-reloads and new data is visible to viewer
I would answer saying there's a lot you can do, but then in the comment to the OP, you say "I would like to program a group game."
And so, my answer becomes only do on the client side what you are able and willing to double check on the server side. Never Trust the Client!
And I do not want to do my job twice.
If you are going to do things on the client side, you will have to do it twice, or else be subject to rampant cheating.
We had the same question when we started our project.In the end we moved everything we could on the JS side. Here's our stack:
The backend receives and send JSON data exclusively.We use Erlang, but Python would be the same. It handles the authentication/security and the storage.
The frontend, is in HTML+CSS for visual elements and JS for the logic.A JS template engine converts the JSON into HTML. We've built PURE, but there are plenty of others available. MVC can be an overkill on the browser side, but IMO using a template engine is the least separation you can do.
The response time is amazing. Once the page and the JS/CSS are loaded(fresh or from the cache), only the data cross the network for each request.

Categories