Is it good way to pass variable between pages using $_GET method with url:
<a href="input_obj.php?id='$id'&method=plain
and take it in file input_obj.php with such code:
$id = $_GET['id'];
$method = $_GET['method'];
OR
using session - has someone idea how?
It depends on your needs, really, If you are passing search arguments between pages, for example, and the variables should be both persistent and be available to the end user (via bookmarking, for example), then pass them in the URL (but don't usually use quotes like you have around $id in "input_obj.php?id='$id'&method=plain)
If you are truly passing internal variables between scripts, this is better done via $_SESSION variables. Remember that end users can easily modify variables passed through URLs. Unless they are intended for use by the end user, that may be a real problem. By using $_SESSION, you insulate your script's variables from tampering by the end user when it's necessary to insulate them. (unless, of course, the variables are produced by other user input via GET/POST/COOKIE)
//page1.php
session_start();
$_SESSION['id'] = $id;
//page2.php
session_start();
echo $_SESSION['id'];
GET variables are a much better way to go. When you start dropping variables into the session, it can have side effects like copy/pasting a URL from browser to browser or trying to bookmark can bring up different pages (which consequently is a nightmare for SEO). Also, it can have complications if you ever start clustering your servers b/c you'll need to deal with session failover.
IMHO, the best solution is to use mod_rewrite to implement path-based variables...you get pretty URLs with all the benefits of GET vars.
GET is a reasonable way to pass variables to another page.
$_SESSION and cookies is another way, but it won't allow a user to bookmark a page.
POST is another way, but it requires form submission which would either need user intervention or javascript.
It depends on the what the data is for, its type and its length. Usually, passing variables in the query string is fine.
Be aware that when accepting mutable parameters, you need to verify they are what you expect them to be. For example, I could change ?id=5 to ?id=hello and possibly break your application. To remedy this, we could typecast the ID to an integer: $id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
You could also use cookies. These are sent like this:
setcookie(name, value, expire, path, domain);
you can ommit the path and domain variables. This has to be declared before the tag. The name is just the name with which you will get it. The value is what wil be returned and expire is the time at which the cookie expires (it is writen in the form of time() + $timeTillExpire where timetillexpire is a variable or constant value you set). This of course has the limitation of if the person has cookies of it will not work.
You get a cookie with:
$_COOKIE["name"];
and returns value
the way you did works fine.
If you're just using variables in your PHP script, you don't really need to 'pass' them. You can create a variable globally and access it from another page.
Related
I have a PHP site but a portion uses a flash upload swf to post a file and some parameters to a PHP script.
When that swf posts parameters my PHP script doesn't know any of the session variables. Must be something funky with Flash and the cookies it sends.
Anyways, I could try to fix it in flash but I thought the easier way is to simply pass the session_id in a post parameter. However, once I receive this session_id in my PHP script, I don't know how to use it to lookup the session variables I really want (such as $_SESSION['username']). I don't want to pass $_SESSION['username'] as a POST parameter because I figure that would be too much of a security risk. A long random session_id seems much better.
You can use session_id():
string session_id ([ string $id ] ) session_id() is used to get
or set the session id for the current session.
Code in vanilla PHP would roughly look like this:
<?php
if( isset($_POST['session_id']) ){
session_id($_POST['session_id']);
session_start();
}
Not sure though whether it'll be easy to integrate with CakePHP.
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.
I have a script that has PHP on it, and a link that goes to a new script that alters that PHP. When writing the query and containing variables on the second script, do I need to use the same variables or are the new ones I create completely seperate? or can will the variables from the first script carry over to the second script if used?
If by "link" you mean you use require or include, then any variables that are defined in the same scope as the "link" will already be defined within that file's "global" scope (under most conditions).
If you are linking to another page via a typical HTML anchor tag, then the answer is no. You can, however, pass along information using HTTP GET method or create sessions through manipulations of $_SESSION in php or by setting cookies in the browser. All of the various ways of maintaining informaion across multiple links really depend on your needs. In the case where you would want to use HTTP GET, you could setup the link in script A to link to script B like this:
Click here
Then in script B you would access that data like this:
<?php
$data1 = $_GET['var1'];
$data2 = $_GET['var2'];
And use it however you need. Of course, be sure to perform sanity checks against the data before accepting it as reliable.
You can try and use sessions
As mentioned by everyone else, HTTP is stateless and nothing is shared unless you explicitly store it. Most of the time you will want to store these in the $_SESSION[] super global, but you could also store them in files, cookies, or the database, although the file system and database introduce larger overhead and cookies can easily be manipulated.
PHP is basically "nothing shared". So, when you build your link, you control the state of the $_REQUEST variable using the query parameters (GET or POST) and the hidden parameters (cookies).
The session ($_SESSION) is a convenient cookie/file storage to migrate common data between pages, but it is typically best to keep session lean and free of non-critical state details.
I run foo.com. I have two different applications that live in foo.com: one is foo.com/bar, and the other is foo.com/example. I use sessions to track information about the user while they're logged in, but if the user goes from foo.com/bar to foo.com/example, foo.com/example sees the session the user started from foo.com/bar and uses that information. My question is, how can I have two different sessions going for each directory at the same time?
You should call session_name before calling session_start. This sets the name of the cookie used to identify the session (by default this is PHPSESSID).
Use a different name for each application. You shouldn't have to mess with the variables inside the session.
I think it's very important to highlight the potential security implications associated with the solutions provided so far.
I have been a web application penetration tester for about 5 years and have developed numerous vulnerable security applications in this time to assist with training of juniors starting out in IT security.
I have just been testing the solutions provided and have noted that none of them prevent access to a session belonging to the neighbouring app. Using different session identifier names with session_name() doesn't prevent users from using the value of these identifiers. PHP doesn't have a segregated storage for each session identifier name. I had two apps using different session names and setting a cookie path for the browser. The following respective Set-Cookie directives were included in HTTP responses:
Set-Cookie: TESTONE=<value one>; path=/testone/
Set-Cookie: TESTTWO=<value two>; path=/testtwo/
If both apps had entirely separate users and someone only had access to the /testtwo/ app, they may be able to access info on the /testone/ app depending on the way in which session parameters were being handled. An example code segment below shows a potential data breach assuming that both apps use a $_SESSION["authenticated"] parameter after successful authentication.
<?php
session_name("TESTONE");
ini_set("session.cookie_path","/testone/");
session_start();
if ($_SESSION["authenticated"] == "yes")
echo $topsecretinfo;
?>
To access this $topsecretinfo one would only need to authenticate on the /testtwo/ application, take the value of their TESTTWO session identifier and use it as the value of the TESTONE session identifier when sending requests to the /testone/ application. PHP's session lookup process does not recognise the name of the session identifier except for parsing the correspoding value. i.e. a session identifier value of "agcy648dja6syd8f93" will return the same session object regardless of the name used to refer to it.
You may be able to use session_set_cookie_params to set the domain and folder for the session to be saved under. IE:
// Used on foo.com/example
session_set_cookie_params(86400, '/example');
// Used on foo.com/bar
session_set_cookie_params(86400, '/bar');
You could also use the same session but change the variable names that you look for.
Edit: Sorry this doesn't answer your question but gives an alternative solution.
Another solution is to effectively create a namespace within your session by pre-pending all session values from foo.com/bar with "bar_" and foo.com/example with "example_".
The way you can keep this from being tedious is to abstract this functionality into a function or class method. For example:
function set_session_value($key, $value) {
//figure out which prefix to use by checking the current working
//directory, or whatever method you like. set $prefix equal to
// "bar_" or "example_".
$_SESSION[$prefix . $key] = $value;
}
Then get your values with a matching function.
The main advantage of this is that you don't have to think about what variable names you're using in /example while programming in /bar. The other is that if you decide to change how you are storing session values, you can easily change everything in one place.
I realize this is old, but thought it might help someone. This example shows how we are setting a separate session for our admin area.
if ( $_SERVER['REQUEST_URI'] == '/admin/' ):
$session_name = 'session1';
else:
$session_name = 'session2';
endif;
session_start( $session_name );
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.