I have a URL structure with query string and parameter called position.
example:
http://computerhelpwanted.com/jobs/?occupation=administrator&position=network+administrator
I also have a form select option drop down list with the form select name of position.
example:
<form action="/jobs/" method="GET" id="menuform">
<select name="occupation" onChange="populate(this.id,\'position\')">
<option selected="" disabled="">Select Occupation</option>
<option value="administrator">Administrator</option>
</select>
<select name="position" onChange="this.form.submit()">
<option selected="" disabled="">Select Position</option>
<option value="network administrator">Network Administrator</option>
</select>
</form>
When the user makes a selection, it sends the option values to the action attribute with the select name="position" as the parameter to use in the query string.
My question is, how do I access the form select values separately from the query string values?
I use the _GET method to call the value from the query string parameter.
example:
$position = isset($_GET['position']) ? ($_GET['position']) : '';
Apparently that gets the value from the URL structure, not the form element. Or maybe it does both, not sure. But testing it, I seem to draw conclusion that it is getting it from URL, not form.
How can I make sure to access the form select value when making my comparisons in my PHP?
Update
The issue I'm having is with my canonical URL set in the header.
<link rel="canonical" href="http://computerhelpwanted.com/jobs/?occupation=administrator&position=network-administrator" />
that link is a indexed link on Google. I know I can just do an htaccess redirect to new link, but I'm just trying to figure out how to display the canonical url for this page.
it should be
<link rel="canonical" href="http://computerhelpwanted.com/jobs/?occupation=administrator&position=network+administrator" />
the only difference is the - and the + in the query string.
Not all of my query strings have the +. Some have the -. But I display the content on both urls whether it has - or +. Either way, both urls get same page content.
But since the canonical is being created dynamically from the URI instead of what the value is from the form element, both content pages have 2 different canonicals.
Using _Get('value') is pulling the value from query string instead of form element. I know this because the form element value has a space between network administrator which gets urlencoded when form submits as network+administrator. So if I can compare to the form element value, I can set the proper canonical.
HTTP is a stateless protocol, you generate the HTML stuff upon invoking the required page, and then it's there. When interacting with a form element, you can put select values from the predefined (built with DOM) options, and you can pass that on to another file for processing. When you pass the values to that processor file, you can do so through various methodologies (for simplicity lets just take a look at the GET and the POST ones).
GET: will convert your form parameters to a url query which you have also posted in your question. When your data arrives in the form of the GET array to your processor file, the file itself has no idea what kind of form it got it from, it only sees the query.
POST: will encode your parameters into the transport layer, having it not apparently visible, however it is still there.
Using GET, you could manually form a query with intendedly invalid or malicious parameters and invoke your processor file with them. POST can also be programatically set to be malicious, but provides a convenient level of obscuration as such, and considering your question, might provide the effect you were looking for ("not directly taking it from the url").
Edit:
Code for simplifying form parameter handling according to visible pattern seen in OP question and comment:
$validKeys = array(
'position',
'occupation'
);
foreach ($validKeys AS $key){
${$key} = isset($_GET[$key]) ? $_GET[$key] : '';
}
/* other processing code */
With the above, if you had lets say 15 input parameters, you wouldn't have to go through all of them one-by-one, as ${$key} allows you to create dynamically named variables, and you just update your $validKeys container (which could also be filled with values held in the database, and not manually controlled). From your updated comment I devised that you might be looking for something like this.
That is because you are are you using GET which can be easily manipulated through URL.
I suggest changing the method to POST. It can be edited though using debuggers.
Related
Thanks in advance for any suggestions on the following:
I've created a php-page to add works from composers to CDs in a database. It's a combination of two forms and looks like this:
1st form:
Composer : [drop down list] : Select
Some blank space
2nd form:
Title : [drop down list]
Track number : [empty varchar field]
Work : [drop down list]
some other fields
Process button
After selecting a name in the first block (posting to $_SERVER["PHP_SELF"]) I stay on the same page, that name is shown in the blank space in between and the drop down lists are populated with only CD titles and works of the selected composer.
I can then select from the lists and enter other data in the other fields. Hitting the process button posts the data from the second block to another page which will eventually send everything to a table in a MySQL database.
After that I send myself back to the first page with header("Location: the_first_page.php")
So far so good, but upon returning I would like the composer, title and work to be preselected. Now I'm sent to a blank page and have to start from scratch. I think I've seen some solution involving testing $_POST['something'] against <option value> in a drop down list but I can't seem to make that work.
My question is: Is there a way to send $_POST['Title'] and $_POST['Work'] back to the first page somehow? Or is it better to split the two forms over seperate pages?
All help is welcome.
You could use sessions or the post data itself. For using the post data itself, the page where you send the request should be the same and include the script that will process it if there's some data like this:
if (!empty($_POST)) {
include "save.php";
}
// More code...
?>
<select name = "a">
<option <?php if ($_POST['a'] == "test") echo "selected"; ?> value = "test">
<option <?php if ($_POST['a'] == "testb") echo "selected"; ?> value = "testb">
</select>
Of course there are many more ways, but this is just a simple one to get you started. Things to know: you might want to change the variable $_POST and clean it up before using it. In this case it should be fine, but in <input type = "text" value = "<?= $_POST['b']; ?> name = "b">` you have a serious security issue.
For sanitizing the input, you want to sanitize it respect to what you expect. But also, as an EXTRA meassure, you normally want to strip everything that looks like a <script>, onclick ="", ' DROP TABLE users and similar. It's not an easy subject, so I recommend you reading on it, mainly on the XSS attacks which is relevant to showing the text back to the user. While it might seem too much work for this "simple case", it is useful in many more situations.
Use session variables and put conditions for them ... see [ $_SESSION ].
I have an HTML array of 10 select fields that must be populated by jQuery each time the div-popup is called. (Each one gets the same options) We have periodic needs for hundreds of employees and this form is intended to allow requests staffing to be forwarded to upper management for approval in a batch fashion by department. I’ll be using .serialize to submit the form but I am unclear as to how to initialize this element with the proper information for input selection. All the info I could find was about submitting the form array, which I already knew how to do.
Here is the HTML structure:
<select id="detJobsCR[]" name="detJobsCR[]"> </select>
And here is my attempt to populate the selection fields:
$.post("events.php",{a: 'detadd-joblist', dept_id: deptID}, function(data) {
for(var i=0;i<10;i++){
$('#detJobsCR[i]').html(data);
}
});
(I tried explicitly defining each elements array position [0],[1]..etc and that did not help.)
The data returned is simple HTML like:
<option value='38'>Admin Support Assistant I</option>
<option value='39'>Admin Admin Support Assistant II</option>...
Thanks for whatever assistance you can offer!
FYI Update: Musa's answer worked perfectly. I also had issues with Date & Time pickers not working, it turns out, for the same reason. When I converted them to classes I was able to use this(below), and the are all now working as well:
$(".detDateStart").datepicker();
Ids should be unique so each select should have its own id. If you want to have one identifiier to represent all the selects you could use a class e.g. <select class="detJobsCR" name="detJobsCR[]"> </select> and then select them with $('.detJobsCR') and set their html with .html(data)
$.post("events.php",{a: 'detadd-joblist', dept_id: deptID}, function(data) {
$('.detJobsCR').html(data);
});
Your problem is two fold:
You're putting i inside your quotes, so it's not interpreting the value of the variable i
Even if i wasn't inside the quotes, when jquery parses the [i] in the expression it's looking for elements with id detJobsCR and with attribute i defined.
Since you have only ONE element, with ID detJobsCR[] you would query it like this: $('#detJobsCR\\[\\]') You need to escape the [ and ] character so jquery knows it's a part of the ID and NOT a parsing rule (for parsing/looking for an attribute).
As suggested by Musa, you can make your life much easier by using a simple class name that doesn't require escaping values. But if you do want to select by id, the example above should do the trick.
EDIT: Answer found! Thank you very much people, a lot of answers worked, I chose the hidden field answer as it was easiest :D
I am creating a commenting script and I came across a problem. I am having to use $_POST and $_GET on the same page, which I don't think makes sense.
I am very new to php and am training myself.
I have a page named viewVerses.php - this has a lists of verses. When someone follows the reply link,
echo '<br />Reply';
I'm passing the verseid (commenting on bible verses) into the reply.php, so that a query may be made with that verseid. (This is so that the user can still see the verse he/she is commenting on).
Now reply.php has the form in it for posting a reply. The form goes to postReply.php
This is in postReply.php
$title = $_POST['title'];
$body = $_POST['body'];
$verseid = $_GET[verseid];
Can I get the verseid from the url and the POST the values from the form in the same page?
If not, is there a way I can do this better? Remember, I am new at php and probably won't implement a solution that is super hard. I have to get it for my to put it in my site.
I hope this is clear
I would add a hidden input to the comment form:
<input type="hidden" name="verseid" value="
<?php echo $_GET['verseid']; ?>
" />
That way, in postReply.php, you can access it using $_POST['verseid'].
Yes you can. The method of a form (in a html page) can be POST and the action URL can contain "GET" arguments being something like process.php?vid=1001 so to say. So in process.php you'll have vid as $_GET and the rest of data from the form as $_POST.
Sure you can, just set the action of the form to postReply.php?verseid=id_of_the_verse this way when an user submits a reply, in the POST array will be the reply related data and in the GET the id of the verse.
Yes, it is possible to mix both GET and POST values with one request. The problem you have is probably that you pass the GET value to reply.php, which then passes POST values to postReply.php. So, unless you tell reply.php to send that GET value as well, it will get lost.
You can do this by either specifying the GET value in the action parameter of the form tag, or you could even switch to a POST value with that, by adding a <input type="hidden" name="verseid" value="<?php echo $verseid; ?>" /> to the form.
Although it may seem counter-intuitive an HTTP request can come in with both Form and QueryString data. Like robertbasic says you can access them both via there respective arrays.
Using a form with a hidden input (<input type="hidden" name="verseid" value="..." />) is probably the cleanest way of doing things.
PHP also defines the $_REQUEST global array in addition to $_GET and $_POST. In general you should use either $_GET or $_POST but in this case where verseid is being passed for both methods, it might be more convenient to use $_REQUEST['verseid']. This way you need not care about the HTTP method being used on your script.
I've never really thought about this, but it helps with some security of something I'm currently working on. Is it possible to submit GET data without an actual input field, and instead just getting it from the URL?
If so, how would I go about doing this? It kind of makes sense that it should be possible, but at the same time it makes no sense at all.
Perhaps I've been awake too long and need some rest. But I'd like to finish this project a bit more first, so any help you can offer would be appreciated. Thanks
Yes. If you add some query-string to yourl url, you can obtain that in php using $_GET without form submitting.
Going to this URL adress http://yoururl/test.php?foo=bar cause echoing foo (if there will be no foo query string, you'll get warning).
# test.php
echo $_GET['foo'] # => bar
Is this what you mean?
Link
// page.php
echo $_GET['type']; // foobar
This is what I understand of your question:
You have a <form method="get" action="foo.php">-like tag on your page
You have a series of <input type="text" name="bar"/> in your page
You want to pass additional GET parameters that are not based on an input from the form
If so, it is possible, but I hardly see how it could help with security. Input from a client cannot be trusted, so even if you hardcode the GET value, you have to check it serverside against SQL injection, HTML injection/XSS, and whatnot.
You have two ways:
Use a hidden input: <input type="hidden" name="myHiddenGetValue" value="foobar"/>
Add the GET parameter to the form action: <form method="get" action="foo.php?myHardcodedGetValue=foobar">
If what you meant is that you want to have a GET request without a form, you just need to pass all the GET parameters to the href of a link:
Click here!
Yes it's possible. Just append the GET data to the link.
For example:
<a href="main.htm?testGet=1&pageNo=54>Test</a>
You can also use Javascript to build the url.
If you happen to be using jQuery and want to build the GET data dynamically you can do this:
var getParams = { testGet:1, pageNo:54 };
$(".myLink").attr("href", url + "?" + $.param(getParams));
Im looking for a way to have a form in cakephp that the user can add and remove form fields before submitting, After having a look around and asking on the cake IRC the answer seems to be to use Jquery but after hours of looking around i cannot work out how to do it.
The one example i have of this in cake i found at - http://www.mail-archive.com/cake-php#googlegroups.com/msg61061.html but after my best efforts i cannot get this code to work correctly ( i think its calling controllers / models that the doesn't list in the example)
I also found a straight jquery example (http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/) which does what i would like my form to do but i cannot work out how to use the cakephp form helper with it to get it working correctly and to get the naming correct. (obviously the $form helper is php so i cant generate anything with that after the browser has loaded).
I an new to cake and have never used jQuery and i am absolutely stumped with how to do this so if anyone has a cakephp example they have working or can point me in the right direction of what i need to complete this it would be very much appreciated.
Thanks in advance
I would take the straight jquery route, personally. I suppose you could have PHP generate the code for jquery to insert (that way you could use the form helper), but it adds complexity without gaining anything.
Since the form helper just generates html, take a look at the html you want generated. Suppose you want something to "add another field", that when clicked, will add another field in the html. Your html to be added will be something like:
<input type="text" name="data[User][field][0]" />
Now, to use jquery to insert it, I'd do something like binding the function add_field to the click event on the link.
$(document).ready( function() {
$("#link_id").click( 'add_field' );
var field_count = 1;
} );
function add_field()
{
var f = $("#div_addfield");
f.append( '<input type="text" name="data[User][field][' + field_count + ']" />' );
field_count++;
}
Of course, if a user leaves this page w/o submitting and returns, they lose their progress, but I think this is about the basics of what you're trying to accomplish.
This was my approach to remove elements:
In the view, I had this:
echo $form->input('extrapicture1uploaddeleted', array('value' => 0));
The logic I followed was that value 0 meant, not deleted yet, and value 1 meant deleted, following a boolean logic.
That was a regular input element but with CSS I used the 'display: none' property because I did not want users to see that in the form. Then what I did was that then users clicked the "Delete" button to remove an input element to upload a picture, there was a confirmation message, and when confirming, the value of the input element hidden with CSS would change from 0 to 1:
$("#deleteextrapicture1").click(
function() {
if (confirm('Do you want to delete this picture?')) {
$('#extrapicture1upload').hide();
// This is for an input element that contains a boolean value where 0 means not deleted, and 1 means deleted.
$('#DealExtrapicture1uploaddeleted').attr('value', '1');
}
// This is used so that the link does not attempt to take users to another URL when clicked.
return false;
}
);
In the controller, the condition $this->data['Deal']['extrapicture1uploaddeleted']!='1' means that extra picture 1 has not been deleted (deleting the upload button with JavaScript). $this->data['Deal']['extrapicture1uploaddeleted']=='1' means that the picture was deleted.
I tried to use an input hidden element and change its value with JavaScript the way I explained above, but I was getting a blackhole error from CakePHP Security. Apparently it was not allowing me to change the value of input elements with JavaScript and then submit the form. But when I used regular input elements (not hidden), I could change their values with JavaScript and submit the form without problems. My approach was to use regular input elements and hide them with CSS, since using input hidden elements was throwing the blackhole error when changing their values with JavaScript and then submitting the form.
Hopefully the way I did it could give some light as a possible approach to remove form fields in CakePHP using JavaScript.