passing post array to function - php

How can i pass a post array to a functing then pull out the params i.e
so i am posting the following.
url=http%3A%2F%2Fwww.facebook.com%2Ftest&userId=680410999&location=Cardiff&lang=en_US&social=facebook
can i grab it like this from the function????
function login($_POST){
//then output the var her.
$_POST['url']; etc
}
this is to save me doing the following in my ajax.php file
function login($_POST['url'],$_POST['userId'],$_POST['location'],$_POST['lang']){
}
any help pls

First you should use $_GET and not $_POST. Second you don't need to call your function parameter as $_GET. You can do this:
function login($array)
{
// do stuff with array
}
and then call the function in this way:
login($_GET);
An additional suggest is to read the following quote and that is the difference of actual parameters towards formal parameters:
Formal parameters are the parameters as they are known in the function
definition. Actual parameters (also known as arguments) are what are
passed by the caller.

The other answers you have got should solve this problem for you.
Just some more advice, remember to clean any $_POST and $_GET data that you are using in your code.
For example, if you are using it in a database query then you will need to use mysql_real_escape_string(); and if you are echo'ing the data then use htmlentities();

If I unserstand you correctly you want a function that you call and pass it an array (in your case the $_POST or $_GET array) as a parameter.
So your function would look something like this:
// not sure what you're doing with your login options but here's an example of getting them out of the array and putting them in variables - using the url as an example here...
var url;
function login($loginOptions) {
// set the url from the array
url = $loginOptions["url"];
// do the same for all your other variable...
}
Then you would call your function like so:
login($_POST); // or $_login($_GET); depending on what you're using
And that's it!

I think what you mean is parsing array to a function for this I will tell you to use a function and connected it with SESSION as this below. You can use the $_GET[$var] to retrieve the variable but it's quite hard to be handled by the method get, you can use the method $_POST and combine it with session to save the data , I will explain how to collaborate the session each page so that you can easily retrieve the variable you wanted.
Here's the code :
<?php
session_start();
if(isset ($_POST['postedit']))
{
$_SESSION['url'] = $_POST['urlsend'];
header("location:dua.php");
}
?>
<html>
<body>
<form action="satu.php" method="POST">
Name : <input type="text" name="urlsend"> <br> <br>
<input type="submit" name="postedit" value="SEND DATA">
</form>
</body>
</html>
<?php
session_start();
if(isset ($_SESSION['url']))
{
//if data empty then will be redirected to the previous page
echo $_SESSION['url'];
}
?>
I created with dynamic data even you can choose to use this method or other method. I hope you can understand.

Related

PHP (Yii) Passing variable to controlle via form

I have a variable in my view $models which I want to pass to my controller for a function which I'm calling using a submit button.
<?php echo CHtml::beginForm('', 'post');?>
<fieldset>
<?php echo CHtml::submitButton('Confirm', array('name'=>'confirm', 'class'=>'btn btn-danger')); ?>
</fieldset>
<?php echo CHtml::endForm(); ?>
how do I access the $models variable from the function in the controller.
I'm not entirely sure how this works and I would have thought I could just use $_POST['models'] but it's saying it's an undefined variable (although I can var_dump on the page and it's definitely not) so I think i'm just trying to access it incorrectly or not submitting it correctly.
This is a html form submission and php syntax problem, but not yii-specific.
Whatever framework you use, even in plain static html, the basic idea of form submission is the same: if you want to send data to a page with a form, you need to put that data in your form, either as a form input the end-user can enter or select (text inputs, dragdown boxes, radios and checkboxes), or as a hidden input. Page2 doesn't care if $models was set on Page1. You need to send the data to Page2.
In PHP, you can't display an array with echo $arrayVar.
For your specific problem, I assume $models is an array of models. Do NOT pass the whole models' definition in your form, just pass their primary key ids. On your next action, just fetch back those models with YourMode::model()->findByPk(). I think you could do this two ways:
<?php
// Idea 1 (untested code)
// Convert an array of ids to a string
$tmp = array();
foreach($models as $model){
$tmp[] = $model->yourPrimaryKey;
}
echo '<input type="hidden" name="whateveryourparamis" value="'.CHtml::encode( implode('|',$tmp)).'">';
// $whateveryourparamis will be a string like: "47|388|638|877". Use explode() to convert it to an array
// Your could also use json_encode/json_decode instead of implode/explode
// Idea 2 (untested code)
// Pass an array of ids (yeah, this is possible)
foreach($models as $model){
echo '<input type="hidden" name="whateveryourparamis[]" value="'.CHtml::encode($model->yourPrimaryKey).'">';
}
// $whateveryourparamis will be an array like: array(47, 388, 638, 877)
?>
I suppose this ain't the best way to achieve what you want, but you can always access the controller through:
$controller = Yii::app()->controller;
And then do with it whatever you want, for storing a variable in your controller, you probably will have to add a variable to your class.
Another variant would be to use CStatePersister http://www.yiiframework.com/doc/api/1.1/CStatePersister or you could also directly write in to $_SESSION..
From what you write, I suppose you should use Sessions for storing that data.

Why doesnt my <form> work with REQUEST but works with POST

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

PHP going back and keeping arguments

I have used this page http://www.binarytides.com/blog/php-redirect-go-back-to-previous-page/
to go back
but from
http://page.co/test.php?item=26
I post something to post.php and then call the php Go back function but I go back to
http://page.co/test.php
losing the argument path, any idea?
In Your form fill in the query string to the action attribute, like this:
<form action="?item=26" name="myform">
...
</form>
and after the submission Your HTTP_REFERER will contain this query string so redirect to it will be successfull...
EDIT: If the form is on the page post.php, it is enough to use action="?item=26" - of course You can and should use PHP to write down the number/ID of item from whenever it may come...
Lets say Your item ID is stored in the variable $item_id - then Your action will look like this: action="?item=<?php echo $item_id; ?>".
You should use sessions for stuff like this. Set a session when posting the data and you're set.

How to set $_GET variable

How do i set the variable that the $_GET function will be able to use, w/o submitting a form with action = GET?
$_GET contains the keys / values that are passed to your script in the URL.
If you have the following URL :
http://www.example.com/test.php?a=10&b=plop
Then $_GET will contain :
array
'a' => string '10' (length=2)
'b' => string 'plop' (length=4)
Of course, as $_GET is not read-only, you could also set some values from your PHP code, if needed :
$_GET['my_value'] = 'test';
But this doesn't seem like good practice, as $_GET is supposed to contain data from the URL requested by the client.
You can create a link , having get variable in href.
<a href="www.site.com/hello?getVar=value" >...</a>
You can use GET variables in the action parameter of your form element. Example:
<form method="post" action="script.php?foo=bar">
<input name="quu" ... />
...
</form>
This will give you foo as a GET variable and quu as a POST variable.
One way to set the $_GET variable is to parse the URL using parse_url()
and then parse the $query string using parse_str(), which sets the variables into the $_GET global.
This approach is useful,
if you want to test GET parameter handling without making actual queries, e.g. for testing the incoming parameters for existence and input filtering and sanitizing of incoming vars.
and when you don't want to construct the array manually each time, but use the normal URL
function setGetRequest($url)
{
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $_GET);
}
$url = 'http://www.example.com/test.php?a=10&b=plop';
setGetRequest($url);
var_dump($_GET);
Result: $_GET contains
array (
'a' => string '10' (length=2)
'b' => string 'plop' (length=4)
)
If you want to fake a $_GET (or a $_POST) when including a file, you can use it like you would use any other var, like that:
$_GET['key'] = 'any get value you want';
include('your_other_file.php');
note: i must add that while this is ok for dev/test/debug, it is considered bad programming and i wouldn't recommend using this method in prod. it would be better to pass the processed values to the function/class instead of having it read the $_GET directly.
The $_GET variable is populated from the parameters set in the URL. From the URL http://example.com/test.php?foo=bar&baz=buzz you can get $_GET['foo'] and $_GET['baz']. So to set these variables, you only have to make a link to that URL.
simply write basic code to set get method value in php
Syntax :- $_GET['< get method variable name>']='';
Ex :- $_GET['send']='invoice';
You could use the following code to redirect your client to a script with the _GET variables attached.
header("Location: examplepage.php?var1=value&var2=value");
die();
This will cause the script to redirect, make sure the die(); is kept in there, or they may not redirect.
For the form, use:
<form name="form1" action="" method="get">
and for getting the value, use the get method as follows:
$value = $_GET['name_to_send_using_get'];
As #Gaurav and #Sander Marechal said, it's possible to add directly at the end of the URL the GET parameters to send to the web page. It works in the majority of cases. But unfortunately, there is an issue with that because an URL cannot accept any character. Some special characters have to be properly encoded to get a valid URL.
Suppose you have an index.php and you want to set a with the value &b= which contains special characters. When I submit the form of the following code, the URL sent is index.php?a=&b= and PHP prints Array ( [a] => [b] => ). So, PHP believes there is two parameters but I only want the parameter a.
You may also notice that the form method is set to POST because if you set it to GET the parameters at the end of the action URL will be ignored. For more details about that see this #Arjan's answer.
<form action="index.php?a=&b=" method="post">
<input type="submit">
</form>
<?php print_r($_GET); ?>
One solution could be to use the PHP function urlencode. But, as you can see in the following code it's not really convenient to use, especially if you have many parameters to encode. When, I submit this form the URL sent is index.php?a=%26b%3D and PHP prints Array ( [a] => &b= ) as expected.
<form action="index.php?a=<?=urlencode("&b=")?>" method="post">
<input type="submit">
</form>
<?php print_r($_GET); ?>
But, instead of urlencode function I recommend using hidden input. Thanks to this tag you can send GET parameters dynamically set by PHP. Besides, these parameters are automatically encoded with the URL standard. And you don't need to use & to separate several parameters: use one input to set one parameter. When, I submit this form the URL sent is index.php?a=%26b%3D and PHP prints Array ( [a] => &b= ) as expected.
<form action="" method="get">
<input type="hidden" name="a" value="<?php echo "&b="; ?>">
<input type="submit">
</form>
<?php print_r($_GET); ?>
I know this is an old thread, but I wanted to post my 2 cents...
Using Javascript you can achieve this without using $_POST, and thus avoid reloading the page..
<script>
function ButtonPressed()
{
window.location='index.php?view=next'; //this will set $_GET['view']='next'
}
</script>
<button type='button' onClick='ButtonPressed()'>Click me!</button>
<?PHP
if(isset($_GET['next']))
{
echo "This will display after pressing the 'Click Me' button!";
}
?>

Simple Search: Passing Form Variable to URI Using CodeIgniter

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.

Categories