Codeigniter pass value from URL - php

Function receives departure date and adult from view page ( it passes value correctly as I have checked doing echo function ) , but from this function I am not able to pass values to another function
public function index()
{
if ($data = $this->input->post('muktinath')) {
$date = $data['departure_on'];
$adult = $data['adult'];
$getNameValue = array(
$date = 'departure_on',
$adult = 'adult',
);
redirect('booking/muktinath/' . $getNameValue);
}
else{
$this->load->view('index');
}
}
This is the function which must receive the value
public function muktinath($getNameValue)
{
echo $getNameValue;
// here value must be shown of departure date and adult passed from above
}

You didn't share the error messages you are getting. Bet there several.
The biggest issue is you cannot put an array as a part of your query string. But the fix is pretty easy.
function index()
{
$data = $this->input->post('muktinath');
if($data)
{
//From your question $data seems to be an array already. Just use that!
redirect('booking/muktinath/'.$data['departure_on'].'/'.$data['adult']);
}
else
{
$this->load->view('index');
}
}
Your function that receives the values is then defined this way.
public function muktinath($date, $name)
{
echo $date . " - " . $name;
}
You will have a problem if $date contains any slashes (/) in what I assume is a date string. The slashes will become part of the URL which, if the date was "7/9/2016" and name was "sandesh" would make this URL.
http://example.com/booking/muktinath/7/9/2016/sandesh
As you can see, it has several more URI segments than you are expecting. This URL would echo "7 - 9" which is not very helpful. You might have to adjust the format of the date while sending it and then reformat it after it is received by muktinath().
By the way, your array declaration is wrong. I think you were trying to make this.
$getNameValue = array(
'departure_on' => $date,
'adult' => $adult
);
The thing is, you have just recreated what $data already was. But you don't need $getNameValue anyway.

Your problem is this:
redirect('booking/muktinath/' . $getNameValue);
Try echoing out booking/muktinath/'.$getNameValue and you will see you have a array to string error. A redirect is a url, but you have got the data from a post. You cannot easily convert from a post to a url and you should not do so either, otherwise what was the point of posting the data in the first place. How do you know the post values do not have illegal url characters in them?
Why redirect at all, just post your form to the correct page in the first place and deal with the post data there?
Either validate, format for url and then use the actual components in your url call NOT like this but something like this....
redirect('booking/muktinath/'.$date.'/'.$adult);
Or better, do not redirect here but call a function (a library or a model or in your controller, that is up to you)
public function muktinath($date, $adult)
{
....
return TRUE/FALSE or whatever you need.
}
And in your controller check the return value to see what to do
if ($this->mylibraryorwhatever->mukinath($date, $adult)
{
// success
redirect('success page'); // or whatever
}
else
{
// fail
.....
}
Hope that helps.

Related

eval() with file_get_contents() .. different results

I am trying to use eval() with json_decode(file_get_contents()) and am getting what appears to be different results when eval'ing and hard-coding the values. Am I just missing something easy?
I am using PHP Version 5.3.24, and do not have the ability to change at the moment. If it is critical to eval() support, I can start the process of getting it changed. I have not found anything that suggests I do not have eval() support in my current PHP implementation.
When I run Example1('key') I get NULL back from the eval() function. When I run Example2('key') I get back an array based on json data that looks like this:
{ key_list: [ { data1_list: [ { subkey1: "data", subkey2: 0 }, .. ], .. ] }
Here is Example1():
function Example1($key) {
$endPoint = 'http:'.'//some.website.com/json/'.$key;
$evalCommand = sprintf('json_decode(file_get_contents("%s"))->%s_list[0];', $endPoint, $key);
echo '$evalCommand = |'.$evalCommand.'|<br />';
$resultsArray = eval($evalCommand);
return $resultsArray;
}
Here is Example2():
function Example2($key) {
$endPoint = 'http:'.'//some.website.com/json/'.$key;
$resultsArray = json_decode(file_get_contents($endPoint))->key_list[0];
return $resultsArray;
}
Rather than using eval, it may be able to use more standard code and using dynamic object access.
The name of the URL is OK, but for the field there is a bit of juggling. This sets the name in $field, but I couldn't get it to do that part and the array part in one line. Here it uses ->$field to get the data and the [0] is on the return...
function Example2($key) {
$endPoint = 'http://some.website.com/json/'.$key;
$field = $key.'_list';
$resultsArray = json_decode(file_get_contents($endPoint))->$field;
return $resultsArray[0];
}

PHP store function in array

i want to store function in array
send the array to another page
then execute it
i already read Can you store a function in a PHP array but still don't know what to do
here's what i try
control.php (it start here)
<?php
function getFirstFunction(){ echo "first function executed"; }
$data = array();
$data[0] = getFirstFunction();
$data[1] = function(){ echo "second function executed"; };
$data[2] = function(){ require_once "additional.php"; };
$data[3] = "my string";
header('Location: view.php?data='.$data);
?>
additional.php
<?php echo "additional included" ?>
view.php
<?php
if( isset($_GET['data']) ){
foreach( $_GET['data'] as $temp ){
if( is_callable($temp) ){
$temp;
}else{
"its not a function";
}
}
}
?>
my error =
Warning: Invalid argument supplied for foreach() in D:\Workspace\Web\latihanns\php\get\view.php on line 4
EDIT
thanks for notify that this code its dangerous.i'm not use this code in real live. i just try to learn store function in array then call it. then i just curious how if i call it on another page. i just simply curious... i make my code look clear and simple here because i afraid if i wrote complicated code, no one will be here or my post will closed as too localized...
If you want to pass anything than string into URL, only option is convert it to string form which is reversible to original types. PHP offers function called serialize() which converts anything to string. After that, you can call unserialize() to convert string back to original data. So you have to change one line in control.php to this:
header('Location: view.php?data='.serialize($data));
In file view.php you have to change one line to this:
foreach( unserialize($_GET['data']) as $temp ){
But you have to fix more things than this. If you have callable variable, you can't invoke function with $variable, but with $variable(). It is good to mention, that in PHP does not matter if you have real function (anonymous function, Closure etc.) in variable, or if variable is simple string with name of exists function.
However you have even another bug in control.php. Code $data[0] = getFirstFunction(); will not pass function getFirstFunction an make it callable, it just calls the function and put its return value to variable. You can define getFirstFunction as anonymouse function like function in $data[1] or just pass it as string like $data[0] = 'getFirstFunction' which will work.
At the end - as anyone mentioned here - IT IS VERY DANGEROUS ans you shouldn't use this on public server.

how arguments are passed to codeigniter method

I have a method in a codeigniter controller which is sometimes called through the url and sometimes called internally from another method of the controller. When I call it internally I pass an array of arguments. Simplified version of method:
(within a controller)
function get_details($args='') {
if (isset($args['first_name']))
{
$first_name = $args['first_name'];
}
else
{
$first_name = $this->uri->segment(3);
}
... do some other stuff ...
}
The method is either called as:
<domain>/<controller>/get_details/abcd/efgh
or from another function of the controller as:
$this->get_details(array('first_name'=>'abcd', 'last_name'=>'efgh'));
I was expecting that when the method was called through the url, isset($args['first_name']) would be false, however it seems that called in this way the argument is there. I tried printing a couple of things and this is what I got:
print_r($args) ----> abcd
echo($args['first_name']) ----> a
echo($args['whatever_index_I_use']) ----> a
It seems like the third parameter of the url is being passed into the method (by codeigniter?), but can't work out why the array indexes seem to be set, all I can think is that php is converting the string to an int, so $args['whatever_index_I_use'], becomes $args[0]??
Not sure if this is a codeigniter thing or me missing a subtlety of php.
Much appreciate anyone who can explain what's going on.
Thanks.
I don't know if this is a bug or a expected behavior, but in the Strings docs there's a comment that show exactly what are you experiencing. If you use a text and index of the string it will return the first char. To avoid it, check first if the argument is an array or a string:
if(is_array($args)) {
echo($args['first_name']);
}
To complete #SérgioMichels answer, the reason for that is because PHP is expecting an integer as the given index. When you give it a string, PHP will cast the string into an integer, and assuming that the string does not start with a number, type casting will return 0 otherwise, it will return the leading number.
$str = 'abcdefghi';
var_dump($str['no_number']); // Outputs: string(1) "a"
var_dump($str['3something']); // Outputs: string(1) "d"
To specifically answer your question - this will solve your bug:
function get_details($args='')
{
if (is_array($args))
{
$first_name = $args['first_name'];
}
else
{
$first_name = $this->uri->segment(3);
}
... do some other stuff ...
}
But you have some issues with your code. Firstly you state that you call the method as
<domain>/<controller>/get_details/abcd/efgh
but you dont accept the "efgh" variable in your controller. To do this, you need to change the function to
function get_details($first, $last)
in which case you can now just call the function as
$this->get_details('abcd', 'efgh');
and now you dont even need to test for arrays etc, which is a better solution IMO.
If you decide to stick with arrays, change:
$first_name = $this->uri->segment(3);
to
$first_name = $args;
because by definition - $args IS The 3rd URI segment.

How to Pass Class Variables in a Function Parameter

The main function of the example class uses the reusableFunction twice with different data and attempts to send that data to a different instance variable ($this->result1container and $this->result2container) in each case, but the data doesn't get into the instance variables.
I could get it to work by making reusableFunction into two different functions, one with array_push($this->result1container, $resultdata) and the other with array_push($this->result2container, $resultdata), but I am trying to find a solution that doesn't require me to duplicate the code.
My solution was to try to pass the name of the result container into the function, but no go. Does somebody know a way I could get this to work?
Example Code:
Class Example {
private $result1container = array();
private $result2container = array();
function __construct() {
;
}
function main($data1, $data2) {
$this->reusableFunction($data1, $this->result1container);
$this->reusableFunction($data2, $this->result2container);
}
function reusableFunction($data, $resultcontainer) {
$resultdata = $data + 17;
// PROBLEM HERE - $resultcontainer is apparently not equal to
// $this->result1container or $this->result2container when I
// try to pass them in through the parameter.
array_push($resultcontainer, $resultdata);
}
function getResults() {
return array(
"Container 1" => $this->result1container,
"Container 2" => $this->result2container);
}
}
(If this is a duplicate of a question, I apologize and will happily learn the answer from that question if somebody would be kind enough to point me there. My research didn't turn up any answers, but this might just be because I didn't know the right question to be searching for)
It looks to me like you want to be passing by reference:
function reusableFunction($data, &$resultcontainer) {
...
If you don't pass by reference with the & then you are just making a local copy of the variable inside reuseableFunction .
You are changing the copy, not the original. Alias the original Array by referenceDocs:
function reusableFunction($data, &$resultcontainer) {
# ^
And that should do the job. Alternatively, return the changed Array and assign it to the object member it belongs to (as for re-useability and to keep things apart if the real functionality is doing merely the push only).
Additionally
array_push($resultcontainer, $resultdata);
can be written as
$resultcontainer[] = $resultdata;
But that's just really FYI.
You may pass the attributes name as a String to the method like this:
function reusableFunction($data, $resultcontainer) {
$resultdata = $data + 17;
array_push($this->{$resultcontainer}, $resultdata);
}
//..somewhere else..
$this->reusableFunction($data, 'result2Container')
Some php experts wrote some texts about "why you shouldn't use byReference in php".
Another solution would be to define the containers as an array. Then you can pass an "key" to the method that is used to store the result in the array. Like this:
private $results = array();
function reusableFunction($data, $resIdx) {
$resultdata = $data + 17;
array_push($this->$results[$resIdx], $resultdata);
}
//..somewhere else..
$this->reusableFunction($data, 'result2Container');
//..or pass a number as index..
$this->reusableFunction($data, 1);

PHP Convert String to an array or object if it represents one

I have a function that prints information to the page, it does this because it checks if that value exists every time and outputs an error if it doesn't. Due to the unknown nature of what is being sent to this function it always arrives as a string, I can't change this.
Is it possible for this function to interpret strings such as "array[0]" and "object.something" and return that value instead of looking for the value as an index in $this
E.g.
private array = array("stuff");
$this->printValue("string");
$this->printValue("array[0]");
$this->printValue("object.name"); //Some specified object
public function printValue($key) {
if(isset($this->$key)) {
echo $this->$key;
} else {
die($key.' doesn\'t exist');
}
}
Would echo:
string
stuff
thename
Maybe this example helps:
class Example {
public function __construct() {
$this->foo = array(9, 8, 7);
$this->bar = (object) array('attr1' => 'val1', 'attr2' => 'val2');
$this->baz = 'abcde';
}
public function printValue($key) {
echo eval('return $this->' . $key . ';') . "\n";
}
}
$example = new Example();
$example->printValue('foo[0]'); # prints 9
$example->printValue('bar->attr1'); # prints val1
$example->printValue('baz'); # prints abcde
However, take into account that eval poses security risks because it can execute any PHP code and it may cause fatal errors. Using variable variables is safer, though not as general. Anyway, the input of these risky functions must be always validated.
I think the bigger question is, are you trying to use array[0] as an index for something you're trying to reference? I'm assuming so, otherwise you could access the data from those items listed. So, if you ARE wanting to use the array[0] as an index-identifier, then you could do something like:
private data_array['array[0]'] = "stuff";
$this->printValue(data_array['array[0]']);
im not sure but i think you want $pie = print_r($var,true) it sends the string as a return value not printing out

Categories