Extract URL value with CakePHP (params) - php

I know that CakePHP params easily extracts values from an URL like this one:
http://www.example.com/tester/retrieve_test/good/1/accepted/active
I need to extract values from an URL like this:
http://www.example.com/tester/retrieve_test?status=200&id=1yOhjvRQBgY
I only need the value from this id:
id=1yOhjvRQBgY
I know that in normal PHP $_GET will retrieve this easally, bhut I cant get it to insert the value into my DB, i used this code:
$html->input('Listing/vt_tour', array('value'=>$_GET["id"], 'type'=>'hidden'))
Any ideas guys?

Use this way
echo $this->params['url']['id'];
it's here on cakephp manual http://book.cakephp.org/1.3/en/The-Manual/Developing-with-CakePHP/Controllers.html#the-parameters-attribute-params

You didn't specify the cake version you are using. please always do so. not mentioning it will get you lots of false answers because lots of things change during versions.
if you are using the latest 2.3.0 for example you can use the newly added query method:
$id = $this->request->query('id'); // clean access using getter method
in your controller.
http://book.cakephp.org/2.0/en/controllers/request-response.html#CakeRequest::query
but the old ways also work:
$id = $this->request->params->url['id']; // property access
$id = $this->request->params[url]['id']; // array access
you cannot use named since
$id = $this->request->params['named']['id'] // WRONG
would require your url to be www.example.com/tester/retrieve_test/good/id:012345.
so the answer of havelock is incorrect
then pass your id on to the form defaults - or in your case directly to the save statement after the form submitted (no need to use a hidden field here).
$this->request->data['Listing']['vt_tour'] = $id;
//save
if you really need/want to pass it on to the form, use the else block of $this->request->is(post):
if ($this->request->is(post)) {
//validate and save here
} else {
$this->request->data['Listing']['vt_tour'] = $id;
}

Alternatively you could also use the so called named parameters
$id = $this->params['named']['id'];

Related

How to get different parts of url using php?

I have coded so that i get the following url upon clicking a certain link.
.../project/auction/auction.php?user=ernie6?auc=1
I just wondered what is best way to "get" the following details "ernie6" (as the username) and "1" this being the first auction. Moreover what is the "general rule" to extract data of the form "y=z?a=b?c=d?..."?
Thanks a lot.
It should be & instead of the second/third/etc ?
user=ernie6&auc=1
and then you can refer to your $_GET global array
To see its full content you can do a var_dump($_GET) or get the specific values by:
$user = $_GET['user'];
$auc = $_GET['auc'];
Your URL is not correct, if you want to provide arguments you need to start with a ? and then separate each arguments by a &
Then on your PHP script auction.php you retrieve each arguments like this:
$user = $_GET['user'];
The $_GET variable is a global array containing every parameters provided on the URL. More info on the query string here : http://en.wikipedia.org/wiki/Query_string
EDIT: If you try to retrieve an argument that does not exist you will have PHP warnings or errors. To avoid these it is better to ensure the index exists in the array before retrieving. Something like this would be better:
if(isset($_GET) && isset($_GET['user'])) {
$user = $_GET['user'];
}
For that url, $_GET['user'] and $_GET['auc'] would be defined in the scope of your script if you properly formatted the link (begin get data with ?, separate variables with &).
Assumimg that you are using GET or POST, you can simply get the values like so:
$user = $_POST['user'];
$auc = $_POST['auc'];
or
$user = $_GET['user'];
$auc = $_GET['auc'];
You might find the following documentation useful:
http://php.net/manual/en/reserved.variables.get.php
http://php.net/manual/en/reserved.variables.post.php

How to store search conditions with php and Codeigniter?

I have small problem.
I've coded a full website in php using CodeIgniter framework. One of my modules is search module, it contains text input with keyword and three select lists with filtering criterias.
That's ok, when I'm searching something - result's listing pagination is done via URL like that:
mysite.com/$keyword/$criteria1/$criteria2/$criteria3/$offset
works like a charm.
But when I'm entering into one of my images (it's image gallery) I want to have an option to go into NEXT and PREVIOUS image from my search results - the ones which I entered this image from.
I'm solving this case now in this way - I have session table called 'search_conditions' and I'm storing values of keyword and my three criterias there, but that's quite not comfortable, because why if someone opens second window and search something else there?
Then all of his searches in another windows or tabs are getting the same criteria - because with every new search, user overwrite the session value.
My next and previous functions:
public function next($count)
{
$search = $this->session->userdata('search_conditions'); //getting session table and overwriting it
$catid = isset($search['catid'])?$search['catid']:'0';
$brandid = isset($search['brandid'])?$search['brandid']:'0';
$prodid = isset($search['prodid'])?$search['prodid']:'0';
$keyword = isset($search['keyword'])?$search['keyword']:'';
$res = $this->search_model->main_search($keyword, $catid, $brandid, $prodid, $count, 1);
}
public function previous($count)
{
$search = $this->session->userdata('search_conditions');
$catid = isset($search['catid'])?$search['catid']:'0';
$brandid = isset($search['brandid'])?$search['brandid']:'0';
$prodid = isset($search['prodid'])?$search['prodid']:'0';
$keyword = isset($search['keyword'])?$search['keyword']:'';
$res = $this->search_model->main_search($keyword, $catid, $brandid, $prodid, $count-2, 1);
}
Can you recommend me some other, more comfortable solution, because this seems not to be good...
: )
Thank you!
Add an index to the $search_conditions variable:
$search_conditions[1]['catid']
$search_conditions[1]['brandid']
...
then refer to it with a controller's or config variable. This way you can allow one session to store multiple search conditions.
But I would recommend you drop storing the search condition in session. Instead, just pass it with the URI. Session data, in the case you describe, work as an intermediary; you don't need it. Use the Pagination Class and pass the search page number, not the direction (next or previous) to the URI.
Do not worry that the URI may look ugly - it only depends on what user searches for, and it's still friendly to share. Your only concern is if the GET string does not extend the limited length.
Pull the segments from the URI in your next() and previous() functions. Use the codeigniter URL helper. That should allow you to pass the different search criterion as variables to the next page, this would also remove your need to use the session.

How to pick up the database name and table name from the URL in PHP?

I am new to PHP.
I need a help regarding the methods of extracting DB name and table name from the given URL name.
For example, let's say, I have an URL like the one below:
/test.php?db=...&table=.../
How to extract the DB name and table name from this URL using PHP and use the result for other query purposes.
If you mean how to parse an existing URL for it's parameters:
parse_url() and parse_str() will help you strip the components of the url. You will primarily be looking at the following
$elements = parse_url($url);
$kvps = $elements->query;
$db = parse_str($kvps['db']);
$table = parse_str($kvps['table']);
But, if you mean how to GET variables from the current page before render:
<?php
$dbname = $_GET['db'];
$tablename = $_GET['table'];
?>
And yea, there are major security risks involved in opening up 'direct' access to your database this way. Best to obfuscate / encapsulate / wrap your functions in tasks like index.php&addUser=tim instead of index.php&insert=tim&db=boofar&table=users&dbuser=root&dbpassword=secure.
If you're just learning, what you're doing is fine, as long as you realize why it's wrong. If you're coding for production, you really need an alternate solution.
There are two ways to pass variables or data to another page.
GET (via the URL)
and
POST (usually a form submission)
You can alway get via
$_GET
http://php.net/manual/en/reserved.variables.get.php
or
$_POST
http://nl.php.net/manual/en/reserved.variables.post.php

PHP GET variables pass along while browsing

My site is organized into topics. Users can switch between topics on any page, at any time. I would like to be able to pass this topic along from page to page. I am guessing this should be done in a php post or get variable. I can grab the topic from the post or get variable and then run the rest of my site. However, this seems like it requires a form on every page to pass along this variable. As of now, the only way I have passed post or get variables was from forms on the previous page. I have never passed along these variables over several pages. Will I need a form on every page to pass these variables? Also, is this the standard way of doing this?
You should probably use GET, because it sounds like you're just trying to display different information, and POST is supposed to be for performing changes or actions.
If you decide to use GET variables, all you have to do is append them to the end of the link's href:
MORE BANANAS
the least overhead method of doing this would be to add some javascript that sets a cookie each time someone navigates to a new topic. This would assume you can select somehow all links that match topics (presumably trough classes)
A better method - because of compatibility,reliability and overhead - but not necessarily feasible, if a large number of links needs changing, is to use GET requests, as another poster suggested
You can create a helper function to generate your anchor tags and just append any existing query string to it, so instead of this:
Foobar
you would do this:
<?php echo anchor('page2.php','Foobar'); ?>
where your function would look like this:
/**
* Function creates an anchor tag and optionally
* appends an existing query string
* #param string $url
* #param string $txt
* #param bool $attach_qs Whether or not to follow a query string
*/
function anchor($url, $txt, $attach_qs = true)
{
$qs = '';
if ($attach_qs === true) {
$qs = (!empty($_SERVER['QUERY_STRING'])) ? '?' . $_SERVER['QUERY_STRING'] : '';
}
return '' . $txt . '';
}
Kolink's suggestion of placing the topic in via a PHP echo statement for every URL would certainly work. There is however, another option that I am surprised hasn't come up yet.
You could use PHPs Session Manager to store the variable. It is similar to using cookies; however, it is only temporary (limited to the session). Where a cookie can be persistent over multiple sessions.
<?php
// use this code before the page is generated, before the topic is decided.
session_start();
if (isset($_GET['topic']) && $_GET['topic'] != $_SESSION['topic']) {
// GET['topic'] is set, session variable does not match
// you may want to sanitize or limit what can be passed via ?topic=
$_SESSION['topic'] = $_GET['topic'];
} else if (isset($_SESSION['topic'])) {
// Session topic is not empty, run code to display appropriate content
} else {
// No topic is set, display default
}
?>
It's by no means the only solution, but it does give you an extra option.

How to add a $userid onto an Html Link

Is it possible once I have retrieved a userid from a MySql database, for example, $userID, to then use that as a parameter in a HTML link, for example;
<href="http://www.site.com/?110938">
Thanks.
In PHP, anything you echo is sent to the browser. So you can simply echo that variable.
echo $userID;
Or to put it in the link:
<href="http://www.site.com/?<?php echo $userID ?>">
Of course that means you're trusting that $userID will contain valid data (and not some malformed HTML attempting to break your site and ruin your user's lives).
If it should always be a number, you can keep out potential bad data by forcing it to be an integer:
<href="http://www.site.com/?<?php echo (int) $userID ?>">
I believe what you are looking to do is use the GET method of retrieving data.
The GET method (as opposed to post) pulls all of the parameters out of the URL. For example, lets take a google maps search url:
http://maps.google.com/maps?q=Empire+State+Building,+NY&hl=en
Let us break down this URL:
http://maps.google.com/ - this is the location of the script
maps? - Maps is the name of the file that contains the script (if
they are using PHP); notice, there is a ? in the URL, indicating
that the GET method is being used. All information after the ?
pertains to the GET data.
q=Empire+State+Building,+NY& - this portion is the first GET
variable. They have decided to use the letter q as the name of
their GET variable, and the value is Empire+State+Building,+NY. The
& indicates that another variable will be specified.
hl=en - this is the second variable in their query.
If they were to use PHP to read these parameters, they would use the following code:
$var1 = $_GET['q']; //Has value Empire+State+Building,+NY as string
$vars = $_GET['hl']; //Has value en as string
If you wanted to have your user's ID be in the URL, and use that to interact with the database, the easiest way would be to use GET, such that your URL would look like this:
www.example.com/example.php?id=45828
Then in your script, you would use the following code to access that data and query the database with it:
$userid = $_GET['id'];
$query = "SELECT * FROM users WHERE userid=$userid;";
$query = mysql_escape_string( $query );
mysql_query( $query );
just pass the variable like <href="http://www.site.com/?var_name=<?php echo $userID;?>">

Categories