Javascript .load doesn't see PHP's variables - javascript

I'm using the following script to load content on the page without refreshing it. The pages that I load this way should not be accessible as stand alone pages.
<script>
$(".toLoad").click( function(event)
{
event.preventDefault();
$("#page-wrapper").load($(this).attr("href"));
});
</script>
I have this in my index.php
define('SECURE', true);
and this in the other files
!defined('SECURE') and exit("Not allowed");
This system works very well with PHP's include or require functions but it blocks me from loading the pages from my index.php using the given javascript. What's the workaround or how could I restrict the direct access but allow it trough javascript on my main page?
Thanks!

define declares a constant, which is accessible during the script operation (only to php which means only on server).
It is not a variable
It does not persist between page loads (so when You hit another php file, this is not defined).
As for disallowing hotlinking - You can check HTTP Referer for instance, but it can be fooled.

Make a php-proxy thingy.. Then you .load('jsproxy.php?url=' + $(this).attr('href'));
I don't know php very much, but you should just define secure, and include the page in the url...

You cannot send your secure variable from index page to next page and session should not be used for this purpose as it will allow direct access as session always enable on request of index page. But you can check request is xmlhttp (ajax) request or not from server with following function as load() function request with HTTP_X_REQUESTED_WITH header with 'xmlhttprequest'.
function isAjax(){
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
if(!isAjax())
{
echo "no direct access"; exit(0);
}

Related

javascript display forms from remote url

I have dynamic forms in my urls .i want to write a javascript such that when the users paste that javascript in their web pages the form should dispay.
<script type="text/javascript">
window.location.href = "http://myserver/2a249ccf59e272abb8e7b8582560a45c"
</script>
The problem is using the above code , The url redirects.I want to avoid redirection
I'v tried iframes , but i dont want to use them as per requirements .
You need to use AJAX to fetch a remote page. You must get the page from the same server that your webpage was delivered from to avoid same origin policy issues.
I would recommend using a library to handle AJAX requests. jQuery has AJAX functions built in, but you could use others also. With jQuery...
// be sure to include jQuery library in the head of your document...
// general wrapper to execute code only after all page elements have loaded
$(function(){
$.get("http://myserver/2a249ccf59e272abb8e7b8582560a45c",function(data,status){
// put the fetched data (your html form) at the end of the existing body content
// you could put it somewhere else by changing the `body` selector
$("body").append(data)
})
})

Get HTML of URL without XMLHttpRequest

thanks for reading. I'm trying to come up with a Javascript function that would convert the HTML source of a page at an external URL into a variable, so that the whole thing would become editable. The complication is, the URL does not end with a "html, htm, aspx" extension, but instead with a string of input form variables (i.e. ?type=AAA&color=BBB...). Hence the XMLHttpRequest method is out of the question.
Is this doable in JS/jQuery at all? I've heard about the same origin policy, but the following tool manages to do just that, although in PHP: http://www.iwebtool.com/code_viewer
Same origin policy does apply in this case, however you can do it with a combination of server side code (PHP) and jQuery. Heres a little example.
PHP
<?php
$url = $_REQUEST['url'];
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,$url);
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
echo($buffer);
?>
jQuery / HTML
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "yourPhpScript.php",
data: "url=http://stackoverflow.com"
}).done(function( content ) {
$('#content').html(content);
//content is your variable containing the source
});
</script>
<div id="content"></div>
XMLHttpRequest works with any valid url, just give it the appropriate url and you can get the response as text.
However, there is the restriction of the same-origin policy. There are different workarounds to this for different situations, but if you want to be able to manipulate the text you receive then there is really only one option. Use the same javascript as you currently have, just add this as the first line of getUrl:
url='/path/to/proxy.php?url='+encodeURIComponent(url);
Then, on your server (the same one that's serving the page and its javascript), write proxy.php:
<?php
echo file_get_contents($_GET['url']);
?>
This will make every ajax request you make go to your server, which does not have the restriction of loading from only one domain. The server will load the url you asked for, and reply to you with the response it got from the page it loaded. Note that the above script will only give you the content body (what you see when you view-source) - if you need to access HTTP headers you can relay those too, it will just be more complicated.

Javascript widget works fine on my own domain, but not on anyone elses?

Created javascript widget. Testing on my own domain and its working fine. However when posting on a 3rd party site it looks like it's not connecting to the database and getting the data.
Here is the part of the js file where I get the data:
/******* Load HTML *******/
var jsonp_url = "http://www.example.com/widget/data.php";
$.getJSON(jsonp_url, function(data) {
When I test on example.com everything is fine. I set the permissions on data.php to 777 and it still isn't working. Please help!
you cannot make an ajax call across different domains:
let's say your domain is 'example.com', and the third party site has 'thirdparty.com'. you install the widget on thirdparty.com. The widget code on thirdparty.com will try to make an ajax request to 'example.com'. Which is forbidden by the browser.
You can always replace the ajax call with a straight < script > tag. This doesn't have any restriction.
Hope it helps
You have a variable called jsonp_url, but the URL you use doesn't include the string callback=? which the documentation says triggers jsonp mode.
You need to include that in the URL and make sure that your server side script is outputting JSONP (using $_GET['callback'] (with suitable sanitisation) to determine the function name you wrap the JSON in).
they need to enable cross orgin resource sharing. http://enable-cors.org/

Can I load data from an external page via AJAX?

I've just starting learning jQuery and AJAX. I'm able to load a local page (on my disk) into a div via jQuery.load(), but external sites don't seem to work. I've even used wireshark to check if the data is being sent from the server (it is). Sample code is below:
<html>
<head>
<script src='jquery-1.4.2.min.js'></script>
<script>
$(document).ready(function() {
// $('#test').load('localpage.htm'); works!
$('#test').load('http://www.google.com/'); // does not work!
});
</script>
</head>
<body>
<div id='test'></div>
</body>
</html>
Is it possible to do this in the first place? If so, how?
You cannot do ajax calls to a different domain than the script originates from.
For doing such a thing, you have to use a proxy page on your own page, eg:
<script>
$(document).ready(function() {
$('#test').load('ajax/getgoogle.php');
});
</script>
getgoogle.php:
<?php
echo file_get_contents("http://www.google.com/");
?>
Out of the box: no. It's a security issue. There are a few different workarounds though.
You're running into the Same Origin Policy. You can't access data from an external domain using AJAX, it's considered a security risk. The reasoning behind it is that AJAX requests work with cookies stored by the browser -- if I tried to access facebook.com, and you were logged in there, the cookie would be sent and I'd have access to your personal data.
For security reasons, you cannot use AJAX to request a page from a different domain (or protocol or port).
Instead, you can write a server-side script on your server to forward requests to another domain. (This is not possible if you're running a page from a file:// url)
Ajax? Yes. XHR? No (unless the browser implements Cross-site XHR which isn't widespread yet).
To get the data with Ajax without using XHR the external site must provide the data in the JSONP format.
Alternatively, you can proxy the data through a server side script on your server, thus making it come from the same host (as far as JavaScript is concerned).
No, it's not. Have a look at Same Origin Policy. The site you are trying to request would need to have JSONP enabled for that to work, and you would utilize a cross-domain callback. Alternatively, you could create a proxy on your own domain which grabs the page on behalf of your ajax request.
Load this PHP script instead of trying to load website directly
$filename = "http://www.sitename.com";
$handle = fopen($filename, "r");
if ($handle)
{
while (!feof($handle))
{
$text .= fread($handle, 128);
}
fclose($handle);
}
print $text;
Edit: Or simply like henchman's solution with file_get_contents
You can't call Ajax from another domain. Check JSON technique for this

starting file download with JavaScript

Let's say I have download links for files on my site.
When clicked these links send an AJAX request to the server which returns the URL with the location of the file.
What I want to do is direct the browser to download the file when the response gets back. Is there a portable way to do this?
We do it that way:
First add this script.
<script type="text/javascript">
function populateIframe(id,path)
{
var ifrm = document.getElementById(id);
ifrm.src = "download.php?path="+path;
}
</script>
Place this where you want the download button(here we use just a link):
<iframe id="frame1" style="display:none"></iframe>
download
The file 'download.php' (needs to be put on your server) simply contains:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So when you click the link, the hidden iframe then gets/opens the sourcefile 'download.php'. With the path as get parameter.
We think this is the best solution!
It should be noted that the PHP part of this solution is a simple demonstration and potentially very, very insecure. It allows the user to download any file, not just a pre-defined set. That means they could download parts of the source code of the site itself, possibly containing API credentials etc.
I have created an open source jQuery File Download plugin (Demo with examples) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:
User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications
Tested cross browser support (including mobile!)
It supports POST and GET requests in a manner similar to jQuery's AJAX API
successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation
In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this.
Just call window.location.href = new_url from your javascript and it will redirect the browser to that URL as it the user had typed that into the address bar
Reading the answers - including the accepted one I'd like to point out the security implications of passing a path directly to readfile via GET.
It may seem obvious to some but some may simply copy/paste this code:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So what happens if I pass something like '/path/to/fileWithSecrets' to this script?
The given script will happily send any file the webserver-user has access to.
Please refer to this discussion for information how to prevent this: How do I make sure a file path is within a given subdirectory?
If this is your own server application then i suggest using the following header
Content-disposition: attachment; filename=fname.ext
This will force any browser to download the file and not render it in the browser window.
Try this lib https://github.com/PixelsCommander/Download-File-JS it`s more modern than all solutions described before because uses "download" attribute and combination of methods to bring best possible experience.
Explained here - http://pixelscommander.com/en/javascript/javascript-file-downliading-ignore-content-type/
Seems to be ideal piece of code for starting downloading in JavaScript.
A agree with the methods mentioned by maxnk, however you may want to reconsider trying to automatically force the browser to download the URL. It may work fine for binary files but for other types of files (text, PDF, images, video), the browser may want to render it in the window (or IFRAME) rather than saving to disk.
If you really do need to make an Ajax call to get the final download links, what about using DHTML to dynamically write out the download link (from the ajax response) into the page? That way the user could either click on it to download (if binary) or view in their browser - or select "Save As" on the link to save to disk. It's an extra click, but the user has more control.
To get around the security flaw in the top-voted answer, you can set the iframe src directly to the file you want (instead of an intermediate php file) and set the header information in an .htaccess file:
<Files *.apk>
ForceType application/force-download
Header set Content-Disposition attachment
Header set Content-Type application/vnd.android.package-archive
Header set Content-Transfer-Encoding binary
</Files>
I suggest to make an invisible iframe on the page and set it's src to url that you've received from the server - download will start without page reloading.
Or you can just set the current document.location.href to received url address. But that's can cause for user to see an error if the requested document actually does not exists.
In relation to the top answer I have a possible solution to the security risk.
<?php
if(isset($_GET['path'])){
if(in_array($_GET['path'], glob("*/*.*"))){
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
}
}
?>
Using the glob() function (I tested the download file in a path one folder up from the file to be downloaded) I was able to make a quick array of files that are "allowed" to be downloaded and checked the passed path against it. Not only does this insure that the file being grabbed isn't something sensitive but also checks on the files existence at the same time.
~Note: Javascript / HTML~
HTML:
<iframe id="download" style="display:none"></iframe>
and
<input type="submit" value="Download" onclick="ChangeSource('document_path');return false;">
JavaScript:
<script type="text/javascript">
<!--
function ChangeSource(path){
document.getElementByID('download').src = 'path_to_php?path=' + document_path;
}
-->
</script>
I'd suggest window.open() to open a popup window. If it's a download, there will be no window and you will get your file. If there is a 404 or something, the user will see it in a new window (hence, their work will not be bothered, but they will still get an error message).
Why are you making server side stuff when all you need is to redirect browser to different window.location.href?
Here is code that parses ?file= QueryString (taken from this question) and redirects user to that address in 1 second (works for me even on Android browsers):
<script type="text/javascript">
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
(window.onload = function() {
var path = urlParams["file"];
setTimeout(function() { document.location.href = path; }, 1000);
});
</script>
If you have jQuery in your project definitely remove those window.onpopstate & window.onload handlers and do everything in $(document).ready(function () { } );

Categories