How can I request a URL with my own variables without using it through a HTML form?
Thanks!
EDIT:
When a specific page loads I want to send a request to a url with a couple of my own variables.
Ex: I come to www.example.com/done
the page sends a request to www.example2.com?abc=123&def=456
Your question is too broad, but there is an answer...
By issuing HTTP request in a different way, for example:
by calling it using AJAX from some website (eg. jQuery.post()),
by issuing a request using some kind of tool, like browser extension (eg. Postman REST Client or Simple REST Client for Google Chrome),
by using some library to do such call in an automated way (eg. Requests library for Python),
In general, GET parameters are passed in the URL, while POST parameters are passed in the body, so to pass both, you need to do both, by issuing POST request and:
appending GET parameters to the URL, in URL-encoded way (like "...?par1=1&par2=2"),
passing POST parameters in the body of the request, also URL-encoded
POST variables are either sent through a form (hence, POSTing them), or sent using AJAX.
GETvariables, however, are simply passed through the URL. For instance, if you wanted to send foo=bar to example2.php, you could use
Go to example2.php
And then in example2.php, you could say
$foo = $_GET['foo'];
Simple. :)
Use AJAX in javascript. For a beginner I'd recommend using the jQuery library
$.get("url", {key: "value"}, function(resp) {})
or
$.post("url", {key: "value"}, function(resp) {})
Should suffice
Related
when use GET Method for receive JSON data , we can acsses the result directly from web browser , for example i send a mydata value from ajax to a main.php file and it process and get answer show a result some thing like below :
<?php
if (isset($_GET["mydata"])) {
if ($_GET["mydata"]=="hello"){
echo "hello world";
}
}
?>
but when a user call it in browser directly like http:mysite.com/mydata.php?mydata=hello recive answer . i want dont allow users to get answer of http request directly , and just can show it from ajax result of main page is it possible ?
You're asking how to prevent an ajax-only request from being accessed directly by copy-pasting the URL into the web browser; that is, only allowing the URL to be accessible via ajax on the main web page.
Well, there are a few things you can try:
Check the Referrer for the URL of the main page with $_SERVER['HTTP_REFERER']
Set a header in Javascript using xhr.setRequestHeader() and then ensure it's value by checking for $_SERVER['HTTP_X_....'] in PHP
Like Jay Bhatt recommended, check for the X_REQUESTED_WITH header, but be aware this might not always be set (see: X-Requested-With header not set in jquery ajaxForm plugin)
However, in any of these situations you should be aware that anyone who knows what they are doing can easily set any HTTP header, variable, or even modify the referrer which is sent to the server. As such, there is no 100% guarantee that your resouce can be accessed only via AJAX on the main web page. There is no control built in the internet to verify where a request is coming from, so anyone can easily spoof or fake it.
What is the best way within my PHP script to differentiate between a normal browser GUI request and an AJAX request?
Not as such.
You can write your JavaScript in such as way to to leave some sort of identifier in the request headers that you could use though. See the XHR setRequestHeader method.
A nice use of HTTP would be to modify the Accept header and then do normal content negotiation. Then (for example), instead of caring if it is Ajax or not, you just care if an HTML response is preferred over a JSON response.
Another convention is to use the non-standard X-Requested-With header with a value of XMLHttpRequest. A number of JavaScript libraries will add this by default to any request using XHR.
Either of these techniques will only work with XMLHttpRequest or plugin based Ajax though. You can't set arbitrary HTTP headers for JSON-P or iframe based Ajax.
As far as the server is concerned, there is no particular difference between a normal request and one initiated by Javascript.
If you want to identify a particular brand of request, a reasonable approach is to pass a custom header.
$.ajax(uri, {
beforeSend: function(xhr) {
xhr.setRequestHeader('X-YourApp-AJAX', '1');
});
Providing you're using Apache, checking for the header you just set in your PHP is easy enough.
$headers = getallheaders();
if(isset($headers['X-YourApp-AJAX'])) {
// AJAX request
} else {
// ...
}
Edit
Looks like jQuery, amongst others, already passes an X-Requested-With header in AJAX requests – use that in preference.
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.
I make ajax calls to the file /ajax.php
It gives me some data.
How do I check inside ajax.php, was this file directly opened in browser or by a true ajax call?
Quick and dirty answer is like, you can't make it sure 100%. An "AJAX" request still is a normal HTTP request. Probably the best way to somewhat verify that is to set a custom HTTP header for which you have to check on the server side.
For instance, it's a common practice to add a X-Requested-With header to the HTTP request if it was an ajax request. jQuery for instance puts that header in all its request under the hood.
I think the usual way PHP developers do this is to pass a flag to the server during the ajax request.
The usual flag I've seen has been: ajax: true
$.ajax({
url : "/ajax.php",
type: "POST", // If you want to send the data as a POST rather than GET
data: ({ajax: true})
});
the best way to make sure this was a true ajax request would be to use tools like firebug, fiddler or the network tab in the google chrome developer tools. you can then observer the traffic between your browser and the server, contents of the traffic etc..
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
}
});