I am trying to auto fill and submit the form using cURL, the code is here but it is doing absolutely nothing,
<?php
$post_data['countryID'] = '162';
$post_data['autocomplete'] = 'Assam, Karimganj';
$post_data['state'] = '3007';
$post_data['city'] = '60695';
$post_data['countryStateCityCase'] = '2';
$post_data['usesAutoComplete'] = '1';
$post_data['categoryParent'] = '185';
$post_data['categoryChild'] = '219';
$post_data['listing_type'] = '2';
$post_data['title'] = 'Title goes here';
$post_data['currency_typeC'] = '13';
$post_data['priceC'] = '2500';
$post_data['description']= 'Descriptio goes hereDescriptio goes hereDescriptio goes hereDescriptio goes here';
$post_data['email']= 'olx#test.com';
$post_data['ad_language_id']= '1';
$post_data['identity']= '1';
$post_data['imageQty']= '0';
$post_data['phone']= '03311234567';
$post_data['bddisclaimer']= '0';
$post_data['security_code']= 'undefined';
$post_data['captchaKey']= 'undefined';
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
$post_string = implode ('&', $post_items);
echo $post_string;
$curl_connection =
curl_init('http://www.olx.in/posting.php?src=8');
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($curl_connection);
echo $result;
print_r(curl_getinfo($curl_connection));
echo curl_errno($curl_connection) . '-' .
curl_error($curl_connection);
curl_close($curl_connection);
?>
all the fields are properly filled but the nothing is output and i am receiving no confirmation email at all but manually it is working fine, could somebody help me out ?
The first reason that hits my head is that you are not doing a percent-encoding while building the content of the HTTP POST request. You can use urlencode(..) function to encode the value of the key-value pair.
Replace
$post_items[] = $key . '=' . $value;
with:
$post_items[] = $key . '=' . urlencode($value);
Related
I wrote my module by send Opencart's orders to my CRM. But in this case I set event by post.add but is not OK because when client refresh their shopping cart, my order is still adding in CRM and by this reason i've got duplicate same order. I decided set post.order.history.add event but in this case I've got 504 gateway timeout. What I can do in this situation?
Note, my CRM and shop on same VPS.
This is my module:
public function check_phone($number)
{
//bla bla bla
$retunr $number;
}
public function on_order_add($order_id)
{
$this->load->model('checkout/order');
$value = $this->model_checkout_order->getOrder($order_id);
//prepare loggin
$url_login = "*********/login/enter/";
$login = array();
$login["username"] = "username";
$login["password"] = "password";
$login["remember"] = "on";
$login["act"] = "act";
//login
$curl = curl_init($url_login);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($login));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($curl, CURLOPT_COOKIEFILE, "cookie.txt"); //saved cookies
curl_setopt($curl, CURLOPT_USERAGENT,
'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0');
$response = (curl_exec($curl));
curl_close($curl);
//prepare order
$orders = array();
$order_id = $order_id;
$url = "******/orders/api/";
$orders["act"] = "add_packaging_order";
//ORDER
$orders["id_user_add"] = 21; //system by default
$orders["date_calendar"] = date("Y-m-d");
$orders["timepicker"] = date("H:i:s");
if ($value["payment_code"] == "cod" || $value["payment_code"] == "cheque")
$orders["inlineRadioOptions"] = "cash"; // НАЛ ИЛИ БЕЗНАЛ
else
$orders["inlineRadioOptions"] = "cashless";
if (stristr($value["email"], 'localhost') !== false)
$value["email"] = " Не указано\n";
$orders["status"] = 1;
//ORDER_END
//auto
if ($value["shipping_code"] == "flat.flat") {
$orders["show_next_auto"] = "on";
$orders["autoname"] = "Для доставки упаковки за 99грн";
$orders["summary_auto"] = 1;
$orders["price_auto_agree"] = 0;
}
if ($value["shipping_code"] == "free.free") {
$orders["show_next_auto"] = "on";
$orders["autoname"] = "Для бесплатной доставки упаковки";
$orders["summary_auto"] = 1;
$orders["price_auto_agree"] = 0;
}
//end auto
//start clients
$orders["name_clients[]"] = $value["lastname"] . " " . $value["firstname"];
$orders["sendsms"] = 0;
$orders["signature"] = "=======";
$orders["number_order"] = $order_id;
$orders["phones[]"] = $this->check_phone($value["telephone"]);
//end clients
$custom_fields = "";
//address
if (isset($value["custom_field"]))
$custom_data = ($value["custom_field"]);
if (isset($custom_data[17]))
$orders["company_name"] = $custom_data[17];
if (isset($custom_data[4]))
$orders["addres[]"] = $custom_data[4];
else
if (isset($custom_data[8]) || isset($custom_data[9]) || isset($custom_data[12])) {
$orders["addres[]"] = $custom_data[8] . ", " . $custom_data[9] . " склад№" . $custom_data[12];
} else
$orders["addres[]"] = "Не указан";
if (isset($custom_data[18]))
$custom_fields .= "\nЕГРПОУ:" . $custom_data[18] . "\n";
if (isset($custom_data[19]))
$custom_fields .= "\nНомер свидетельства плательщика НДС :" . $custom_data[19] .
"\n";
$orders["addres_counter"] = "2";
if (isset($custom_data[16]))
if ($custom_data[16] == 26)
$custom_fields .= "\nЮридическое лицо\n";
else
$custom_fields .= "\Физическое лицо\n";
///end address
$orders["commentary_total_order"] .= "Номер заказа в магазине№" . $order_id . "\n " .
$value["comment"] . "\n " . "EMAIL:" . $value["email"] . "\n Оплата: " . $value["payment_method"] .
"\n Доставка: " . $value["shipping_method"]; // КОММЕНТАРИИ
//default
$addr_query_string = "&num_build[]=&num_office_flat[]=";
//product
$this->load->model('account/order');
$products = $this->model_account_order->getOrderProducts($order_id);
$orders["show_next_pack"] = "on";
$q = "";
foreach ($products as $value => $key) {
$q .= "&pack[]=" . urlencode($key["name"] . " (" . $key["sku"] . ")");
$q .= "&num_pack[]=" . urlencode($key["quantity"]);
$q .= "&unit[]=" . urlencode("1");
$q .= "&price_pack[]=" . urlencode($key["price"]);
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($orders).$q.$addr_query_string);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($curl, CURLOPT_COOKIEFILE, "cookie.txt"); //saved cookies
curl_setopt($curl, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0');
$response = (curl_exec($curl));
curl_close($curl);
}
}
I need your help.
Actually I'm doing a CURL post with X-Wsse auth and posting only 2 arguments, ID and Phone.
Everything is ok.
Now I need to pass a list of ID and phones. In which way I can do this? Post a file directly? Using a loop?
I have a csv file, but for simplify I upload this file on a DB, so I can take directly from there.
This is the actual code.
<?php
function make_nonce() {
$chars = "123456789abcdefghijklmnopqrstuvwxyz";
$random = "" . microtime();
$random .= mt_rand();
$mi = strlen($chars) - 1;
for ($i = 0; $i < 10; $i++) {
$random .= $chars[mt_rand(0, $mi)];
}
$nonce = md5($random);
return $nonce;
}
function make_token($username, $password) {
$nonce = make_nonce();
$ts = date ( 'Y-m-d\TH:i:sP', time() + 290 );
$digest = base64_encode(sha1($nonce.$ts.$password, true));
return sprintf('UsernameToken Username="%s",
PasswordDigest="%s",Nonce="%s", Created="%s"',
$username, $digest, $nonce, $ts);
}
$token = make_token("username", "password"); // ### GENERO IL TOKEN
$headers = array( 'Content-type: application/x-www-form-urlencoded;
charset=UTF-8','Accept-Charset : UTF-8', 'X-Wsse :' . $token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://URL');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"phoneNumber=38452136&idPratica=745");
curl_exec ($ch);
var_dump($ch);
curl_close ($ch);
?>
I have a list of 1000 phonenumber and relatives idpratica (ID).
What can I do?
I know the way for doing with just one record.
$fields = array(
'phoneNumber' => '38452136',
'idPratica' => '745'
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
and then use
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
Please help me
i have Problem with my Scraping Script. I like to select the value from my sql by id in a while and save the the scraped content in my database. its works but the curl script send a wrong result to my database, everytime the content from the first request.
My Code:
<?php
error_reporting(E_ALL);
include('db.php');
$i = 1;
while ($i <= 5)
{
$sql = "SELECT * FROM `plz` WHERE `id` = '$i'";
$row = mysql_fetch_assoc( mysql_query($sql) );
$plz = $row['plz'];
//create array of data to be posted
$post_data['adv_plz'] = "$plz";
$post_data['finda'] = 'adv';
$post_data['lang'] = 'de_DE';
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
//create cURL connection
$curl_connection = curl_init('https://www.domain.de/');
//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
//set data to be posted
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
//perform our request
$result = curl_exec($curl_connection);
//show information regarding the request
$result = utf8_encode($result);
mysql_query("UPDATE plz SET content = '$result' WHERE id = '$i'");
$i++;
}
?>
Here is the Content of the echo $post_string
adv_plz=01000&finda=adv&lang=de_DE
adv_plz=01000&finda=adv&lang=de_DE&adv_plz=01001&finda=adv&lang=de_DE
adv_plz=01000&finda=adv&lang=de_DE&adv_plz=01001&finda=adv&lang=de_DE&adv_plz=01002&finda=adv&lang=de_DE
adv_plz=01000&finda=adv&lang=de_DE&adv_plz=01001&finda=adv&lang=de_DE&adv_plz=01002&finda=adv&lang=de_DE&adv_plz=01003&finda=adv&lang=de_DE
adv_plz=01000&finda=adv&lang=de_DE&adv_plz=01001&finda=adv&lang=de_DE&adv_plz=01002&finda=adv&lang=de_DE&adv_plz=01003&finda=adv&lang=de_DE&adv_plz=01004&finda=adv&lang=de_DE
I hope somebody can help me. If i try the script not in a while it works perfectly.
Try resetting the $post_items variable before entering the foreach loop.
$post_items = array();
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_d ....
I try to login on steam using the following code.
steamcommunity.com/login/getrsakey first request is successful.
Request a steamcommunity.com/login/dologin/ all the time gives an error incorrect login.
Perhaps dealing with encryption password or need to add ssl.
I use to encrypt library on http://phpseclib.sourceforge.net/
function geturl($url, $ref, $cookie, $postdata, $header, &$info, &$output)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36');
if ($ref)
{
curl_setopt($ch, CURLOPT_REFERER, $ref);
}
if ($cookie)
{
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}
if ($postdata)
{
curl_setopt($ch, CURLOPT_POST, true);
$postStr = "";
foreach ($postdata as $key => $value)
{
if ($postStr)
$postStr .= "&";
$postStr .= $key . "=" . $value;
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $postStr);
}
curl_setopt($ch, CURLOPT_HEADER, $header);
$info = curl_getinfo($ch);
$output = curl_exec($ch);
curl_close($ch);
}
geturl("https://steamcommunity.com/login/getrsakey", null, null, array('username' => $login), 0, $info, $output);
$data = json_decode($output, true);
if ($data['success'] === true)
{
$publickey_exp = $data['publickey_exp'];
$publickey_mod = $data['publickey_mod'];
$RSA = new Crypt_RSA();
$RSA->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$n = new Math_BigInteger($publickey_mod, 16);
$e = new Math_BigInteger($publickey_exp, 16);
$key = array("modulus"=>$n, "publicExponent"=>$e);
$RSA->loadKey($key, CRYPT_RSA_PUBLIC_FORMAT_RAW);
$encryptedPassword = base64_encode($RSA->encrypt($password, false));
$captchaGid = -1;
$captchaText;
$emailAuth;
$emailSteamId;
$params = array(
'username' => $login,
'password' => $encryptedPassword,
'rsatimestamp' => $data['timestamp'],
'captcha_gid' => $captchaGid,
'captcha_text' => $captchaText,
'emailauth' => $emailAuth,
'emailsteamid' => $emailSteamId
);
geturl("https://steamcommunity.com/login/dologin/", null, null, $params, 0, $info, $output);
$data = json_decode($output, true);
var_dump($data);
if ($data['captcha_needed'])
{
$captchaGid = $data['captcha_gid'];
echo '<img src="https://steamcommunity.com/public/captcha.php?gid=' . $captchaGid . '">';
}
}
I think it would be better to use third-part libraries to auth.
Check this one: https://github.com/SmItH197/SteamAuthentication
It creates login button like "Sign in via Facebook".
EDIT: Steam has alsow his own API https://steamcommunity.com/dev
I can't be sure, but it looks like you are attempting to log a user into your site using Steam as the login method. Is this what you are attempting to do? If so, I recommend using the LightOpenID library.
<?php
require 'includes/lightopenid/openid.php';
$_STEAMAPI = "YOURSTEAMAPIKEY";
try
{
$openid = new LightOpenID('http://URL.TO.REDIRECT.TO.AFTER.LOGIN/');
if(!$openid->mode)
{
if(isset($_GET['login']))
{
$openid->identity = 'http://steamcommunity.com/openid/?l=english'; // This is forcing english because it has a weird habit of selecting a random language otherwise
header('Location: ' . $openid->authUrl());
}
?>
<form action="?login" method="post">
<input type="image" src="http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_small.png">
</form>
<?php
}
elseif($openid->mode == 'cancel')
{
echo 'User has canceled authentication!';
}
else
{
if($openid->validate())
{
$id = $openid->identity;
// identity is something like: http://steamcommunity.com/openid/id/76561197960435530
// we only care about the unique account ID at the end of the URL.
$ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
preg_match($ptn, $id, $matches);
echo "User is logged in (steamID: $matches[1])\n";
// $matches[1] is the profile ID you will want to use for additional API calls
}
else
{
echo "User is not logged in.\n";
}
}
}
catch(ErrorException $e)
{
echo $e->getMessage();
}
?>
At the end of this login, you will have the user's profile ID (ie. 76561197960435530) which you can use against many of the API's that Steam provides to gather further information on the player.
Use "urlencode()" function
$encryptedPassword = urlencode(base64_encode($RSA->encrypt($password, false)));
I'm having a lot of trouble integrating Sagepay InFrame Server with PHP, as there are no integration kits available for the new protocol (v3). I have the old kits for v2.23 but much of the code therein is deprecated.
At the moment the only way i have been successful in retrieving an OK status from the Sagepay Server servers is to have a form with the collection of hidden values required by Sagepay, including the cryptography field, and using the server URL as the form action. This gives me a status of 'OK' and the SecurityKey etc in the browser tab, but its not much use in the browser tab as i need that POST response back on my server, not on theirs.
For this i opted for curl. I hold the return values for curl_exec in a variable called $rawresponse, and dump the response after each attempt, and as it stands $rawresponse is returning as a false boolean:
$curlSession = curl_init();
curl_setopt ($curlSession, CURLOPT_URL, $url);
curl_setopt ($curlSession, CURLOPT_HEADER, 0);
curl_setopt ($curlSession, CURLOPT_POST, 1);
$data['Crypt'] = new CurlFile('filename.png', 'image/png', 'filename.png');
curl_setopt ($curlSession, CURLOPT_POSTFIELDS, $data);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curlSession, CURLOPT_TIMEOUT,30);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 0);
$rawresponse = curl_exec($curlSession);
Now as you can see here I am having to force the Crypt value to be of type CurlFile, which is what i think is breaking the request, however if i dont do that i get the following error:
"The usage of the #filename API for file uploading is deprecated. Please use the CURLFile class instead"
I can only ascertain from this that the cryptography is being mistaken for a file (possibly because the string starts with #), and to counter this im trying to force it to be an image.
So my question is this - is there a particular way to use CurlFile so cryptography strings can be understood? Is there a better way of integrating this functionality with Sagepay that anyone knows about? It really is a very confusing system, and the good documentation is let down by a complete lack of example.
Apologies for this, I was building the string the wrong way. Just in case anyone has a similar problem in the future i'll paste the code that works for me:
public function registerTransaction()
{
$VPSProtocol = urlencode($_POST['VPSProtocol']);
$TxType = urlencode($_POST['TxType']);
$Vendor = urlencode($_POST['Vendor']);
$VendorTxCode = urlencode($_POST['VendorTxCode']);
$Currency = urlencode($_POST['Currency']);
$Amount = urlencode($_POST['Amount']);
$NotificationURL = urlencode($_POST['NotificationURL']);
$Description = urlencode($_POST['Description']);
$BillingSurname = urlencode($_POST['BillingSurname']);
$BillingFirstnames = urlencode($_POST['BillingFirstnames']);
$BillingAddress1 = urlencode($_POST['BillingAddress1']);
$BillingCity = urlencode($_POST['BillingCity']);
$BillingPostCode = urlencode($_POST['BillingPostCode']);
$BillingCountry = urlencode($_POST['BillingCountry']);
$DeliverySurname = urlencode($_POST['DeliverySurname']);
$DeliveryFirstnames = urlencode($_POST['DeliveryFirstnames']);
$DeliveryAddress1 = urlencode($_POST['DeliveryAddress1']);
$DeliveryCity = urlencode($_POST['DeliveryCity']);
$DeliveryPostCode = urlencode($_POST['DeliveryPostCode']);
$DeliveryCountry = urlencode($_POST['DeliveryCountry']);
$url = "?VPSProtocol=" . $VPSProtocol;
$url .= "&TxType=" . $TxType;
$url .= "&Vendor=" . $Vendor;
$url .= "&VendorTxCode=" . $VendorTxCode;
$url .= "&Currency=" . $Currency;
$url .= "&Amount=" . $Amount;
$url .= "&NotificationURL=" . $NotificationURL;
$url .= "&Description=" . $Description;
$url .= "&BillingSurname=" . $BillingSurname;
$url .= "&BillingFirstnames=" . $BillingFirstnames;
$url .= "&BillingAddress1=" . $BillingAddress1;
$url .= "&BillingCity=" . $BillingCity;
$url .= "&BillingPostCode=" . $BillingPostCode;
$url .= "&BillingCountry=" . $BillingCountry;
$url .= "&DeliverySurname=" . $DeliverySurname;
$url .= "&DeliveryFirstnames=" . $DeliveryFirstnames;
$url .= "&DeliveryAddress1=" . $DeliveryAddress1;
$url .= "&DeliveryCity=" . $DeliveryCity;
$url .= "&DeliveryPostCode=" . $DeliveryPostCode;
$url .= "&DeliveryCountry=" . $DeliveryCountry;
$strPurchaseURL = "https://test.sagepay.com/gateway/service/vspserver-register.vsp";
$arrResponse = $this->requestPost($strPurchaseURL, $url);
dd($arrResponse);
}
public function requestPost($url, $data){
// Set a one-minute timeout for this script
set_time_limit(60);
// Initialise output variable
$output = array();
// Open the cURL session
$curlSession = curl_init();
curl_setopt ($curlSession, CURLOPT_URL, $url);
curl_setopt ($curlSession, CURLOPT_HEADER, 0);
curl_setopt ($curlSession, CURLOPT_POST, 1);
curl_setopt ($curlSession, CURLOPT_POSTFIELDS, $data);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curlSession, CURLOPT_TIMEOUT,30);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 2);
$rawresponse = curl_exec($curlSession);
dd($rawresponse);
//Store the raw response for later as it's useful to see for integration and understanding
$_SESSION["rawresponse"]=$rawresponse;
//Split response into name=value pairs
$response = preg_split(chr(10), $rawresponse);
// Check that a connection was made
if (curl_error($curlSession)){
// If it wasn't...
$output['Status'] = "FAIL";
$output['StatusDetail'] = curl_error($curlSession);
}
// Close the cURL session
curl_close ($curlSession);
// Tokenise the response
for ($i=0; $i<count($response); $i++){
// Find position of first "=" character
$splitAt = strpos($response[$i], "=");
// Create an associative (hash) array with key/value pairs ('trim' strips excess whitespace)
$output[trim(substr($response[$i], 0, $splitAt))] = trim(substr($response[$i], ($splitAt+1)));
} // END for ($i=0; $i<count($response); $i++)
// Return the output
return $output;
} // END function requestPost()