I have a search form on each of my pages. If I use form helper, it defaults to $_POST. I'd like the search term to show up in the URI:
http://example.com/search/KEYWORD
I've been on Google for about an hour, but to no avail. I've only found articles on how $_GET is basically disabled, because of the native URI convention. I can't be the first person to want this kind of functionality, am I? Thanks in advance!
There's a better fix if you're dealing with people without JS enabled.
View:
<?php echo form_open('ad/pre_search');?>
<input type="text" name="keyword" />
</form>
Controller
<?php
function pre_search()
{
redirect('ad/search/.'$this->input->post('keyword'));
}
function search()
{
// do stuff;
}
?>
I have used this a lot of times before.
As far as I know, there is no method of accomplishing this with a simple POST. However, you can access the form via Javascript and update the destination. For example:
<form id="myform" onsubmit="return changeurl();" method="POST">
<input id="keyword">
</form>
<script>
function changeurl()
{
var form = document.getElementById("myform");
var keyword = document.getElementById("keyword");
form.action = "http://mysite.com/search/"+escape(keyword.value);
return true;
}
</script>
Check out this post on how to enable GET query strings together with segmented urls.
http://codeigniter.com/forums/viewthread/56389/#277621
After enabling that you can use the following method to retrieve the additional variables.
// url = http://example.com/search/?q=text
$this->input->get('q');
This is better because you don't need to change the permitted_uri_chars config setting. You may get "The URI you submitted has disallowed characters" error if you simply put anything the user enters in the URI.
Here is the best solution:
$uri = $_SERVER['REQUEST_URI'];
$pieces = explode("/", $uri);
$uri_3 = $pieces[3];
Thanks erunways!
I don't know much about CodeIgniter, but it's PHP, so shouldn't $_GET still be available to you? You could format your URL the same way Google does: mysite.com/search?q=KEYWORD and pull the data out with $_GET['q'].
Besides, a search form seems like a bad place to use POST; GET is bookmarkable and doesn't imply that something is changing server-side.
Related
Hello I have the following form that collects data entered and later I output it. It works just fine when I use POST but when I use REQUEST like the teacher said to do, the echo $word comes back empty. Any ideas guys? please?
<Form name ="form1" Method ="REQUEST" Action ="">
<Input Type = "text" Value ="<?php echo $word ?>" Name ="word">
<Input Type = "Submit" Name = "Submit1" Value = "Submit">
<?php
if (isset($_POST['Submit1'])) {
$word = $_POST['word'];
$book = $_POST['book'];
}
?>
There is no method called REQUEST on a Form. It should be either GET or POST
Maybe your teacher is confused with the $_REQUEST in PHP.
I think you are looking for GET, not REQUEST.
GET will include the contents of the form submission in the URL itself, so it's suitable for things that should be able to be bookmarked, like search form submissions.
Here's more: http://blog.teamtreehouse.com/the-definitive-guide-to-get-vs-post
Not sure why your teacher asked you this, but "REQUEST" is not a standard HTTP method so I don't think there's any shortcut in PHP to retrieve the data. I found that even using PATCH sometime causes problems.
What you could try is to read the raw data directly using:
file_get_contents("php://input")
There is NO method named REQUEST. You can use only two methods : POST and GET.
If you are using POST as method, you can get the values using only POST OR REQUEST.
If you are using GET as method, you can get the values using only GET OR REQUEST.
For more information please refer to this page: http://www.w3schools.com/tags/ref_httpmethods.asp
I am new to PHP and javascript programming
I have a string that can be "abc" or "aac" or "aaa" etc based on the inputs given by the user. After the user clicks some button(say submit) I want to generate a dynamic link like www.domain.com/abc or www.domain.com/aac based on string and navigate the user to the generated link. Is this possible?
Thank You
You can actually define a function and set it your form action. Then taking the user input it will be really each in the function to use header('location:YOUR_SITE_URL/'.$_GET['user_input']); die; for redirecting the user to desired url.
Hope that helps.
Yes it is possible, you can pass the string variable throw POST or GET when the user click submit
and then echo the link you want with the string congrenated. assuming you want to use php take a look at the example
$adress = "www.domain.com/";
$string = $_POST["get_string"];
$result = $adress + $string;
echo $result;
Possible, using routing. A real world example is how your usernames get to be part of the URL in social sites like Facebook.
What you need is a database of some sort to store the string, and it's matched data (could be an ID, or some identified) to tell the server what to load when that string is received. You'd also need routing code, which parses the entire url in search of that certain segment which should contain the string. This is how routing works in frameworks like CodeIgniter, Connect and Express.
In JS, routers in Connect look like:
app.route('/users/:username',function(username){
//okay! we got the username!
//now we'll look for it in the database if it's there
});
For PHP, here's an article regarding URL parsing.
In PHP :
Use methode in your page and store the variable to $UrlName (for example)
and continued with
echo("<script>location.href = \"www.domain.com/" . $UrlName . "\";</script>");
First in page1.html:
<form method="post" action="page2.php" >
String: <input type="text" name="string" />
<input type="submit" />
</form>
Then in page2.php:
header('location:www.domain.com/string/'.$_POST['string']);
But you should put a .htaccess containing:
Redirect /string/(.+) /page3.php?string=$1 [B,QSA]
And page4.php:
echo $_GET['string'];
dear all, i'm a noob in codeigniter,
i would like to ask for advise, on how to create a search form that would result to url as:
http://domain/class/index/searchvar1/searcvar1val/searchvar2/searchvar2val
the form would be like
<form action="http://domain/class/index">
<input name="searchvar1" value="searchvar1val">
<input name="searchvar2" value="searchvar2val">
<input type="submit">
</form>
what is the best practice for this?
i've googled around including stackoverflow posts, still can't find any solution.
thanks :)
~thisismyfirstposthere
update ::
i would like to emphasize that my objective is to process search variables from the uri string (above), not from post vars; so i think setting the form search to POST is not an option? :)
update (2)
i don't think this can be done out of the box in codeigniter, i'm thinking of client-processing the form vars/vals into the form action in URI format using jQuery.
will post an update here later when done.
taking a look at the user_guide :
$this->uri->assoc_to_uri()
Takes an associative array as input
and generates a URI string from it.
The array keys will be included in the
string. Example:
$array = array('product' => 'shoes', 'size' => 'large', 'color' => 'red');
$str = $this->uri->assoc_to_uri($array);
// Produces: product/shoes/size/large/color/red
and i think if your form is this:
<form action="http://domain/class/index/search">
<input name="product" value="shoes">
<input name="size" value="large">
<input name="color" value="red">
<input type="submit">
</form>
then somewhere in the search controller do this $this->uri->assoc_to_uri($data); IMHO will produce product/shoes/size/large/color/red
hey guys, thanks for replying and discussing, I think imma go with flow:
View --> form --> jquery, on form submit: replace action attribute with form params --> controller with uri string --> rest of the process
the jquery part would be something like this
$("#searchFormID").submit(function(){
// $(this).serialize() outputs param1=value1¶m2=value2 string
// var.replace(regex, string) outputs param1/value1/param2/value2 string
// newact would be http://localhost/class/index/param1/value1/param2/value2
var newact = $(this).attr("action") + "/" + $(this).serialize().replace(/&|=/g,"/");
$(this).attr("action", newact); // or $(this).attr("target", newact);
return true;
});
notes:
add an id attribute to the form -> for the form selector in jquery
use post method in the form (this is default in codeigniter) -> so action url will not be populated with the GET string
You may want to enable query strings and use $_GET. IMO, this is a perfect example what the query string is intended for.
Make sure to change your form to <form method="get" action="http://domain/class/index">
You will then have a query string in your URL like ?searchvar1=value1&searchvar2=value2
You can access parts of the string like this: $this->input->get('searchvar1')
With the method you are currently using, if a user searches for any characters that are not allowed in your $config['permitted_uri_chars'], you will have to do a lot of encoding and decoding yourself to make sure the string is safe/readable in your URL. The CI Input class takes care of this for you, so it is my recommendation.
Another disadvantage to URI segment based search params is that there is no proper way to express an array like ?values[]=one&values[]=two&values[]=three. There are hacks to work around this, but they are all exactly that: hacks. you will eventually run into trouble.
Using $_POST is very tedious and forces the use of form submits for paginated results and links, and also ensures that you cannot link to the search results or use the back button properly.
If you must use this method, simply have the form post to your controller, read the input, and then redirect() to the url that you construct from it. littlechad has the right idea for this method in his answer
// This URL:
http://domain/class/index/searchvar1/searcvar1val/searchvar2/searchvar2val
// With this:
$search = $this->uri->uri_to_assoc();
// Produces this:
array(
'searchvar1' => 'searchvarval1',
'searchvar2' => 'searchvarval2',
);
// And you can use it like this:
$arg1 = $search['searchvar1'];
$arg2 = $search['searchvar2'];
To get TO this url, you can do something like this with your form post (in the controller after post):
$var1 = $this->input->post('searchvar1');
$var2 = $this->input->post('searchvar2');
redirect('searchvar1/'.urlencode($var1).'/searchvar2/'.urlencode($var2));
I'm sure you can see how much more work this is than just using the tried-and-true query string...
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));
How can I let a user access a WordPress protected page with a URL that will submit the password in the form below?
I want to be able to let a user get to a password protected WordPress page without needing to type the password, so when they go to the page, the password is submitted by a POST URL on page load.
This not intended to be secure in any respect; I'll need to hardcode the password in the URL and the PHP. It's just for simplicity for the user.
Edit 4/19/10: As per answers below, it's possible to set a cookie directly to allow users to not have to enter a password. Letting search bots in is best done by detecting the user agent and redirecting, as bots aren't going to deal with cookies.
This is the form (which is WordPress core code):
<form action="http://mydomain.com/wp-pass.php" method="post">
Password: <input name="post_password" type="password" size="20" />
<input type="submit" name="Submit" value="Submit" /></form>
This is wp-pass.php (which is WordPress core code):
<?php
require( dirname(__FILE__) . '/wp-load.php');
if ( get_magic_quotes_gpc() )
$_POST['post_password'] = stripslashes($_POST['post_password']);
setcookie('wp-postpass_' . COOKIEHASH, $_POST['post_password'], time() + 864000, COOKIEPATH);
wp_safe_redirect(wp_get_referer());
?>
Rather than keep appending in the previous answer, I'll try to explain the problem a bit further here.
The way Wordpress passwording works, is:
The original page has a form, which
is sent to wp-pass.php.
wp-pass.php takes the provided
password, puts it in a cookie and
redirects the user back ot the
original page.
The original page checks the cookie
and if the password is correct, it
will show the page.
The problem here is that search engines don't accept cookies. So, you have two options:
Change the code Wordpress uses for passworded content to something that also accepts $_GET variables.
Use cURL to send the cookie using headers, having a separate page search engines can use.
I'd love to expand on the latter answer if you want, but I do wonder; if you're going to give search engines access to passworded content, anyone will have access. Why not just remove the password?
Change $_POST to $_REQUEST everywhere in wp-pass.php.
That code is only looking at the POST variables, not the GET variables in the URL. The REQUEST global contains both the POST, and the GET variables, which is what you want.
There's probably a better way, but I don't know WordPress.
EDIT
The problem is those parameters are in the GET array, not the POST array. So using a regular link with parameters isn't going to work. You can use a form with a hidden field. You can style the submit button to look like a link, if you want.
<form action="http://mydomain.com/wp-pass.php" method="post">
<input name="post_password" type="hidden" value="totally insecure password here" />
<input type="submit" name="Submit" value="Click here to enter your account" />
</form>
If you want to do this without editing WP's core, you can use cURL to simulate POST variables like this:
$ch = curl_init("http://mydomain.com/wp-pass.php");
curl_setopt($ch, CURLOPT_POSTFIELDS, "post_password=mypassword&Submit=Submit");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_exec($ch);
curl_close($ch);
In your comment in this answer:
Actually, now I think I want search
engines to index the page, but then
non-googlebot traffic from that search
link gets redirected to an
introductory page, not a password
protected page. I could use php to
select googlebot traffic to see the
page (and index it), but non-googlebot
traffic could get an http redirect to
an intro page where the content is
user toggled by ajax after they see
the intro?
Beware about this practice. Search engines could interpret this as Cloaking.
Cloaking is a black hat search engine
optimization (SEO) technique in which
the content presented to the search
engine spider is different to that
presented to the user's browser.
I'm not saying they are automatically going to know you're doing this, maybe they'll never will. But it's interesting to know the risks involved.
I would like to know your intents about this practice to know if there are other alternatives that fit your needs.
First I don't know how search engines react to javascript, but could something like this work?
Call mydomain.com/wp-pass.php?post_password=mypassword&Submit=Submit
Add these 2 js function:
function gup( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
function setPassword()
{
var password = gup('post_password');
var passField = document.getElementByName('post_password');
var buttonSubmit = document.getElementByName('Submit');
if(password != "")
{
passField.value = password;
buttonSubmit.Click();
}
}
Add to the body tag, OnLoad="setPassword();"
I dont know how robots react to this...
I think the previous answers are rather more convoluted than they need to be.
If everyone can read the page, do not password protect it. That is by far the most neat solution. What is the password for if everyone and his dog can read the page?
If you really feel the need to make a link that uses POST though, here is the way to do it:
(Sorry if this background is redundant, but it seems like from your question like it is worth mentioning: HTTP supports various methods on URLs; POST is on, GET is another. When you normal-fetch a url, like with an <a> element, you are using the GET method.)
I agree that modifying core files to replace $_POST with $_REQUEST is unnecessary. What you want is a link element that uses the POST method. To do that, make a simple form like so:
<form action="your url" method="POST">
<input type="hidden" value="my_password" name="password"/>
<input type="submit" value="Submit" name="submit">
</form>
You can add style="border: 0; background: transparent;" and so on to the second input to make it look like a normal link if you want. It is a bit cumbersome, but works fine whenever you need to send a link using the POST method.
PS. Using Wireshark to inspect POST variables is a big waste of time. Install the Firebug FF extension and use the net panel. It will massively speed up working these sorts of things out.