Accessing an unaccessible backwards directory in javaScript - javascript

My server is pointed at localhost/_mainDir/. I need jsFile.js to access phpFile.php, however this is out of reach for jsFile.js.
How can I achieve this? I know that javaScript cannot access directories behind what the server is pointing to; however I do not want to change where my server is pointing due to security reasons.
Here's my directory structure:
projectDir -> _mainDir -> index.php
-> jsDir -> jsFile.js
-> phpFile.php
index.php:
<!DOCTYPE html>
<html>
<head>
<script src="jsDir/jsFile.js"></script>
</head>
</html>
jsFile.js:
$(document).ready(function() {
$.post("../../phpFile.php", {
x: 3
}, function(data) {
alert(data);
})
});

There are a couple of options.
You can setup a Symlink to that php file, as long as your webserver is setup to follow symlinks this would work - with that being said you may as well just move the file which will cause the same security issue you talk about.
You create another PHP file which the js file can communicate with, which then passes arguments to the ../../phpFile.php and handles the response from phpFile.php back to the $.post - that way your not exposing the phpFile.php and only the particular call made from the client side javascript.
Javscript calls from the front end can be somewhat controlled with CSRF tokens
http://bkcore.com/blog/code/nocsrf-php-class.html
This will allow you to include a CSRF token with the javascript call to the new file that proxies the request to phpFile.php
That way A. you know the request is coming from your frontend (CSRF), B. your only exposing what is required to the frontend.
EDIT: change POST, to arguments using $argv[0]

Related

Redirect a specific url that is not found with javascript in header

I moved my website and I have a QR code (which is printed in public and can't be easily replaced) that points to a specific file on my old website that has now been moved. Currently, the URL just points to a "Not found" page on my new website. I try to use javascript in the header to catch the URL and forward it to the right URL as following:
<script type="text/javascript">
if(window.location.href === "https://www.website.com/multimedia/hoerproben/1.mp3")
{
window.location.href = "https://www.webseite.com/app/download/10079133850/1.mp3";
}
</script>
But it doesn't work. Any hints what I am doing wrong?
when you open an url, the browser makes an http request to your server for that particular resource (in your example, an mp3 file).
JavaScript is not involved at all (actually, there are so called "service workers", but they are not what you're looking for, they are meant to do caching, not redirecting). The browser does not know that your JavaScript code exists and would not execute it.
What you should do is route redirecting from server, so when the browser asks from /oldlocation/file.mp3, instead the server answers with /newlocation/file.mp3
This could be in some different way according to your server. If you have no control on how your server works, what you're asking is simply not possibile.
It won't work unless you place that code in the "Not found" page that gets served. If your URL pointed to an HTML file, you could have just placed one to do the redirect. For media files you would have to configure your server to serve an HTML file instead. Don't worry about the extension, it's the Content-Type header that determines the type of the file served. Doing this, however, is not good practice because your server would still be returning a 200 response code.
It's good practice to return 301 Moved Permanently as 101arrowz pointed out in the comments. How that can be accomplished will depend on what server you're using.
Here's how that would have been accomplished with express.js:
app.get('/multimedia/hoerproben/1.mp3', function(req, res) {
res.redirect('/app/download/10079133850/1.mp3');
});

.htaccess rewrite rule to send data to PHP script without revealing location via AJAX

I hope the question didn't confuse you firstly. I'm very picky on security and do not want to have ANY PHP files anywhere in the public_html folder, but on the private area usually before this directory "../public_html". Here's a quick example of my needs, and do believe .htaccess will rescue me (or one of you guys!) with a solution. Inside JS I get data I want to send to PHP. I'm not going to write all the JS code but you'll understand surely. The JS file is located here: c://wamp64/public_html/assets/js/send_ajax.js and index /public_html/index.php
var username = helloWorlder;
/* and all the onreadystate change content here */
xmlhttp.open("POST", "this_is_the_problem_file_name.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("u=" + username);
You see the file I'm POSTing to, I want to have a rewrite condition so it can point to this example C://wamp64/private_area/php/this_file.php. I don't want to do this in the JS script ../../../private_area/this_file.php because that will be TOO much revealing a sensitive directory. To clarify the index page, and of course JS file is public. The PHP file isn't. Surely there's a way. Thanks in advance.
.htaccess and javascript will only be able to communicate with what is publicly accessible by the browser. What you will probably want is an intermediary controller. You can set up a snippet in MODX that loads your hidden PHP files, set up a blank page that calls that snippet, then post your requests to that page and read the responses.
You can't make a request that gets processed by a PHP program unless you give that PHP program a URL.
The easiest way to do that is to put the PHP program under the server root.
You could use alias or mod_rewrite to keep the file elsewhere, but that is largely pointless.
The only benefit that gives you is that in the unlikely event of something going wrong with your server configuration which might leak the source code of the PHP program, then it will likely go sufficiently wrong to break access to it entirely.
You can get the same benefits, without the complexity, by putting the sensitive parts of the program outside the server root and then include()ing them.

External javascript in html is sent incorrectly to the server

I'm running a Node.js server along with an Angular frontend. One of the Angular dependencies I'm using requires me to import a javascript file into my html page, by the name of swing.js. However, when I try to do this, it sends the required file as an http request to the server, resulting in requests that look like the following:
http://localhost:3000/home/me/app/node_modules/angular-swing/dist/swing.js
Obviously, this comes up as a 404. As an alternative, I've tried changing
<script src="/home/me/app/node_modules/angular-swing/dist/swing.js"></script>
into
<script src="swing.js"></script>
and then on the server-side, doing:
app.get('swing.js', function(req, res){
res.sendFile('home/me/app/node_modules/angular-swing/dist/swing.js');
});
This works a little more, but then the file doesn't run properly, as I'm assuming it's no longer in the npm environment it needs to be in. I've tried multiple iterations of changing
<script src="/home/me/app/node_modules/angular-swing/dist/swing.js"></script>
into something that uses periods (.) to represent more relative paths, but that doesn't appear to work either. Overall, I'm very stuck, and would appreciate any insight. If it's of any use, I'm also using:
app.use(express.static(__dirname+'/public'));
Making my comments into an answer...
node.js does not serve any files by default so any script files that you need sent from your server to the client upon request need an explicit route to handle them or they need some generic route that knows how to handle all the requested script files.
swing.js in the client is not part of any "NPM environment". It's running the browser at that point, not in any NPM enviornment. It's possible that swing.js itself needs some other scripts or resources that also need routes and that's why it doesn't work after you make an explicit route for it. You can probably examine the specific errors in the console to give you a clue why it isn't working.
You may also want to read this: How to include scripts located inside the node_modules folder?

Javascript examples found on severial sites regarding fopen is not working for me

I am trying to read a text file that is in the same directory as my html file using javascript so that I might include the contents of the text file in my html file.
Here is the code I have to test the fopen and fread functions
<html>
<head>
</head>
<body>
<script>
fh = fopen('my.txt', 0); // Open the file for reading.
if(fh!=-1) // Check if the file has been successfully opened.
{
length = flength(fh); // Get the length of the file.
str = fread(fh, length); // Read in the entire file.
fclose(fh); // Close the file.
// Display the contents of the file.
write(str);
}
</script>
</body>
</html>
I've tried replacing the 'write' with document.write and still nothing.
Here are some websites that had this code as an example:
http://answers.yahoo.com/question/index?qid=20130519190823AA2lQ1W
http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm
Any help at all would be much appreciated.
Thank you!
Javascript has no filesystem access. As it is mentioned in the second link you posted,
you will need to install special plugins in order to give JS file system access.
I don't think it is the right way to accomplish whatever you are trying to do.
In order to access client's filesystem, the popular way I've seen is using Flash or Java applet or Microsoft Silverlight for that matter.
For accessing your server filesystem, you will need to run a web server which has proper permissions to access the filesystem. Then, you can make AJAX calls to the web server, which in turn will fetch the file for you.
As Apoorv said, JavaScript has no filesystem access. But I think it is important to consider why that is. Or rather, ask yourself, would you go to a website that could access files on your machine?
Functions like fopen is not defined in web browsers. You cannot access file system from javascript. Either have to do something like this: Question
or load your files with ajax
Either way you cannot load file's from viewer's computer, only from your server.
Again either way trying to load from a different server will also result in cross origin related limitations.

External JSON data with offline development

I am developing a web app that accesses some external JSON data. I'm currently using jQuery's getJSON to get the data and call the callback.
My internet at home is terrible, so I'm regularly not connected. I am looking for a way to develop this app while disconnected from the internet.
My initial thought was to have an OFFLINE variable that I set, which changes the location of the scripts to a local file, but because jQuery's getJSON uses dynamically named functions for callbacks, it would need some server intelligence.
More info on how getJSON callbacks work here: http://docs.jquery.com/Ajax/jQuery.getJSON
I'm sure there's an easier way. Any suggestions?
** Edit **
Let me try and clarify a bit
I'm currently running a local web server. I have to - script tags can't reference a local file, for security reasons.
I'm currently calling getJSON with the url: http://twitter.com/status/user_timeline/user.json?callback=?
If I downloaded that json response and hosted it on the local webserver, it wouldn't work, because the callback name will change every time, yet the feed will have the function name it was originally fetched with.
I have a similar problem. Try xampp for an easy php/apache/mysql install on your machine.
I use dreamhost to host my site. I manage everything with a subversion repository, which allows me to simply do 'svn update' on my live site when I am ready to pull in my changes.
I also define all my paths relative to a base_url variable, which is set depending on the http host, so I don't have to change anything for my site to run on different webservers. I use codeigniter, and my config file looks like this:
switch($_SERVER['HTTP_HOST']) {
case "claytonhp":
$config['base_url'] = "http://claytonhp/<project_url>";
break;
// etc.
}
To use that same path in my javascript, I put the following at the top of each html file:
<script type="text/javascript">
siteUrl = '<?= base_url();?>';
</script>
<script type="text/javascript" src="<?= base_url();?>public/scripts/external/jquery/jquery.js"></script>
<!-- Local functionality -->
<script type="text/javascript" src="<?= base_url();?>public/scripts/common.js"></script>
<!-- etc -->
Then, my jquery ajax calls look like this:
$.ajax({
type: "POST",
url: siteUrl + "index.php/ajax_controller/getSomeData",
dataType: "json",
data: "id=5",
success: successCallback,
error: errorCallback
});
Just use a web server (IIS is built into Windows, or use Apache, or XAMP otherwise). That way, you're always connected to your web site (use http://localhost/...).
Quick solution is to just run a local web server. This is a good idea for all sorts of reasons.
If you don't want to do that, just define the URL to get the JSON from somewhere global, and pass it to getJSON(). Just don't forget to set it back before you put your code up on the server.
I used a local sinatra webserver, and replaced the hosts in my /etc/hosts file. It's nice because it's super easy to define new services.
I often forget to reset my hosts file, which can cause a lot of frustration, so I created a script to wrap the whole thing as well.
Here's an example that will serve up a twitter user feed.
run.sh
#!/bin/bash
cp /etc/hosts /etc/hosts.original
cat offline_hosts >> /etc/hosts
ruby server.rb -p 80
cp /etc/hosts.original /etc/hosts
offline_hosts
127.0.0.1 twitter.com
server.rb
#!/usr/bin/ruby
require 'sinatra'
# twitter user
# http://twitter.com/status/user_timeline/$USER.json&callback=?
get '/status/user_timeline/:username.json', :host_name => /twitter\.com/ do
render_file "feeds/#{params[:username]}.json"
end
def render_file filename
output = File.open(filename).read
output = "#{params[:callback]}(#{output});" if params[:callback]
output
end

Categories

Resources