I know this is bad form, but we can't change the hidden input name as it is set by SalesForce. I have a form with an input like this:
<input type="hidden" name="00N5000000XXXXX" value="Demo_Account" />
and my PHP to post to them via cURL
$00N5000000XXXXX = $_POST['00N5000000XXXXX'];
which obviously won't work as it has number for a variable name.
When I change the name to:
$Foo = $_POST['00N5000000XXXXX'];
the back end doesn't work because it is expecting the form to submit a value with a name of 00N5000000XXXXX, not Foo or whatever I want to call it.
Obviously, Im not a PHP developer but need some advice on how to get around this.
Thank you.
You don't have to save it to a variable first:
<?php
$transferPostFields = array(
'00N5000000XXXXX'
);
$postFields = array();
foreach ($_POST as $key => $value) {
if (in_array($key, $transferPostFields)) {
$postFields[$key] = $value;
}
}
$curlHandle = curl_init();
curl_setopt_array($curlHandle, array(
CURLOPT_URL => 'http://api.salesforce.com/whatever/urls/they/use',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($postFields)
));
$output = curl_exec($curlHandle);
echo 'The output we received from SalesForce was: ' . $output;
?>
If you want to transfer all post fields, simply change the top part (anything above $curlHandle = curl_init() to:
$postFields = $_POST;
If you don't need to go past your own server first, then simply change your form:
<form method="post" action="http://api.salesforce.com/whatever/urls/they/use">
Related
The company I work for stores contacts into a 1shoppingcart database. We recently signed up for FreshAddress to validate emails before the information is sent to 1shoppingcart.
In order to get this information to 1shoppingcart I stored the name in a session - since it seemed that after the validation script ran that it cleared any form data aside from the email address it was validating, and the remaining hidden values that would normally be in the form as hidden input fields.
Everything transfers over except for the second ar variable. This is how it would normally look inside the form itself:
<input name="ar" type="hidden" id="ar" value="000000">
<input name="ar" type="hidden" id="ar" value="000000">
<input name="ar" type="hidden" id="ar" value="000000">
In order to send the information over I stored what normally would be hidden values in the form as php variables and placed them into an array to be sent over through. Again, the name, e-mail and everything else works except that $ar2 is not being stored for some reason. Here is the code I have:
if($submitPage === true) {
$name = $_SESSION['Name'];
$email = $_POST['Email1'];
$merchId = '000000';
$arTY = 'Url to redirect goes here';
$copyarresponse = '0';
$custom = '0';
$ar1 = '000000';
$ar2 = '000000';
$ar3 = '000000';
$allwMulti = '0';
$visiblefields = 'Name, Email1';
$requiredFields = 'Name, Email';
// where are we posting to?
$url = 'http://www.mcssl.com/app/contactsave.asp';
// what post fields?
$fields = array(
'merchantid' => $merchId,
'ARThankyouURL' => $arTY,
'copyarresponse' => $copyarresponse,
'custom' => $custom,
'ar' => $ar1, $ar2, $ar3,
'allowmulti' => $allwMulti,
'visiblefields' => $visiblefields,
'requiredfields' => $requiredFields,
'Name' => $name,
'Email1' => $email
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
// execute post
$result = curl_exec($ch);
// close connection
curl_close($ch);
session_destroy();
}
The code basically runs when the e-mail that has been validated, returns as safe to send and $submitPage is set to true.
I have looked through this forum and various other sources online as well as contacted 1shoppingcart and fresh address and have had no luck as to what could possibly be preventing the second ar variable from being stored.
Any help would be much appreciated!
How can I post some known queries (hard-coded) together with user input?
For example, if I did not need user input, the query would look like this:
$post = "userid=11&token=abcdef&action=set&name=cf_1&value=UserInput";
But, since I need the value from users, I make something like this:
<form action="submit.php" method="post>
Insert cf_1: <input name='value' type='text'>
<input value="submit" type="submit">
</form>
And the php script:
<?php
$url = someurl;
$post = "userid=11&token=abcdef&action=set&name=cf_1";
$options = array( CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS, $post
);
$ch = curl_init();
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);
?>
However, using the above form and php script, the user input couldn't be submitted to the server
$post .= '&value='.$_POST['value'];
Make sure you do the necessary cleaning of the $_POST value, though.
Here's my problem. A few months ago, I wrote a PHP script to get connected to my account on a website. I was using CURL to get connected and everything was fine. Then, they updated the website and now I am no longer able to get connected. The problem is not with CURL, as I do not get any error from CURL, but it is the website itself which tells me that I am not able.
Here's my script :
<?php
require('simple_html_dom.php');
//Getting the website main page
$url = "http://www.kijiji.ca/h-ville-de-quebec/1700124";
$main = file_get_html($url);
$links = $main -> find('a');
//Finding the login page
foreach($links as $link){
if($link -> innertext == "Ouvrir une session"){
$page = $link;
}
}
$to_go = "http://www.kijiji.ca/".$page->href;
//Getting the login page
$main = file_get_html($to_go);
$form = $main -> find("form");
//Parsing the page for the login form
foreach($form as $f){
if($f -> id == "login-form"){
$cform = $f;
}
}
$form = str_get_html($cform);
//Getting my post data ready
$postdata = "";
$tot = count($form->find("input"));
$count = 0;
/*I've got here a foreach loop to find all the inputs in the form. As there are hidden input for security, I make my script look for all the input and get the value of each, and then add them in my post data. When the name of the input is emailOrNickname or password, I enter my own info there, then it gets added to the post data*/
foreach($form -> find("input") as $input){
$count++;
$postdata .= $input -> name;
$postdata .= "=";
if($input->name == "emailOrNickname"){
$postdata.= "my email address ";
}else if($input->name == "password"){
$postdata.= "my password";
}else{
$postdata .= $input -> value;
}
if($count<$tot){
$postdata .= "&";
}
}
//Getting my curl session
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $to_go,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postdata,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_COOKIESESSION => true,
CURLOPT_COOKIEJAR => 'cookie.txt'
));
$result = curl_exec ($ch);
curl_close ($ch);
echo $result;
?>
CURL nor PHP return any error. In fact, it returns the webpage of the website, but this webpage tells me that there's an error that occurred, as if there was missing some post data.
What do you think can cause that ? Could it be some missing curl_setopts ? I've got no idea, do you have any ?
$form = $main -> find("form") finds first occurrence of element
and that is <form id="SearchForm" action="/b-search.html">
you will need to change that into $form = $main->find('#login-form')
Most likely the problem is that the site (server) checks cookies. This process mainly consists of two phases:
1) When you visit the site first time on some page, e.g. on the login page, the server sets cookies with some data.
2) On each subsequent page visit or POST request the server checks cookies it has set.
So you have to reproduce this process in your script which mean you have to use CURL to get any page from the site, including the login page which should be getting by CURL, not file_get_html.
Furthemore you have to set both CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE options to the same absolute path value ('cookies.txt' is a relative path) on each request. This is necessary in order to enable cookies auto-handling (session maintaining) within entire series of requests (including redirects) the script will perform.
What I am trying to achieve is:
I have a web site to which I have full source code access. The pages in this web site has been created using velocity templates and I have a page with the following form.
<h3>form data</h3>
<form action="$portalPath/test" method="post">
<input type="text" name="text" value="$!self.getTextFromFormData()" />
<input type="submit" />
</form>
Now from another application written in php, I want to make an http request to this page and get a file downloaded. (Which is an html file). To do that, I wrote following code from the other web application :
$url = 'http://localhost/portal/default/test';
$data = array('filename.html');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
But the result shows the html source of the template I access(i.e. test) and not the html file I want to download. What I want to do is to make an http request to auto enter the file name to the form and make the form auto submit the request and process it and get the required html file downloaded as the result. I don't know if this is possible or if possible whether this is the correct way. If this can be done using curl, that's better. Any idea will be highly appreciated.
See: how can I post an external form using PHP?
So, from the referenced URL:
<?php
$url = 'http://localhost/portal/default/test';
$fields = array(
'text'=>urlencode($value_for_field_text),
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
// Initialize curl
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
// Results of post in $result
?>
I have an online gateway which requires an HTML form to be submitted with hidden fields. I need to do this via a PHP script without any HTML forms (I have the data for the hidden fields in a DB)
To do this sending data via GET:
header('Location: http://www.provider.com/process.jsp?id=12345&name=John');
And to do this sending data via POST?
You can't do this using PHP.
As others have said, you could use cURL - but then the PHP code becomes the client rather than the browser.
If you must use POST, then the only way to do it would be to generate the populated form using PHP and use the window.onload hook to call javascript to submit the form.
here is the workaround sample.
function redirect_post($url, array $data)
{
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function closethisasap() {
document.forms["redirectpost"].submit();
}
</script>
</head>
<body onload="closethisasap();">
<form name="redirectpost" method="post" action="<? echo $url; ?>">
<?php
if ( !is_null($data) ) {
foreach ($data as $k => $v) {
echo '<input type="hidden" name="' . $k . '" value="' . $v . '"> ';
}
}
?>
</form>
</body>
</html>
<?php
exit;
}
A better and neater solution would be to use $_SESSION:
Using the session:
$_SESSION['POST'] = $_POST;
and for the redirect header request use:
header('Location: http://www.provider.com/process.jsp?id=12345&name=John', true, 307;)
307 is the http_response_code you can use for the redirection request with submitted POST values.
Another solution if you would like to avoid a curl call and have the browser redirect like normal and mimic a POST call:
save the post and do a temporary redirect:
function post_redirect($url) {
$_SESSION['post_data'] = $_POST;
header('Location: ' . $url);
}
Then always check for the session variable post_data:
if (isset($_SESSION['post_data'])) {
$_POST = $_SESSION['post_data'];
$_SERVER['REQUEST_METHOD'] = 'POST';
unset($_SESSION['post_data']);
}
There will be some missing components such as the apache_request_headers() will not show a POST Content header, etc..
It would involve the cURL PHP extension.
$ch = curl_init('http://www.provider.com/process.jsp');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "id=12345&name=John");
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); // RETURN THE CONTENTS OF THE CALL
$resp = curl_exec($ch);
/**
* Redirect with POST data.
*
* #param string $url URL.
* #param array $post_data POST data. Example: array('foo' => 'var', 'id' => 123)
* #param array $headers Optional. Extra headers to send.
*/
public function redirect_post($url, array $data, array $headers = null) {
$params = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data)
)
);
if (!is_null($headers)) {
$params['http']['header'] = '';
foreach ($headers as $k => $v) {
$params['http']['header'] .= "$k: $v\n";
}
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if ($fp) {
echo #stream_get_contents($fp);
die();
} else {
// Error
throw new Exception("Error loading '$url', $php_errormsg");
}
}
Use curl for this. Google for "curl php post" and you'll find this: http://www.askapache.com/htaccess/sending-post-form-data-with-php-curl.html.
Note that you could also use an array for the CURLOPT_POSTFIELDS option. From php.net docs:
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. This can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.
Your going to need CURL for that task I'm afraid. Nice easy way to do it here: http://davidwalsh.name/execute-http-post-php-curl
Hope that helps
Alternatively, setting a session variable before the redirect and test it in the destination url, can solve this problem for me.
You have to open a socket to the site with fsockopen and simulate a HTTP-Post-Request.
Google will show you many snippets how to simulate the request.
I used the following code to capture POST data that was submitted from form.php and then concatenate it onto a URL to send it BACK to the form for validation corrections. Works like a charm, and in effect converts POST data into GET data.
foreach($_POST as $key => $value) {
$urlArray[] = $key."=".$value;
}
$urlString = implode("&", $urlArray);
echo "Please <a href='form.php?".$urlString."'>go back</a>";
An old post but here is how I handled it. Using newms87's method:
if($action == "redemption")
{
if($redemptionId != "")
{
$results = json_decode($rewards->redeemPoints($redemptionId));
if($results->success == true)
{
$redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml?a=redemptionComplete';
// put results in session and redirect back to same page passing an action paraameter
$_SESSION['post_data'] = json_encode($results);
header("Location:" . $redirectLocation);
exit();
}
}
}
elseif($action == "redemptionComplete")
{
// if data is in session pull it and unset it.
if(isset($_SESSION['post_data']))
{
$results = json_decode($_SESSION['post_data']);
unset($_SESSION['post_data']);
}
// if you got here, you completed the redemption and reloaded the confirmation page. So redirect back to rewards.phtml page.
else
{
$redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml';
header("Location:" . $redirectLocation);
}
}
Yes, you can do this in PHP e.g. in
Silex or Symfony3
using subrequest
$postParams = array(
'email' => $request->get('email'),
'agree_terms' => $request->get('agree_terms'),
);
$subRequest = Request::create('/register', 'POST', $postParams);
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
A workaround wich works perfectly :
In the source page,, start opening a session and assign as many values as you might want.
Then do the relocation with "header" :
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
$_SESSION['val1'] = val1;
...
$_SESSION['valn'] = valn;
header('Location: http//Page-to-redirect-to');
?>
</head>
</html>
And then, in the targe page :
<!DOCTYPE html>
<?php
session_start();
?>
<html>
...
<body>
<?php
if (isset($_SESSION['val1']) && ... && isset($_SESSION['valn'])) {
YOUR CODE HERE based on $_SESSION['val1']...$_SESSION['valn'] values
}
?>
</body>
</html>
No need of Javascript nor JQuery..
Good luck !