I'm trying to rewrite a snipped of PHP into JavaScript, ideally passing as few as possible variables between the two. Are there any super-global variables in JavaScript that give similar information to the PHP $_SERVER array?
In JavaScript, location seems to give me a bit of useful information but what about something like the PHP equivalent of $_SERVER['HTTP_REFERER']? I also have jQuery as a resource.
window.location can be read or set and comes with properties such as .pathname, .search, .protocol, et cetera -- each of which will provide that particular aspect of the URL as a read-only value.
document.referrer will provide the referring URL as a string. If you want the domain/path/query/et cetera to be separated from one another, you will need to do that yourself, or use a library which will provide it.
document.cookie will provide you a semicolon-delimited list of user/server-set cookies.
Again, turning that into an array or an object is on your own shoulders.
Your cookie string also has no access to expiration-times, nor applicable paths the particular cookie is set for -- security.
For most of the rest of the data, you're going to have to talk to the server -- the browser likes to keep client-side script in the dark about things (like the user's IP, or session-variables, or anything else which can be turned into a security-risk).
This will get you the referrer -
document.referrer
But I think you are looking at this in the wrong way - JavaScript and jQuery are run client side - if you want server variables accessible - you'll have to pass them to the script - possible by means of an AJAX call. You say that you have jQuery available - so you can use the .ajax() function to retrieve all the server data you'll need.
Related
I've never understood this, and on my own projects I have never needed it. But I've been contributing to WordPress a little, and they use it heavily.
Somehow they are able to redirect the user to a different page with some sort of GET variable in the URL (which is what I understand to be the advantage of using GET over POST). How do they do this? Is it as simple as making a header like header('site.com/page.php?foo=true');? This can't be useful since you have to hard code everything in (unless you want to create a string based on other variables which is kind of annoying, even still). I thought there would be a built-in function like send_get('page.php', $foo);.
I understand how to use information by using $foo = $_GET['foo'];, but I don't know how to send it with PHP.
An explanation would be appreciated - thanks!
There isn't exactly a "customary" way of using it. It is one of nine superglobals. The way you use them is at your discretion. As Greg P already mentioned, they are passed through the URL.
I know how to set up a HTML form that sends variables this way, but how can I do the same thing with PHP?
If you're talking about sending GET variables with PHP solely, the answer is no. You needn't even have PHP to send a GET variable. It is as simple as adding a question mark followed by a variable name = something. Separate several of them using an ampersand (&)
Setting up a GET variable is as easy as creating an anchor link.
<a href='somepage.php?getVar1=foo&anotherVariable=2&thirdVar=3
You can use PHP to dynamically place certain information in there instead of writing it manually, which is the entire purpose of the language to begin with. It is a preprocessor
So, something like this should get you started
<?php
$someID = // An id pulled from a mysql_query
echo "<a href='somepage.php?someID=" . $someID . "'>GET LINK</a>";
I thought there would be a built-in function like send_get('page.php', $foo);
Again, PHP is a preprocessor. It doesn't send information, it only outputs it. What you're talking about is Javascript.. moreover, AJAX. AJAX is the only method that will allow you to send GET variables "behind-the-scenes". And, like was mentioned in another post, jQuery has an awesome codebase for this.
I think you're missing the forest for the trees...the $_GET/$_POST are just variables that are passed to the page processing them - what is DONE with them and how it is done, is up to the design of the application. For example, Joomla always puts the component_id and the item_id in the $_GET array, and has been designed with that in mind, so expects them to be there, and constructs the page, or redirects, or whatever with that in mind.
In your example, a send_get() function might be a good idea (I didn't design it), but the architects didn't see it that way for one reason or another. Joomla happens to have a redirect function that does have a certain dependancy on what was passed in the $_GET, but that is only by design of the applications authors.
Maybe redirect URL is kept in some of session variable. Properly $_GET variable, indicate for wordpress: "check session variable for redirect URL".
PHP.net says:
An associative array of variables passed to the current script via the URL parameters.
URL parameters: generally are variables passed to a script via the URL such as in your example site.com/page.php?foo=true. Everything after the ? is considered a paramter.
Quoted from a StackOverflow question:
The HTTP protocol defines GET type requests as being idempotent, while POST may have side effects. In pain English that means that GET is used for viewing something, without changing it, while POST is used for changing something. For example, a search page should use GET, while a form that changes your password should use POST.
To be specific, I want to make code like Yahoo's Registration (Yahoo ID - Check Availability) checking the availability. The problem here is I need to use PHP to connect, get, and search/verify if the entered value in the textbox is unique.
I tried passing a JavaScript value to a PHP variable, but based on my research, doing this isn't possible, so I need another possible solution to get the value of the textbox and set it to a PHP variable.
Thank you in advance.
The only way to get data from JavaScript to PHP (in a typical environment) is to deliver it over HTTP. Doing this without leaving the page is known as Ajax, and usually done using XMLHttpRequest.
There are no shortage of tutorials describing how to do this, nor any shortage of libraries that will help (plus, of course, all the large libraries such as YUI and jQuery).
You can use Ajax for manipulating this situation.. Have a look at following link.
http://www.digimantra.com/technology/javascript/check-username-availability-validation-ajaxphp/
You need to use AJAX for that.
AJAX is used to send and receive data from the server. So, on the server side, you can create a URL that checks whether a username (can be passed using get/post) is available or not & accordingly send a response. At the client side, depending on the response you receive from the server, you can alert the user.
I have some variables set in Javascript. Further down the script I want to use these values in PHP. I realise I need to POST/GET them with jQuery, but I don't understand either function fully, even after looking at the manuals.
Could somebody break it down and explain the parameters?
Would I be better off using GET or POST in the instance?
Can the URL specified be the same as the current page e.g. index.php?
Thanks very much for your help.
You can not do this unless PHP is writing the javascript. PHP is on the server side and will be parsed before Javascript is ever seen by the client. Any variables set by JS will NOT be seen by PHP on the same request.
It's really just a question of style, really.
GET places all key/value-pairs in the URL field, whereas POST puts it in the HTTP body. Since URLs are limited in length, POST is preferred for longer, larger sets of data or data needing to benefit from TLS/SSL encryption.
So let's say we have a key: articleID. You want to pass 1 to articleID, so that the backend can contact the database and retrieve the article in question.
If you make a GET request, you'd invoke the following URL:
index.php?articleID=1
If you use POST, you'll put the data in the request body itself, so you wouldn't be able to tell what value you sent to the server without opening the packet in question and examining the request.
You'll find more information on how to perform these requests back at jQuery's reference site. More information about GET and POST.
You are the architect of the application, so you would know best what method to use. As for contacting the view itself, it's certainly possible albeit questionable from an architectural point of view.
I'd like to inspect the session variable. Best case something that works in the firebugs little interpreter, but if I have to put it in the file thats fine. Right now I just made a short PHP to output $_SESSION, but if I could find something analogous to be done right in the browser that would be ideal. document.cookie doesn't seem to do what im looking for, at least not that i see.
Basically looking for something analogous to $_SESSION that I can use in javascript
EDIT - was trying to see if i could get anything more than, or extract the meaning PHPSESSID=o147cf52u9d7qr251hc3n6ilu2; ASESSIONID=101wvpe-3FA77F204CFF55BA61E696AD3F62F0F8 on the client-side. As it stands I guess i can just write a small ajax function to a url that echos the session. Thanks for the help!
PS - Do those document.cookie values have anything to do with whats inside the session, or are they just identifiers to tell one session from another?
Session data is stored on the server. It isn't accessible to client-side JavaScript unless you manually expose it (e.g. by writing a PHP program that dumps it to JSON and delivers it over HTTP).
The browser just gets a cookie containing a token that identifiers which packet of session data the server side programs should open for a given client.
Just look at what cookies are set in your browser: Firefox,
Chrome, etc.
Edit: oooh, after re-reading your question, you want to ACCESS the session data.
That's not possible via JavaScript for very good reason. XSS would be a breeze. Besides, the data is stored on the server, which JS has no access to (thankfully).
It's not possible to do what you're asking.
I am using FirePHP to debug variables from my Ajax calls, maybe it is what you are looking for?
You can't access PHP sessions within JavaScript directly. You could however make an Ajax call to a PHP script which will return the PHP sessions. This is your best option.
I am new to PHP. In the path of learning PHP language, I notice that, some website would this kind of URL:
www.website.com/profile.php?user=roa3&...
My questions:
What is the "?" symbol used for?
If I were develop a php website, must I use it in my URL? For example, after a user(roa3) successful logged in, I will redirect to "www.website.com/profile.php?user=roa3" instead of "www.website.com/profile.php"
What are the advantages and disadvantages of using it?
Good questions, briefly,
"?" stands for the start of querying
string which contains the data to be
passed to the server. in this case
you are passing user=roa3 to
profile.php page. You can get the
data by using $_GET['user'] within
profile.php. querystring is one of the methods to send data to the server from client agent. The other one places the data in HTTP body and POST to the server, you don't see the HTTP POST data directly from browser.
querystring can be edited by user
and it is visible to the public. If
www.website.com/profile.php?user=roa3
is intended to be public then it is
fine, otherwise you may want to use
session to get current user's
context.
it is a flexible way to pass data to
the server, but it is visible and
editable to the users, for some
sensitive data, at least produce
some kind of hash before attaching
it to the querystring, this prevents
users to edit it or understanding
the meaning of it. However this
doesn't prevent a decent hacker to
do something wrong about your
website. Different browsers support different max length of URL, the lengthy URL is made up by those querystring parameters. If you want to send large amount of data, place the data in the HTTP body and POST to the server.
Most of the answers I've seen so far have been in terms of PHP, when in reality this isn't language specific. The answers given so far have been from the view of PHP and the methods you would use to access the information differ from one language to the next, but the format in which the data is in the URL (known as the Query String) will remain the same (Ex: page.ext?key1=value&key2=value&...).
I don't know your technical background or knowledge, so please forgive me...
There are two different methods for a web page to provide data back to the web server. These are known as the POST or GET methods. There also also a bunch of others, but none of those should be used in any sort of web design when dealing with a normal user. The POST method is sent invisibly to the server and is meant for 'uploading' data, while the GET method is visible to the user as the Query String in the URL and is only meant to literally 'get' information.
Not all sites follow this rule of thumb, but there can be reasons as to why. For example, a site could use POST exclusively to get around caching by proxy servers or your browser, or because they use double byte languages and can cause issues when trying to perform a GET because of the encoding conversion.
Some resources about the two methods and when to use them...
http://www.cs.tut.fi/~jkorpela/forms/methods.html
http://weblogs.asp.net/mschwarz/archive/2006/12/04/post-vs-get.aspx
http://en.wikipedia.org/wiki/Query_string
Now from a strictly PHP position, there are now 3 different arrays you can use to get the information a webpage has sent back to the server. You have to your disposal...
$_POST['keyname'], to grab only the information from a POST method
$_GET['keyname'], to grab only the information from a GET method
$_REQUEST['keyname'], to allow you to grab the POST, GET, and any COOKIE information that might have been submitted. Sort of a catchall, especially in cases where you don't know which method a page might be using to submit data.
Don't get sloppy by going directly with the $_REQUEST method. Unless you have a case like I mentioned above for the $_REQUEST variable, then don't use it. You want to try and use a 'deny all, and only allow x,y,z' approach when it comes to security. Only look for the data that you know your own site will be sending, only look for the combinations that you'll be expecting, and cleanse all of the information before you use it. For example..
Never do an eval() on anything passed via the above methods. I've never seen this done, but it doesn't mean people haven't tried or do.
Never use the information directly with databases without cleaning them (research into SQL injection attacks if you're not familiar with them)
This is by far not the end-all, be-all to PHP security, but we're not here for that. If you want to know more along line, well then thats another question for SO.
Hope this helps and feel free to ask any questions.
1) If a user logs in to your site, you would use Sessions to store there username instead of passing it in the url e.g profile.php?username=roa3
2) Using a ? symbol in the urls is generally considered bad for Search Engine Optimization. Also, the urls look a bit ugly. Using mod_rewrite you can do the same thing as profile.php?user=roa3 or products.php?id=123&category=toys with: site.com/profile/roa3 or products/toys/123.
Using the CodeIgniter framework will give you friendly URLs by default and eliminate the need for ?s in your urls. See this page for an example.
3) The ? symbol is also used inside the code of a php page. For example, an if else block such as:
if ($x==1)
$y=2;
else
$y=3;
can also be written as:
$y=($x==1) ? 2 : 3;
The "?" signifies that some GET variables are to follow. You example uses a variable called "user", and assigns a variable called "roa3".
Advantages of using GET variables:
they can be bookmarked as part of the URL
Disadvantages
they are public.. Anyone can intercept and see this information. These url requests are even cached by servers along the journey. So anyone can impersonate your roa3 user just by typing that information in by hand... also they could change the roa3 to a different user and impersonate them..
You can also use a "&" symbol to separate many variables e.g.:
www.website.com/profile.php?user=roa3&fav_colour=blue
Other options:
POST variables
You can send your variables via the POST variables. These variables are passed in the header of the request, not the url of the request. they are not immediately obvious, and are not cached by servers along teh journey, but they can still be read. unless you have a HTTPS conection established.
variables in a form can be sent by POST or GET methods.. You specify this in the "method" of the form. <form action="index.php" method='post'/>
SESSION variables
Session variables are stored on the server. A session id is passed to the user, and this session id is passed back to the server every time the user makes another request. This session id can then be used to get the session variables that were stored. So you could store a user's favorite colour, their name, and ip address etc.. but you could store it on teh server rather than the user's home PC.
Session ids can be impersonated, so it is good to check against the user's IP, and or to wrap them in a secure conection. eg https.
session variables can't be changed by someone who intercepted the request.
COOKIE variable:
Similar to the session variables, except that they are stored on the user's PC, not the server. They are stored against a domain, and when they go to that domain, they resubmit the variables in the header of the request to the server.. this means that the user could change and hack the variables, or someone else could.
To access these variables in php you can use:
$x = $_GET['user'] for a get variable
$x = $_POST['user]
$x = $_REQUEST['user'] - the combination of get, post and cookie variables
$x = $_COOKIE['user'] - cookie variables
$x = $_SESSION['user'] to access the session variables
(user could be replaced with the name of the variable you are using)
Simple enough stuff, but important to know what they actually do.
? is part of the HTTP standard and not part of PHP. Thought I should point that out so when you move on to another language and see it again you are not confused thinking there is PHP involved.
Otherwise there are some excellent answers above.
From the server's point of view, the ? is just another character. PHP provides easy methods for parts of the URL after the ? character, e.g. for "/profile.php?user=roa3", PHP will set $_GET['user'] = 'roa3'.
The reason ? is useful in URLs is that browsers can construct dynamic URLs using forms -- in the case above, I would expect that the URL was built by an HTTP form with a field "user", into which the human user has typed "roa3".
"?" is used to separate the URL and the parameters. For e.g, it is like http://www.url.com/resourcepath?a=b&c=d. In this case a=b is like request_parameter=request_value.
Ya, Its not advisable to use much of the parameters because the total url size is limited and it is like GET request, where all the parameters are shown on the url and the user can modify it. In your example, say what if a user modify the url to "user=techmaddy'.
Advantage is it can be used for the GET kind of requests. Disadvantage is low security, limitation in size.