Obtain actual browser URL in PHP - php

I need to retrieve the actual URL that the user see's in their browser. I have an Ajax request running at page load. Hence, the regular $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"] expression returns the request URL of the Ajax request instead of the actual URL in the browser.
Any idea how to get this?

You could pass it up from javascript in your ajax request, using window.location.href.
Also, it's likely that $_SERVER['HTTP_REFERER'] will contain the browser's current location.

You could also try using $_SERVER['HTTP_REFERER'];. This might work, not 100% sure though.

You can't do that with server-side code, as there is no server-side variable that refers to what the client sees. The only thing you CAN see (and then again, it depends on the browser the user's using, some don't pass this info) is the HTTP_REFERRER variable. This however, is only set when a page calls another, not when users first access your site.
See this for more details.
A possible solution however, might be to use javascript function to send the browser's top URL to the server using an AJAX query, and to fire it client-side whenever a user loads the pages) you want to get this info for.
Edit: Damn, too slow, already answered!

Pass a hidden input that has the browser value set with your ajax request. Unless someone is being malicious, it should suffice.

If you do an Ajax-request, you could pass the address available through Javascripts window.location.href variable as a POST-variable with the request.
With jQuery it would be something like:
$.ajax({
url: 'your-url.php',
type: "POST",
data: { url: window.location.href },
success: function (data) {
// Do something on success
}
});
With such a request you could access the URL on the server-side with a simple:
<?php
$url = $_POST["url"];
?>

Actual Website Link in php
<?php
echo $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
?>

Server-side languages can't see what happens after they've rendered and outputted the page.

Related

Hide var data on ajax

I am making AJAX like function but I have problem that bad user can change the value into any other current user. So, how can I prevent this thing?
$live = 'user1';
$fol = 'user2';
function ajax(like){
var data = 'like='+like+'&CURRENTUSER=<?php echo $live; ?>&TOFOLLOW=<?php echo $fol; ?>';
$.ajax( {
type: 'POST',
url: 'ajax.php',
data: data,
success: function(e) {
$('#success').html(e);
}
});
}
Also I want to move this ajax function into ajax.js file, but i am have problem in getting the value $live and $fol of users because echo $live doesn't work on .js.
So, is there any way to do this like Facebook, Twitter AJAX function does ?
This solution works for apache web-server. For interpreting JS file using php, add this line to your .htaccess file:
AddType application/x-httpd-php .js
And put your script inside ajax.js. One other way is using rewrite URL:
RewriteEngine On
RewriteRule ^ajax.js$ ajax.js.php [L]
And put your scripts inside ajax.js.php file. Of course, all these are if you want to show your URL as JS file.
at the top of your ajax.js or ajax.js.php file, before any kind of output, put this:
header('Content-Type: application/javascript');
I have problem that bad user can change the value into any other current user. So, how can I prevent this thing?
Of course you can not do that at all.
HTTP is a stateless protocol – so each and every request that reaches your server is to be mistrusted, period.
You have to check server-side whether the requesting client is authorized to request/perform whatever action it is he wants to trigger – f.e. by checking that the user id that is passed as the “current” user against the session where you stored your login information. (So when you have the id of the current user stored in there, then there’s no need to actually send it from the client any more in the first place.)
This is one of the most basic security principles of any web application – don’t trust any incoming request, until you have verified that the client has the appropriate authorization. So asking for how to “hide” any data that is send from the client is completely the wrong question – that would be what’s called “security by obscurity”, and that does not work.
There can be many solutions for such problem.
Add one of follow user in session before page load so even you dont need to send data in ajax. Just need to confirm action and all data will be taken from session. Hence hackers cant modify users.(This is how i solved the problem in my project)
You can build an function like encode() & decode(). when you are using data in file encode() it first.Then at code end use decode() to extract the info. Since if invalid data came out mean some one has tempered and you will not execute that action. But you have to create such encode() & decode() yourself.
$live = encode(user1);
At php end
$real_live = decode($live);
3. Ajax request to when start php execution you can have a function like
check_auth(user1,user2);
So even if some one used bad data your security rules can filter them.
Hope you can use any of them.

Allow access to PHP file only through ajax on local server

I have a website that needs to increment values in a database based upon user interaction. When users click a button a php script is called that increments the value. I'd like to protect this script from being accessed by outside scripts. Currently a user could write their own web page with a javascript function that hits the same php file repeatedly to blow up the value in the database.
Here's my jquery code that does the incrementing:
jQuery(function(){
$('.votebtn').click(function(e){
var mynum = $(this).attr('id').substring(0,5);
$.ajax({
url:"countvote.php",
type:"GET",
data: {
thenum:mynum
},
cache: false,
success:function(data) {
alert('Success!');
}
}
});
});
});
How would I go about making it so that only a call from ajax/jquery on the local server can access 'countvote.php'? If that's not the correct way to go about it, I'm open to any suggestion that will prevent my php script from being abused by outside scripts.
The solution needs two steps.
Firstly the ajax file must allow access only in ajax request with this code.
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!IS_AJAX) {die('Restricted access');}
Secondly the ajax file has access in the name of file that call it with command $_SERVER['HTTP_REFERER'].
So you can restrict access only in the host server.
$pos = strpos($_SERVER['HTTP_REFERER'],getenv('HTTP_HOST'));
if($pos===false)
die('Restricted access');
Maybe the code can work only with the second part
You can check if $_SERVER['HTTP_X_REQUESTED_WITH'] equals xmlhttprequest, but it's not a reliable method to determine whether a request is an AJAX request or not, there is always a way to get around this. But it protects you from random hits like wrongly entered urls, crawlers etc.
Theres not really a 100% method of doing so. AJAX requests are always going to come from a client. Use POST requests instead of GET and that will help deter any issues but not completely stop them and in your php, just drop all get requests.
I am not sure if this will work, but whats about settings an API key on eg. index.php into a $_SESSION variable, afaik this cannot be visible to the user, unless you do it manually, then in the restricted php file, check the $_SESSION['VOTEAPIKEY'] or whatever

Php, Jquery - Post variable to other page with leaving the page

I'm working on a complex project which needs nice variable posting between pages without post or get. I made it with get, before that I used post in php, but then I started to use jquery which has got better ways to do things. I know how to pass variables between two pages without leaving the page:
visible function blahblah (id){
$.ajax({
type: "POST",
url: "blahblah.php",
data: $(id).serialize(),
success: function(data){
$('#results').html(data);
}
});
}
I always show results in a div, but the one I want to achieve is different. I need to pass a variable WITH leaving the page, but without using php post or get. I did search for it, but I wasn't successful. Can you help me out in this, if it's possible? Thank you for your help.
If you're worried about losing the "go back" function I assume this is because of the annoying warning that appears when you go back to a page that has posted data? To get around that you can try (as others have stated):
POST your form normally to the page
Save variables in $_SESSION[]
$_SESSION['var1'] = $_POST['var1'];
Change the header to refresh the page:
header('Location: ' . $_SEVER['SCRIPT_NAME']);
exit;
That way no one sees what you've posted by GET and you avoid the annoying "Resubmit your posted variables" message.
I am not sure, if I got your question perfectly right..I think you want to:
Send your data to a page using POST/GET
Redirect to another page. Use header function for this.
But, when you say, you don't want to use POST/GET, I really get confused! How can you communicate with your server then? Setting everything to session, can never be a good solution.

access post vars JS or PHP?

I am using jquery to post vars to a php script.
Is it possible to access these vars once the script has posted? If I post the data to the php script, is the only way to access it in the html/js that i posted it from, to send it back from the php script as json?
I cant seem to do it in JS, but even php will not work?, Sorry correction i can access the post vars in the php page, but not in the html/js page i posted from
Any ideas how to access posted vars from the page thats doing the posting?
update: yep to be a bit clearer, i am using a html page with javascript to post to a php page, i would like to access the posted vars in the html javascript page. I tried outputting $.post and $.ajax and these just show a long function.
Cheers
Ke
How are you submitting your elements to php page? If you are doing everything fine and using ajax (see jquery post method) for example, you can access the php variables normally with $_POST['var_name'].
Make sure that:
Your form method type is set to POST
Your ajax request goes successful
You have specified the correct path to your server side script
In PHP, the data should be accessible through the $_POST array, just like if you posted to the script using a form (whether you make an AJAX request or a normal request through your browser, the server behaves the same). If they're not there, perhaps you actually sent your data by GET instead (you could check $_REQUEST, but it's better, and more secure, to know what method your data will be coming in), or else your AJAX request failed.
I don't recommend using $_REQUEST to post something back to your site. If someone changes their $_REQUEST vars on you, then you have an opening for cross site scripting.
Push all your vars to $_SESSION and post them as you see fit but only after they have been purified. That way even if you make some modifications to them after the fact you can rely on the source, which is in the $_SESSION. However if you are trying to perform actions after a page has executed you are straying outside the boundaries of PHP's limitations. People do it all the time with things like Jquery but it doesn't make it right.
Warning: if you allow accessing and process of vars after PHP has finished printing the page, then you run the risk of enabling attacks on your code.
I assume that you are using $.ajax or $.post to do this.
Just keep your data in local variables. There i sno reason why you should lose the posted data, or your php not being able to access it.
If you post code, maybe someone can help better.
In your php function, you can use this:
function foo() {
//do something
echo json_encode($var);
}
I use .ajax, use dataType: "json". The success attribute would be:
$.ajax(
{
url: 'ajaxfile.php',
type: "POST",
data: ($("#myForm").serialize()),
dataType: "json",
success: function(data)
{
//Insert your logic to handle the vars from php
}
});

Form that makes browser redirect when accessed by either a regular form submit or an Ajax request - is this possible?

I have a web page with a form. When the user submits the form, I want the server to make the browser redirect to a different page from the form action. Right now, I am doing this by using PHP's header function to send a 302 status code. It works fine.
I am trying to make the page on the server redirect the browser in the same way, regardless of whether it was submitted normally (without Javascript) or via Ajax. I tried to do this by setting the window location to whatever URL is in the Location header. I am using jQuery, and doing a call like this:
$.ajax({
url: this.action,
type: "POST",
data: getFormData(this),
complete: function(request) {
window.location.assign(request.getResponseHeader("Location"));
}
});
However, that didn't work. After thinking about it, I realized that this is not very surprising. In an Ajax request, the browser is supposed to transparently handle redirect responses such as 302 codes before changing the readyState. When the complete function runs, it is looking for the Location header in the final destination and not finding it.
As an experiment, I then tried sending a 200 status code with a Location header. I tried the Ajax request and it worked fine. However, when I did the non-Ajax submit, it didn't work. The browser went to the form action page and stayed there, like it was ignoring the Location header.
Is there any way to make the same page redirect in both cases, without the server having to know or care whether the request is an Ajax request?
In case this matters, I tried the form in various browsers (IE8, IE7, IE6, Firefox 3.5, Chrome) with similar results each time. Also, I am doing a post request to avoid bumping into IE's 2083-character URL length limit.
HTTP 302 response are consumed silently by XmlHttpRequest implementations (e.g. jQuery's ajax function). It's a feature.
The way I've solved this in the past is to detect for XmlHttpRequests and issue a "Content-Location" header (rather than a "Location" header). The most cross-library way of doing this is to check for the "X-Requested-With" http header in your server-side code (jQuery, Prototype, Mootools among others set this):
if (#$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
header('Content-Location: ' . $redirect_url);
} else {
header('Location: ' . $redirect_url);
}
You still need to special-case your client-side code:
$.ajax({
// ...
complete: function(xhr) {
var redirect_url = xhr.getResponseHeader("Content-Location");
if (redirect_url) {
window.location = redirect_url;
}
}
})
If the user is getting redirected regardless, why the Ajax? The whole point of Ajax like this is to make changes to the page without a page refresh, so the technique you're using seems a little like building a printer that outputs into a shredder hopper.
I'd like to know more about your use-case for this. From what I understand your trying to get your application to load a page based on the 'Location' header of an Ajax call within it? I'd ask why?
An HTTP header doesn't seem to be the right place to get that information from. Isn't your application essentially making a query that says "Where shall I redirect to?". There's no reason the Ajax response actually has to respond with a 302 and a 'Location' header. Why not just have it respond with JSON or XML which contains the new URL?
Edit: Just re-read your penultimate paragraph. I'm not sure there's a good way of achieving what you want. The concept sounds broken to me. :)
Pass additional parameter to your ajax request for easy identify type of request. When ajax - do not redirect - just send target url, then redirect client side in ajax callback via location.href
like this:
$.post('/controller/action', {formdata}, function (redirect_to) {
location.href = redirect_to;
});
Will "complete" work:
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
complete: complete(xhr, status) {
window.location.assign(xhr.getResponseHeader("Location"));
}
});
Did you try using the error function instead of complete?
$.ajax({
url: this.action,
type: "POST",
data: getFormData(this),
error: function(request) {
if(request.status == 302)
window.location.assign(request.getResponseHeader("Location"));
}
});
jQuery sends any 3xx response to the error function. Maybe the 'Location' header will still be available at this stage.
Why not have your "ajax action" simply fill in the needed form fields and submit the form instead? This way you'll get exactly the same behavior as when submitting by hand.
Here is another option although you will need to do some cross browser tests:
complete: function(request) {
if(request.status == 200) {
var doc = document.open(request.getResponseHeader('Content-Type'));
doc.write(request.responseText);
doc.close();
}
}
Major drawbacks: URL in address bar doesn't change; could mess with back button/history
Although I think #crescentfresh's idea is the way to go

Categories