Hi anyone please help me. I writted on php simple code test.php. I am just reading cookie only and displaying it. when i execute the below url in chrome browser i am get response
https://www.domainname.com/cbscheck/test.php
response
testa3433^| 1^|1^|0da1d48927ec9118d271cc6a4f0df3e90ee4d296^|1
same php url i called in below html file using xmlhttprequest but i am not getting the above reponse.
file:///G:/Hari/MyTaks/Chat/chatCheck.html
response i am getting empty.
My perception $_COOKIE not working when i called using xmlhttprequest. please any help me how to resolve it. i shared code below
testCheck.htm
<html>
<body>
<div id = 'onlineUsers' class='bottomDiv'>
</div>
<script>
var url = 'https://www.somedomain.com/cbscheck/test.php';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("onlineUsers").innerHTML = this.responseText;
}
};
xhttp.open("GET", url , true);
xhttp.send();
</script>
</body>
</html>
test.php
<?php
echo $_COOKIE["loginInfo"];
?>
You need to set xhttp.withCredentials = true; to send credentials (and COOKIES too) to the target server using XMLHttpRequest. For more information look the docs.
The next problem you faced is about Access-Control-Allow-Origin header. Your server sends Access-Control-Allow-Origin: * header, and thats why your browser rejects your XMLHttpRequest. Access-Control-Allow-Origin: * header means that your server application allows you to send requests from frontend to ANY other server. With combination of xhttp.withCredentials = true it's very big vulnerability, cause malware js script on your page can send user's credentials to any other place. Thats why your browser rejects your request. You should add yours domain to Access-Control-Allow-Origin header and remove *. This problem was already solved in this question.
Ensure that domain the cookie is set on and domain you are making ajax request to are the same. Also, check the url path the cookie is set on.
Browser will send cookies only to the domain and within the url path it was set on (if you don't apply specific cross-domain rules).
I think you have to run in server if you open html directly in browser it will not understand php code so that's why it's not working.
Related
Noticed that token information when sent to a 3rd party service in the in format "https://domaindotcom/login/token/blah.blah.blah.blah" works fine when copying and pasting it into the browser.
Now, when the same token is sent from a webpage sitting on an internal website via a PHP redirect (using the header function) we get issues. The redirect executes, the token triggers the event with the vendor, but it fails to finalize.
The page sits on a web server which is NOT accessible by the world.
Differences perhaps in what information gets sent out via these two methods?
Would a browser send more info when a PHP script is triggered on it such as referer?
Perhaps referer information received via the PHP header redirect function, and the vendor attempts to ping back (if their server detects a referer), but since the server is not accessible it may be flagged and process killed?
Would appreciate thoughts and ideas on what may be happening. Thank you!
This most likely has to do with their cookie settings. Specifically, if the cookie setting of the domain you are redirecting to contains SameSite=strict, the first request after a redirect from another domain will not include cookies.
var str = window.location.href;
var stringWithNumbers = str;
var n = 1;
console.log(str);
var changedString = stringWithNumbers.replace(/\/(\w+)/ig,v => n++ == 4 ? "ltfgt" : v);
console.log(changedString);
var st = changedString.split('ltfgt')[0];
console.log(st)
var str2 = "/Videos/folder/pencil.html";
var res = st.concat(str2);
console.log(res);
window.location.href=res;
var rplc= st.replace("ltfgt","/Videos/folder/pencil.html");
console.log(rplc);
After the hoster upgraded from PHP 4.x to PHP 5.4.1 a friend of mine has a huge problem accessing $_SESSION variables when doing it via XMLHttpRequest (he uses jQuery for that).
I hope the following snippets of his code are illustrating his problem:
index.php
<?PHP
session_start ();
$_SESSION['chatfenster'] = array();
$_SESSION['user'] = 1;
?>
<!-- HTML Markup -->
<script type="text/javascript" src="../scripts/jquery/js/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
setInterval(function() {
$.post("http://www.his-domain.at/ticker_tracker.php", function( feedback ) { alert(feedback); } )
},
10000);
});
ticker_tracker.php:
<?PHP
session_start();
var_dump($_SESSION);
?>
When he browses to index.php and afterwards manually to ticker_tracker.php, the $_SESSION variables are var_dumped correctly, but if the php file is called via $.post(), the $_SESSION variables are all empty, thus alerting just "array{}".
Hosters support says everything is fine and they didn't change any settings at all, but I noticed that Chrome blocks the XMLHttpRequest due to cross domain requests, giving the error message (also only appearing after upgrade to PHP 5.4.1):
XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present.
Adding Access-Control-Allow-Origin headers on the very top of every php solves this error, but the main problem (empty $_SESSION variables) still remains.
Any advice is appreciated. Thanks in advance!
If you get the access-control-allow-origin error (that can be solved as you said by adding a header), then you are doing a cross-domain request. That's why you have different session contents: they are different sessions!
This can be from one machine (domain) to the other (www.one.com to www.two.com), this could be from one subdomain to the other (www.one.com vs one.com) or this could be a different service (e.g. http vs https, and these might be served by a different machine or process).
All these things have one thing in common: you have a request that seems to go to a different place (hence the allow origin). And a different place has different sessions, as they are not shared.
Check why you have the access control thingy going on: the request isn't going to the same place. So 'fixing' it with headers is just a fix for the origin: remove that 'fix', and make the request not needing it. then you're back at the same server/process/whatever, and will have the same session.
My site is like this that user opens it and runs index.php, and in index.php there are many ajax calls to other php scripts in same server directory as index.php. Now im using post, but if user comes to know addresses of these other scripts (like from right-click ---> view page source) then he can run those scripts in their browser, which can lead to inconvenience (e.g sometimes causing blank entries to be inserted in to database, just an example). So how do I disable php execution of those scripts from a browser yet ajax can call them?
You can't, at least not reliably (you can use JavaScript to add extra request headers, for example, but the user can observe those requests and add the headers themselves).
Check that submitted data is sane instead. If a submission to add a blank entry comes, throw an error message back.
you should check in php script if it is Ajax Reponse
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo 'call from ajax'; //here you have call request by ajax
}
else
{
die("You shouldn't be here");
}
/* not ajax, do more.... *
Source of code
Most of well known JS libraries use this header. If you don't use library you can set this header by your own.
var req = new XMLHttpRequest();
req.setRequestHeader("HTTP_X_REQUESTED_WITH", "xmlhttprequest");
These headers can be set when attacker tampers data but for common guy who wants to access page via browser it will show "you shouldn't be here" message.
Here's what I use to detect AJAX requests:
function isAjax()
{
/* AJAX check */
return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}
Please note that this does NOT guarantee detection and can only help stall misguided users, not determined attackers.
I am calling a php file using $.post. From the server I am returning json response. When I open the server url directly in browser it returns successfully. But from js it is not working.
The link I am calling is this(http://54.249.240.120/qcorner/login).
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<input type="button" id="testID">
<script type="text/javascript">
$(document).ready(function() {
$("#testID").click(function() {
$.post('http://54.249.240.120/qcorner/login',function(result){
alert(result);
});
});
});
</script>
</body>
</html>
I also tried in Firefox. In that I get 200 OK, but no response.
Why this is happening
The problem is that it is a cross domain request the error being returned can be viewed by turning on the javascript console:
XMLHttpRequest cannot load http://54.249.240.120/qcorner/login. Origin null is not allowed by Access-Control-Allow-Origin.
You will need to make sure that the Access-Control-Allow-Origin headers are set to allow this to happen or Chrome will cancel the request.
I suspect you're running into a Cross-origin resource sharing problem. I'm guessing you're not accessing this page from http://54.249.240.120/, given that Chrome is showing it explicitly in the network tab (usually it doesn't do that if it's the same domain).
Long story short, you can't post via Javascript to another domain name. If you're accessing this at www.example.com, the browser won't recognize the IP address as the same domain name (even if the domain name resolves there). Easiest way, if you're in control of the whole situation, is just put that login code on the same domain as the code you're testing. In a local environment you can do this with your [hosts file, something like 54.249.240.120 www.example.com to redirect example.com (replace with your own domain that you are accessing the test page from) to the IP address. This won't work for the public internet, however.
If you must POST to another domain via javascript, you'll need to look into implementing the CORS standard. Here's an article I found explaining how to implement it in PHP.
An HTML 200 OK is not the same as a valid response. It means the server got your request, but it doesn't mean that your PHP file actually returned usable data. It could be returning an empty response altogether. It's time to debug the PHP file. I'd suggest logging to a file temporarily or use FirePHP. If error display is disable (as it should be on a production server), this can happen if your script is failing before any output is generated.
What exactly is happening with the request? You can't make an ajax request cross-domain with what you have listed in the question.
However, you're sending an empty POST request to the URL, and when I replicate an empty post request, it responds with an HTTP 206 error, which is what you need to sort out.
curl -X POST http://54.249.240.120/qcorner/login
{"head":{"status":206,"message":"Only 0 fields received, required 2"},"body":""}
I had the same issue as you and what I did is very simple.
In you PHP file receiving the ajax request, just add this line before sending the response :
<?php
header("Access-Control-Allow-Origin: *");
... // your code here
?>
I'm using some PHP pages do some AJAX stuff but I don't want them to be directly accessible. Facebook does a similar thing so for example: domain.com/ajax/my_ajax_form.php
If I was to load that page using AJAX it would work fine, but if a user were to try and loading the file directly by typing in that url it would do through an error so e.g.
if( IS FILE LOADED DIRECT? )
{
header ( HTTP/1.0 404 );
}
This isn't possible. You cannot rely on $_SERVER['HTTP_X_REQUESTED_WITH'], and even if you could, it doesn't matter. Anyone can send the same request to your server that your browser does, via POST or GET.
What you should do is validate the request, and return the proper result if it is valid. If it is invalid, do not return a 404. (Browsers can cache errors like 404. If your client-side code had a trouble, subsequent requests may fail!) If the request is invalid, return an error of some sort.
Again, it is impossible to secure stuff like this. You should be validating the session and request data. That's all.
You can look for the HTTP_X_REQUESTED_WITH header.
$is_ajax = array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER)
&& $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
if (! $is_ajax) {
die('go away.');
}
Note, though, that it's not standard, but needs to be set explicitly on the requesting side. AFAIK, at least jQuery and Mootools set it though, probably most others as well, but don't take my word for it.
Simplest way is to only access that page via POST, and not via GET. Though keep in mind - if a browser can do it - then a hacker can too.
You have to use session variables, or more generally, cookies.
With cookies: (set in JavaScript)
JavaScript: Set token in cookie
JavaScript: Make XMLHttpRequest
Server side: Check token from cookie
Server side: Return JSON output or error message
Please note that this is no way secure! This just prevents easy linking.
With session variables: (cookies set in server side)
Server side: Authenticate user, set privileges
JavaScript: Make XMLHttpRequest
Server side: Check privileges
Server side: Return JSON output or error message
This method is as secure as the user authentication is.