problem sending varibles to remote url with CURL - php

I'm trying to send variables from server A to server B, and back. I have everything working other then actually sending the variables from server A to server B. So i can send variables back from server B to server A but just cant send them to Server B from server A. I use JSON to send the variables back (which works fine) and i use _POST to send them to server B.
Here is my code on both Servers:
Server A
<?
require ('../refference.php');
$post_fields = array(
'unq__id' => $sponsor_reference,
'gdi__username' => $sponsor_GDI_id,
);
$ch = curl_init('http://site.com/WP/d__access.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);
$data = json_decode($result);
$sponsor_first_nme = $data->sponsor_first_nme;
echo $sponsor_first_nme;
?>
Server B
<?
include ('config/wp__2135432135435135412312415456654452547534.php');
mysql_connect($hostname,$username,$password) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$reference = $_POST['unq__id'];
$username = $_POST['gdi__username'];
$select = mysql_query("SELECT * FROM $usertable WHERE ". "GDI_Username = '$username' AND Unique_id = '$reference'");
while($check = mysql_fetch_array($select)) {
$sponsor_email = $check["Email"];
$sponsor = $check["GDI_Username"];
$sponsor_first_nme = $check["First_Name"];
$sponsor_second_nme = $check["Last_Name"];
$sponsor_domain = $check["GDI_Domain"];
$unq_id = $check["Unique_id"];
}
$sponsor_name = "$sponsor_first_nme $sponsor_second_nme";
$result = array(
'sponsor_first_nme' => $sponsor_first_nme,
'sponsor_second_nme' => $sponsor_second_nme,
'sponsor_email' => $sponsor_email,
'sponsor' => $sponsor,
'sponsor_domain' => $sponsor_domain,
'unq_i' => $unq_id,
'sponsor_full_name' => $sponsor_name,
);
echo json_encode($result);
?>
I know that everything else works fine as I've replaced:
$select = mysql_query("SELECT * FROM $usertable WHERE ". "GDI_Username = '$username' AND Unique_id = '$reference'");
WITH
$select = mysql_query("SELECT * FROM $usertable WHERE ". "GDI_Username = 'myusername' AND Unique_id = '45415645154'");
So i know the problem lies within sending the variables (
'unq__id' => $sponsor_reference,
'gdi__username' => $sponsor_GDI_id,
from server A as i cant use them in the script on server B)
When i test it using the variables, I just get a blank page, but when i replace that line as mentioned above, i get the name ($sponsor_first_nme) echoed out (the expected result)

You could use serialize() to create a string representation of whatever you are trying to send.

You may have to set the post option before you set the post data.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
If not, the post data could be empty.

Send the post data as a string
$fields = array(
'unq__id' => $sponsor_reference,
'gdi__username' => $sponsor_GDI_id,
);
$field_string = "";
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string,'&');
Now you can send it in curl:
Edit:
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

I've got it working, well it seemed to be working the whole time...
I was just echoing it out incorrectly. I used echo $sponsor_first_nme when it was supposed to be echo "$sponsor_first_nme" (with quotes).
Really appreciate all your help though! Thanks a BUNCH!

Related

Send txt file from A domain to B domain And run

I'm junior php developer with one year experience.
It's my first time to ask for some help
If there's anything that is not appropriate,please tell me,thanks a lot.
Situation:
1.We have two different places(domain A, domain B)
2.When updating the sql on domain A, save a txt file in JSON type as well.(json.txt)
3.Then "send" this txt file from domain A to domain B
4.read and decode the txt file on domain B, then used in Updating sql
Question:
that "send" in situation 3 is the question need to be helped.
What kind of method can be used in this situation?
Here is the whole process in code :
Domain A = "c://example"
Domain B = "220.xxx.xx"
testing file = "sending.txt"
DomainA
<?php
// this code is on Domain A
include_once "lib/database.php";
$pdo = DB_CONNECT();
$file = "sending.txt";
$f = fopen($file, 'w');
// select data from sql, update and put in array, then save it into txt
$sql = "SELECT id,lastupdated FROM customer";
$pdo -> query($sql);
$rs = $pdo -> query($sql);
foreach ($rs as $key => $row) {
$array[$key]=[
"id" => $row["id"],
"lastupdated" => $row["lastupdated"],
];
$sql = "INSERT INTO customer_test (customer_id,lastupdated) VALUES
(".$row["id"].",'".$row["lastupdated"]."')";
$pdo -> query($sql);
}
$array_json = json_encode($array);
fwrite($f, $array_json);
fclose($f);
?>
The Json txt I svaed
[{"id":"1","lastupdated":"2017-03-01 13:55:17"},
{"id":"2","lastupdated":"2017-01-08 17:03:39"},
{"id":"3","lastupdated":"2017-02-07 09:34:29"}]
Domain B
<?php
include_once "lib/database.php";
$pdo = DB_CONNECT();
// get from local txt which has been sent to here From other Domain;
$json_data = file_get_contents('sending.txt');
$array = json_decode($json_data, true);
//then save into same database,but this one is on Domain B.
foreach ($array as $i => $row) {
$id = $array[$i]["id"];
$lastupdated = $array[$i]["lastupdated"];
$sql = "INSERT INTO customer_test (customer_id,lastupdated) VALUES
(".$id.",'".$lastupdated."')";
$pdo -> query($sql);
}
?>
What code should I add in these two php files?
My boss only give this link to me :
How to simulate browser form POST method using PHP/cURL
But I still don't have any idea at all.
Can't even know where to add my code to test.
Please take a look when you are available with this question.
Many thanks.
Add this to the bottom of Domain A. This generates a post request by the php curl library. You'll need to have it installed and it likely is. http://php.net/manual/en/book.curl.php
$ch = curl_init('http://220.xxx.xx');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $array_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($array_json))
);
And check the data from Domain A by putting this on domain B:
var_dump($_RESPONSE);exit;
Also, open up the network tab on your element-inspector to get a better idea of what's going on.
// get from local txt which has been sent to here From other Domain;
It could go the other way around. Domain A doesn't send the text... Domain B retrieves the text from Domain A.
Example from php.net: http://php.net/manual/en/curl.examples.php
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "c://example/sending.txt"); // Domain A
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
// or you could use file_get_contents
$text = file_get_contents('c://example/sending.txt');
$text_array = json_decode($text); print_r($text_array);
?>

salesforce api add leads from form

I am trying to add leads from my contact form to salesforce. Currently I am using this solution that passes them through what I assume is the Web-to-Lead solution they have:
if (isset($_POST['submit'])) {
$ch_register_first_name = $_POST['ch_register_first_name'];
$ch_register_last_name = $_POST['ch_register_last_name'];
$ch_register_dob = $_POST['ch_register_dob'];
$ch_register_phone = $_POST['ch_register_phone'];
$ch_register_email = $_POST['ch_register_email'];
$ch_register_street = $_POST['ch_register_street'];
$ch_register_street2 = $_POST['ch_register_street2'];
$ch_register_city = $_POST['ch_register_city'];
$ch_register_state = $_POST['ch_register_state'];
$ch_register_zip = $_POST['ch_register_zip'];
//set POST variables
$url = 'https://test.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8';
$fields = array(
'last_name'=>urlencode($ch_register_first_name),
'first_name'=>urlencode($ch_register_last_name),
'street'=>urlencode($ch_register_street),
'city'=>urlencode($ch_register_city),
'state'=>urlencode($ch_register_state),
'zip'=>urlencode($ch_register_zip),
'company'=>urlencode($company),
'description'=>urlencode($ch_register_dob),
'email'=>urlencode($ch_register_phone),
'phone'=>urlencode($ch_register_email),
'mycustomefieldid' => urlencode($ch_register_dob), // custom field
'oid' => $ch_register_salesforce_id, // insert with your id
'retURL' => urlencode('http://thank-you/'), // sending this just in case
'debug' => '1',
'debugEmail' => urlencode("email#email.com"), // your debugging email
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//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,$fields_string);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION, TRUE);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
}
The issue by doing this (if I am correct that its using the Web-to-Lead solution) the max limit is 500 in 24hrs. Some events this form will be used at day of will have more than 500 for sure. How can I use just their API I have read about? Or should I save the locally to the database then run a batch using the Force api?

how to pass an array of data through cURL in php?

i go from my front(login.php) to my back(loginback.php) i want to send an array of data from the back to the front. When i do this all it prints is "Array", so i tried using print_r to see what was in it and it still just says "Array".
login
<?php
if(isset($_POST['submit']))
{
include_once("dbconnect.php");
$name = $_POST['name'];
$pass = $_POST['pass'];
$account = $_POST['account'];
$post = 'name='.$name.'&pass='.$pass.'&account='.$account;
$url = "#####/Middle/loginBack.php";
$ch = curl_init();//initialize
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURL_POST, true); //true = 1
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);//post is the date of name value pair
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//get data bak = true
$response = curl_exec($ch); //execute and get back data
curl_close($ch);// close all curl connections
print_r($response);
?>
loginback
<?php
include ('dbconnect.php');
$name = $_POST['name'];
$pass = $_POST['pass'];
$account = $_POST['account'];
$sql = " SELECT id, Username, Password FROM studentAccounts WHERE Username = '$name' ";
$query = mysqli_query($dbCon, $sql);
$row = mysqli_fetch_row($query);
$dbid = $row[0];
$dbName = $row[1];
$dbPass = $row[2];
$num = 100;
$myArray = array($num, $name, $dbid);
echo $myArray;
?>
It's not possible to print an array with echo. In your case since you want to grab the data from another server, you would need to send data in a controlled from. JSON would work fine here.
Change your echo to something like this
echo json_encode($myArray);
then you should see the JSON string representing your array. Now on the other side, you would use json_decode to convert it back to an array.
EDIT:
Just to make it clear, if you would replace
print_r($response);
with
print_r(json_decode($response));
i do think you will see your data.
you can use the below code to send array to the desired url using post method
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => AUTHENTICATIONURL,
CURLOPT_USERAGENT => 'user Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'0' => 'ram',
'1' => 'sham',
'2'=> 'geta',
'3'=>'so on'
)
));
Try this code snippet
and $post = 'name='.$name.'&pass='.$pass.'&account='.$account;
This is not an array it's just a string

I am able to fetch the data from facebook in json format but not able to insert in the database.

The code is working fine but i am not able to insert the user data in the mysql database.
<?php
$facebookAppAuthUrl = 'https://graph.facebook.com/oauth/access_token';
$facebookGraphUrl = 'https://graph.facebook.com';
$facebookClientId = ''; // Put your App Id here.
$facebookRedirectUrl = ''; // Redirect url same as passed before.
$facebookAppSecret = ""; // Put your App Secret here.
$code = $_GET['code'];
$url =$facebookAppAuthUrl."?client_id=".$facebookClientId
."&redirect_uri=".$facebookRedirectUrl
."&client_secret=".$facebookAppSecret
."&code=".$code;
$output = urlResponse($url);
$var = strtok($output, "&");
$ApCode = strtok($var, "=");
$ApCode = strtok("=");
// This $ApCode will be used as a token to get user info from facebook.
$url = $facebookGraphUrl.'/me';
echo '<pre>';
$resposeObj = json_decode(processUrl($url,$ApCode));
var_dump($resposeObj);
echo '<pre>';
function urlResponse($url)
{
$ch = curl_init();
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function processUrl($url,$apCode){
if(stripos($url,'?')>0)
$url = $url.'&access_token='.$apCode;
else
$url = $url.'?access_token='.$apCode;
return urlResponse($url);
}
?>
I guess the code below is wrong. I got the user data from facebook in JSON format but unfortunately I am not able to add user data in mysql using the PHP. How could we insert the json format data in mysql using php?
<?php
require('../conn.php');
$name = $url['id']['name'];
$first_name = $url['id']['first_name'];
$last_name = $url['id']['last_name'];
$hometown = $url['id']['hometown'];
{
$sql="insert into user values('','$name','$first_name','$last_name','$hometown')";
mysql_query($sql);
}
?>
<script type="text/javascript">window.location="../index.php"</script>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
Here what you need to do , first the JSON returned data needs to be converted to array as
$response = json_decode($response,true);
Now with this data you have the array and you can use print_r($response) and see how the array looks like and use the data in the query.
Hope this helps
So, apparently I can't comment without 50 rep points - so whatever. I suspect your insert statement is off. Why do you have an empty string at the beginning? I hope that's not your primary key field. I would specify my fields if I were you and leave the auto-inc field out of it so it can auto increment :)
$sql="insert into user (`name`,`firstName`,`LastName`,`homeTown`) values('$name','$first_name','$last_name','$hometown')";

Getting a curl response in string format

I am trying to execute a url and getting its response. Following is the code that executes the curl. I want the curl execution to return me a string in $result.
<?php
$fields = array
(
'username'=>urlencode($username),
'pwrd'=>urlencode($pwrd),
'customer_num'=>urlencode($customer_num)
);
$url = 'http://localhost/test200.php';
//open connection
set_time_limit(20);
$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);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $result; //I want $result to be "Successful"
?>
This is my test200.php on localhost:
<?php
$usernam = $_POST['username'];
$pass = $_POST['pwrd'];
$customer_num = $_POST['customer_num'];
echo "Successful!";
?>
What changes do I make in test200.php? Please help.
You should use the httpcode returned by the curl execution and not rely on a string that is returned
$res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Here - http://www.webmasterworld.com/forum88/12492.htm
Once the data is sent to test200.php do the appropriate manipulation like insert the posted values into a table and on success
echo "Successful!";
or print the same in your test200.php.. assuming you are doing an insert code in test200.php code would be like
<?php
$qry = "INSERT INTO `your_table` (`field_customer_name`, `field_username`, `field_password`) VALUES ($fields['customer_num'], $fields['username'], some_encrypt_fxn($fields['pwrd']))";
mysql_query($qry);
$err_flag = mysql_error($your_conn_link);
if($err_flag == '') {
echo "Successful!";
}
else {
echo "Failed, Error " . $err_flag;
}
?>
If the purpose of getting "Successful!" is to check if the cURL returns success then i suggest using Prateik's answer of using the returned status code
Somehow a simple print("Successful"); statement in test200.php worked well. The response i get now is as follows: HTTP Code: 0 Array ( [0] => [1] => Successful )

Categories