简体   繁体   中英

PHP: Run query based on the URL?

Hopefully I can explain this properly...

I have a search engine script that runs off PHP and uses API's from various places. I would like to be able to generate query results ($q) based on the URL.

eg If a user goes to domain.com/stackoverflow I would like the site to automatically generate a query that runs a search for "stackoverflow". ie $q = stackoverflow.

I suppose this is the opposite of the header function in PHP, where instead of putting information into the URL bar I want to take information out.

I realise there may be some editing to .htaccess to make this work, but is it possible? It would also mean being able to handle conflicts with whatever might already sit on the site, eg I would need to define that domain.com/login is reserved and to not run a query search on that, etc.

This is done through the $_GET array.

Imagine this is your url: http://www.website.com/?foo=bar then $_GET['foo'] will be bar .

If you want to do something like domain.com/stackoverflow you will need to use htaccess to rewrite that url to something like domain.com/?domain=stackoverflow and then you can access it through $_GET['domain'] .

If I understood well, you could use the function parse_url(). Here you have the documentation .

There are several ways of doing what you want.

  1. You should use .htaccess to ModRewrite it in a way so that example.com/?q=whatver will become example.com/whatever , and then use PHP's $_GET superglobal . to get the information normally.
  2. You could use PHP's parse_url() function , get the path and use it ( $parsed_url['path'] ).

Good luck:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM