php- curl isn't working - php

Here is my code, I have two cURL statements in the same program. The first one uses $ch and second uses $ch1. The problem is first one is getting executed and showing the output but second one does nothing.
<?php
include ('DBconnect.php');
if (isset($_POST['submit'])) {
$verified = "1";
$error = array();
if (empty($_POST['name'])) {
$error[] = 'I am sure you have a name!';
}
else {
$name = $_POST['name'];
}
if (empty($_POST['phone'])) {
$error[] = 'Please enter your phone number with country code';
}
else {
$Phone = $_POST['phone'];
}
if (empty($_POST['Password'])) {
$error[] = 'Please choose a password ';
}
else {
$Password = $_POST['Password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the phone number is available:
$query_verify_phone = "SELECT * FROM members WHERE Phone ='$Phone'";
$result_verify_phone = mysqli_query($dbc, $query_verify_phone);
if (!$result_verify_phone) { //if the Query Failed ,similar to if($result_verify_phone==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_phone) == 0) { // IF no previous user is using this phone number.
$query_insert_user = "INSERT INTO `members` ( `Name`, `Phone`, `Password`, `Verified`) VALUES ( '$name', '$Phone', '$Password', '$verified')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
$customerToken = "TOKEN HERE";
$clientTransactionId = rand(55555, 77777);
$duration = "180";
$countryCode = "91";
$z2vToken = "TOKEN HERE";
$postData = array(
'customerToken' => $customerToken,
'clientTransactionId' => $clientTransactionId,
'callerid' => $Phone,
'duration' => $duration,
'countryCode' => $countryCode,
'z2vToken' => $z2vToken,
);
// create post body
$post_body = '';
foreach($postData as $key => $value) {
$post_body.= urlencode($key) . '=' . urlencode($value) . '&';
}
$post_body = rtrim($post_body, '&');
// Initialize CURL data to send via POST to the API
// FIRST ONE CURL REQUEST- WORKING
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.zipdial.com/z2v/startTransaction.action");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_body);
// Execute CURL command and return into variable ch
$string = curl_exec($ch);
curl_close($ch);
$json = json_decode($string);
// now the json has been decoded
// echo "Please do a missed call on: ";
// echo "<img src=' ".$json->img."'>";
$pf = 'fl' . uniqid();
$un = uniqid($pf);
$fpl = 'img' . $un . '.png';
file_put_contents($fpl, file_get_contents($json->img));
Everything above goes fine but the second curl request is not working:
// EVERYTHING ABOVE GOES FINE. BELOW IS SECOND REQUEST- NOT WORKING
$url = "https://api.idolondemand.com/1/api/sync/ocrdocument/v1";
$post = array(
'apikey' => "MY KEY HERE",
'url' => "http://site.ext/users/$fpl",
'mode' => "document_photo"
);
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, $url);
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
$ocr = curl_exec($ch1);
$jsonocr = json_decode($ocr, true);
$textblock = $jsonocr['text'][0];
echo '<div class="success">Please give a missed call to ' . $textblock['text'] . ' from your registered phone number to activate account. </div>';
curl_close($ch1);
}
else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
}
else { // The phone number is not available.
echo '<div class="errormsgbox" >That phone number has already been registered. </div>';
}
}
else { //If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc); //Close the DB Connection
} // End of the main Submit conditional.
?>
I can make request to second curl request manually from my browser and it works but it isn't working here. What's wrong?

I think you get this error when you dump curl_error($ch1) :
Unknown SSL protocol error in connection to api.idolondemand.com
You can add this line when you curl https if you have no sensitive transiting data :
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
Here is the code which works for me :
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, $url);
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, 1);
$ocr = curl_exec($ch1);
var_dump($ocr);
var_dump(curl_error($ch1));
When I do this, I get :
string(97) "{ "message": "Unknown API key", "detail": { "error": 2002, "key": "MY KEY HERE" } }" string(0) ""

I have set VERIFYPEER to false and VERIFYHOST to 1 and it worked.

Related

php code for powerpoint2pdf in convertapi not working

I use the following to convert a doc file to pdf in PHP:
function CallToApi($fileToConvert, $pathToSaveOutputFile, $apiKey, &$message,$unique_filename)
{
try
{
$fileName = $unique_filename.".pdf";
$postdata = array('OutputFileName' => $fileName, 'ApiKey' => $apiKey, 'file'=>"#".$fileToConvert);
$ch = curl_init("http://do.convertapi.com/word2pdf");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
$headers = curl_getinfo($ch);
$header=ParseHeader(substr($result,0,$headers["header_size"]));
$body=substr($result, $headers["header_size"]);
curl_close($ch);
if ( 0 < $headers['http_code'] && $headers['http_code'] < 400 )
{
// Check for Result = true
if (in_array('Result',array_keys($header)) ? !$header['Result']=="True" : true)
{
$message = "Something went wrong with request, did not reach ConvertApi service.<br />";
return false;
}
// Check content type
if ($headers['content_type']<>"application/pdf")
{
$message = "Exception Message : returned content is not PDF file.<br />";
return false;
}
$fp = fopen($pathToSaveOutputFile.$fileName, "wbx");
fwrite($fp, $body);
$message = "The conversion was successful! The word file $fileToConvert converted to PDF and saved at $pathToSaveOutputFile$fileName";
return true;
}
else
{
$message = "Exception Message : ".$result .".<br />Status Code :".$headers['http_code'].".<br />";
return false;
}
}
catch (Exception $e)
{
$message = "Exception Message :".$e.Message."</br>";
return false;
}
}
I now want to use the same to convert a ppt to pdf. For which I change
$ch = curl_init("http://do.convertapi.com/word2pdf");
to
$ch = curl_init("http://do.convertapi.com/PowerPoint2Pdf");
but I am not sure why it isnt converting the given input. Is there something that I may be missing?
It's due to PHP 5.6.
You need to add this line to your code as well
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
See:Backward incompatible changes (at the bottom).

How to print MerchandiseReturn label

USPS suggests to send request XML to
secure.shippingapis.com/ShippingAPI.dll?API=MerchandiseReturnV4&XML=
I have tried with the example XML given at
https://www.usps.com/business/web-tools-apis/merchandise-return-service-labels-v10-2a.htm
$url="https://secure.shippingapis.com/ShippingAPI.dll";
$api="API=MerchandiseReturnV4&XML=";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $api . $xml);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$error = curl_error($ch);
echo result;
but it is returning nothing.....
If the request is approaching the API then it would return the response which can be the proper expected response or the error code with some error detail.
The problem for not getting the proper response might be of the following here-
Wrong XML passed to the query string
Missed some required fields in the XML
Invalid Web Tools Credentials
In order to know the exact Error Code and Details you need to parse the returned XML from the API Server.
You can get the response stream and read the stream to the Stream Reader
string result = null;
using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
However I implemented this in .Net MVC but it might help for a head start to find the exact problem.
I forget to put the answers after solving my problem.
Function for connect to usps :-
public function connectToUSPS($url, $api, $xml) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $api . $xml);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$error = curl_error($ch);
if (empty($error)) {
return $result;
} else {
return false;
}
}
Function to generate USPS label :-
function create_UspsLabel($shipId, $userId) {
$row = 'contains user data';
$uspsUserName = 'a valid usps user name';
$uspsPassword = 'a valid usps user password';
$retailerName = 'retailer name';
$retailerAddress ='retailer address';
$permitNumber = 'a valid permit number';
$retailerState = 'retailer state;
$retailerCity = 'retailer city';
$retailerZip = 'retailer zip code';
$PDUPoBox = 'pdu box number';
$PDUCity = 'pdu city name';
$PDUState = 'pdu state name';
$PDUZip = 'pdu zip code';
$PDUZip2 = 'pdu zip code2';
$oid = 'order id';
$packageId = "KR" . str_pad(($oid + 1), 5, "0", STR_PAD_LEFT);
$state = 'state';
$xml = '<EMRSV4.0Request USERID="' . $uspsUserName . '" PASSWORD="' . $uspsPassword . '">
<Option>RIGHTWINDOW</Option>
<CustomerName>' . $row->name.' '.$row->lastName . '</CustomerName>
<CustomerAddress1>' . $row->suit . '</CustomerAddress1>';
$xml.=' <CustomerAddress2>' . $row->address1 . '</CustomerAddress2>
<CustomerCity>' . $row->city . '</CustomerCity>
<CustomerState>' . $state . '</CustomerState>
<CustomerZip5>' . $row->zipcode . '</CustomerZip5>
<CustomerZip4 />
<RetailerName>' . $retailerName . '</RetailerName>
<RetailerAddress>' . $retailerAddress . '</RetailerAddress>
<PermitNumber>' . $permitNumber . '</PermitNumber>
<PermitIssuingPOCity>' . $retailerCity . '</PermitIssuingPOCity>
<PermitIssuingPOState>' . $retailerState . '</PermitIssuingPOState>
<PermitIssuingPOZip5>' . $retailerZip . '</PermitIssuingPOZip5>
<PDUPOBox>' . $PDUPoBox . '</PDUPOBox>
<PDUCity>' . $PDUCity . '</PDUCity>
<PDUState>' . $PDUState . '</PDUState>
<PDUZip5>' . $PDUZip . '</PDUZip5>
<PDUZip4>' . $PDUZip2 . '</PDUZip4>
<ServiceType>Priority Mail</ServiceType>
<DeliveryConfirmation>False</DeliveryConfirmation>
<InsuranceValue />
<MailingAckPackageID>' . $packageId . '</MailingAckPackageID>
<WeightInPounds>0</WeightInPounds>
<WeightInOunces>10</WeightInOunces>
<RMA>RMA 123456</RMA>
<RMAPICFlag>False</RMAPICFlag>
<ImageType>TIF</ImageType>
<RMABarcode>False</RMABarcode>
<AllowNonCleansedDestAddr>False</AllowNonCleansedDestAddr>
</EMRSV4.0Request>';
$result = $this->connectToUSPS('https://secure.shippingapis.com/ShippingAPI.dll', 'API=MerchandiseReturnV4&XML=', $xml);
$xml = new SimpleXMLElement($result);
$string = base64_decode($xml->MerchandiseReturnLabel);
if ($string) {
$img_file = fopen(__USPSLABELIMAGE__ . "uspsLabel.tif", "w");
fwrite($img_file, $string);
fclose($img_file);
$imageMagickPath = "/usr/bin/convert";
$dest = __USPSLABELIMAGE__ . "uspsLabel.tif";
$filename = time() . ".png";
$pngDestPath = __USPSLABELIMAGE__ . $filename;
exec("$imageMagickPath -density 72 -channel RGBA -colorspace RGB -background none -fill none -dither None $dest $pngDestPath");
return $filename;
} else {
return "error";
}
}

LinkedIn oAuth - Accessing simple read only public data - no posting etc

I'm trying to do a very basic setup of LinkedIn - accessing public profile data about people.
I've tried several ways of accessing with oAuth over several hours. I'm not getting anywhere.
All the existing class structures et'al seem to help with accessing a user's account to post, or add friends, find a fish etc. I don't need any of that. I just want to get basic profile data.
Some code of latest attempts; but I don't get it past here:-
$consumer = new OAuthConsumer($apiKey, $apiSecret);
$signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$req_req = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $linkedInURL . "/uas/oauth/requestToken");
$req_req->sign_request($signature_method, $consumer, NULL);
$signed_url = $req_req->to_url();
That should gives me a signed request of:-
https://api.linkedin.com/uas/oauth/requestToken?oauth_consumer_key=xxx&oauth_nonce=xx&oauth_signature=xxxx&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1316530337&oauth_version=1.0
Obviously, that's not what I need to get data. But, just out of interest I checked the URL with the API data request, as such:-
http://api.linkedin.com/v1/people/url=http%3A%2F%2Fwww.linkedin.com%2Fin%2Fchrisvoss:public?oauth_consumer_key=xxx&oauth_nonce=xxx&oauth_signature=xxx&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1316529463&oauth_version=1.0
And got :-
<error>
<status>401</status>
<timestamp>1316531835564</timestamp>
<request-id>L8A1M85MWN</request-id>
<error-code>0</error-code>
<message>
[unauthorized].OAU:tm6i3ke827xz|*01|*01|*01:1316529463:MSFHS3f4iaG9pg2gWYlf22W4NPo=
</message>
</error>
I'm just a bit clueless here. I know everyone says it's tears to implement oAuth and Linkedin. But, I don't need half of what most need, so how do I get to the basic data is only my question.
Thanks in advance for any help.
Try To Use the following code
session_start();
require_once("OAuth.php");
$domain = "https://api.linkedin.com/uas/oauth";
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$test_consumer = new OAuthConsumer("DEHYU99peS88wDDAFOcSm3Af5VO1tdrdgq1xPu_fpSSjsqPcoeABUs_NCyY33WIH", "gZrZr2-7s80CEsGpAHqFgREMbRWkR3L8__tkje3j-oKtIDlmn5KCR6bXD8i0HFp1", NULL);
$callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?action=getaccesstoken";
# First time through, get a request token from LinkedIn.
if (!isset($_GET['action'])) {
$req_req = OAuthRequest::from_consumer_and_token($test_consumer, NULL, "POST", $domain . "/requestToken");
$req_req->set_parameter("oauth_callback", $callback); # part of OAuth 1.0a - callback now in requestToken
$req_req->sign_request($sig_method, $test_consumer, NULL);
$ch = curl_init();
// make sure we submit this as a post
curl_setopt($ch, CURLOPT_POSTFIELDS, ''); //New Line
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
$req_req->to_header()
));
curl_setopt($ch, CURLOPT_URL, $domain . "/requestToken");
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
curl_close($ch);
//print_r($req_req); //<---- add this line
//print("$output\n"); //<---- add this line
parse_str($output, $oauth);
# pop these in the session for now - there's probably a more secure way of doing this! We'll need them when the callback is called.
$_SESSION['oauth_token'] = $oauth['oauth_token'];
$_SESSION['oauth_token_secret'] = $oauth['oauth_token_secret'];
# Redirect the user to the authentication/authorisation page. This will authorise the token in LinkedIn
Header('Location: ' . $domain . '/authorize?oauth_token=' . $oauth['oauth_token']);
#print 'Location: ' . $domain . '/authorize?oauth_token=' . $oauth['oauth_token']; // <---- add this line
} else {
# this is called when the callback is invoked. At this stage, the user has authorised the token.
# Now use this token to get a real session token!
//print "oauth_token = [[".$_REQUEST['oauth_token']."]]\n";echo "<br/><br/>";
$req_token = new OAuthConsumer($_REQUEST['oauth_token'], $_SESSION['oauth_token_secret'], 1);
$acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $req_token, "POST", $domain . '/accessToken');
$acc_req->set_parameter("oauth_verifier", $_REQUEST['oauth_verifier']); # need the verifier too!
$acc_req->sign_request($sig_method, $test_consumer, $req_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, ''); //New Line
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
$acc_req->to_header()
));
curl_setopt($ch, CURLOPT_URL, $domain . "/accessToken");
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error 1: ' . curl_error($ch);
}
curl_close($ch);
parse_str($output, $oauth);
$_SESSION['oauth_token'] = $oauth['oauth_token'];
$_SESSION['oauth_token_secret'] = $oauth['oauth_token_secret'];
# Now you have a session token and secret. Store these for future use. When the token fails, repeat the above process.
//$endpoint = "http://in.linkedin.com/in/intercom"; # need a + symbol here.
$endpoint = "http://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,industry,educations,site-standard-profile-request)";
//$req_token = new OAuthConsumer($oauth['oauth_token'], $oauth['oauth_token_secret'], 1);
$req_token = new OAuthConsumer($oauth['oauth_token'],$oauth['oauth_token_secret'], 1);
//$profile_req = OAuthRequest::from_consumer_and_token($test_consumer, $req_token, "GET", $endpoint, array("name" => "intercom")); # but no + symbol here!
$profile_req = OAuthRequest::from_consumer_and_token($test_consumer,$req_token, "GET", $endpoint, array());
$profile_req->sign_request($sig_method, $test_consumer, $req_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
$profile_req->to_header()
));
curl_setopt($ch, CURLOPT_URL, $endpoint);
$output = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error 2: ' . curl_error($ch);
}
curl_close($ch);
//header ("Content-Type:text/xml");
//print $output;
$myFile = $_SERVER['DOCUMENT_ROOT']."/oauth/linkedin.xml";
$fh = fopen($myFile, 'w') or die("can't open file");
//$stringData = "Bobby Bopper\n";
fwrite($fh, $output);
fclose($fh);
//Initialize the XML parser
global $currentTag;
global $profileArray;
$parser=xml_parser_create();
//Function to use at the start of an element
function start($parser,$element_name,$element_attrs) {
$element_name = strtolower($element_name);
global $currentTag;
$currentTag = $element_name;
/*switch($element_name) {
case "person":
$currentTag = $element_name;
break;
case "headline":
echo "headline: ";
break;
case "school-name":
echo "school-name: ";
break;
case "degree":
echo "degree: ";
break;
case "field-of-study":
echo "field-of-study: ";
}*/
}
//Function to use at the end of an element
function stop($parser,$element_name) {}
//Function to use when finding character data
function char($parser,$data){
//echo $data;
global $currentTag;
global $profileArray;
switch($currentTag) {
/* case "member-url":
if(!isset($profileArray['member-url'])) {
$profileArray['member-url'] = $data;//echo $profileArray['industry'];
}
break;*/
case "id":
if(!isset($profileArray['id'])) {
$profileArray['id'] = $data;//echo $profileArray['industry'];
}
break;
case "site-standard-profile-request":
if(!isset($profileArray['site-standard-profile-request'])) {
$profileArray['site-standard-profile-request'] = $data;//echo $profileArray['industry'];
}
break;
case "first-name":
if(!isset($profileArray['first-name'])) {
$profileArray['first-name'] = $data;//echo $profileArray['industry'];
}
break;
case "last-name":
if(!isset($profileArray['last-name'])) {
$profileArray['last-name'] = $data;//echo $profileArray['industry'];
}
break;
case "industry":
if(!isset($profileArray['industry'])) {
$profileArray['industry'] = $data;//echo $profileArray['industry'];
}
break;
case "headline":
if(!isset($profileArray['headline'])) {
$profileArray['headline'] = $data;
}
break;
case "school-name":
if(!isset($profileArray['school-name'])) {
$profileArray['school-name'] = $data;
}
break;
case "degree":
if(!isset($profileArray['degree'])) {
$profileArray['degree'] = $data;
}
break;
case "field-of-study":
if(!isset($profileArray['field-of-study'])) {
$profileArray['field-of-study'] = $data;
}
break;
}
}
//Specify element handler
xml_set_element_handler($parser,"start","stop");
//Specify data handler
xml_set_character_data_handler($parser,"char");
//Open XML file
$fp=fopen($_SERVER['DOCUMENT_ROOT']."/oauth/linkedin.xml","r");
//Read data
while ($data=fread($fp,4096)) {
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
//Free the XML parser
xml_parser_free($parser);
print_r($profileArray);
getCurrentCookieValue($name)
}
you can use linkedIn javascript API to retrieve profile information

contact form security code php problem? How to remove code?

I'm trying to find the security code in this php for a mailer.
Please could you tell me which parts of the code I need to delete to remove this.
Thanks for your help
<?php
$adminemail = 'info#blue.co.uk'; // type your actual email address in place of you#yourdomain.com
$usesecimage = ''; // the path to a WSN Links, Gallery, KB or Forum install if you wish to borrow its security image prompt
$autoresponse = ''; // type the URL of a text file which should be used as the autoresponder body text
$controlvars = ' thankspage submitteremail ccsubmitter messagetosubmitter ';
$messagetoadmin = "A user has filled out a form with this content:
";
if (!isset($_POST['messagetosubmitter'])) $messagetosubmitter = "You have submitted a form with the content listed below. Your submission will be reviewed, please be patient in awaiting a response.
";
else $messagetosubmitter = $_POST['messagetosubmitter'];
while(list($key, $value) = each($_POST))
{
if (!stristr($controlvars, ' '. $key .' '))
{
$messagetoadmin .= $key .': '. $value .'
';
$messagetosubmitter .= $key .': '. $value .'
';
}
}
$submitter = $_POST['submitteremail'];
if ($submitter == '') $submitter = 'info#innco.uk';
if (strstr($submitter, "\n") || strlen($submitter) > 50) die("Begone, foul spammer.");
if ($usesecimage)
{
$curr_path = getcwd();
chdir($usesecimage); // Go to the WSN directory
require 'start.php';
if (isset($_REQUEST['seed'])) $seed = $_REQUEST['seed']; else $seed = false;
$correct = securityimagevalue($seed);
if (strtolower($_POST['securityimage']) != $correct) die("You did not type the value from the image correctly. Press the back button.");
chdir($curr_path); // Return to original directory
}
session_start();
if(empty($_POST['TermsOfBusiness']))
{
error_reporting(0);
echo "You must agree to our Terms of Business. Please <a href='javascript: history.go(-1)'>click here</a> to return to the form";
}
elseif(($_SESSION['security_code'] == $_POST['security_code']) && (!empty($_SESSION['security_code'])) ) {
mail("$adminemail, kat#cat.com", 'Form Submitted: '. stripslashes($_POST['subject']), stripslashes($messagetoadmin), 'From: '. $submitter);
unset($_SESSION['security_code']);
} else {
error_reporting(0);
echo "The security code you entered was incorrect, please click the back button on your browser to try again.";
}
if ($_POST['ccsubmitter'] == 'yes')
{
mail($submitteremail, 'Form Submitted: '. stripslashes($_POST['subject']), stripslashes($messagetosubmitter), 'From: '. $adminemail);
}
if ($autoresponse != '')
{
$body = geturl($autoresponse);
mail($submitteremail, 'Re: '. stripslashes($_POST['subject']), stripslashes($body), 'From: '. $adminemail);
}
header('Location: '. $_POST['thankspage']);
// just in case redirect doesn't work
die('<meta http-eqiv="refresh" content="0;url='. $_POST['thankspage'] .'">');
if (!function_exists('geturl'))
{
function geturl($url)
{
if (extension_loaded('curl'))
{
$user_agent = 'Mozilla/4.0 (compatible; MSIE 6.02; PHP)';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt ($ch, CURLOPT_HEADER, false);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 15); // timeout after 5 seconds
curl_setopt ($ch, CURLOPT_TIMEOUT, 15); // timeout after 5 seconds
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec ($ch);
curl_close ($ch);
// curl_error($ch); // for debugging
return $result;
}
if (version_compare("4.3.0", phpversion(), "<"))
{
$filecontents = #file_get_contents($url);
}
else
{
$fd = #fopen($url, 'rb');
$filecontents = "";
do
{
$data = #fread($fd, 8192);
if (strlen($data) == 0)
{
break;
}
$filecontents .= $data;
} while(true);
#fclose ($fd);
}
return $filecontents;
}
}
?>
The binary-search method can be used here, which starts like this:
Delete the bottom half of the file; check: Did that contain the "security code"?
No: Delete the top half of the file; check: Did that contain the "security code"?
No: Retest-assumption: Are you sure the security code is in this file?
Once you've found which half the "security code" is in:
Delete the bottom half of that half of the file; check: Did that contain the "security code"?
No: Delete the top half of that half of the file; check: Did that contain the "security code"?
No: Retest-assumption: Are you sure the security code is in this half of this file?
Repeat until you have found the line (or lines) that you are interested in.
remove this :)
EDIT: the elseif.. wasn't showing as code, corrected.
elseif(($_SESSION['security_code'] == $_POST['security_code']) && (!empty($_SESSION['security_code'])) ) {
mail("$adminemail, kat#cat.com", 'Form Submitted: '. stripslashes($_POST['subject']), stripslashes($messagetoadmin), 'From: '. $submitter);
unset($_SESSION['security_code']);
} else {
error_reporting(0);
echo "The security code you entered was incorrect, please click the back button on your browser to try again.";
}
and this (by Cameron Conner)
if ($usesecimage)
{
$curr_path = getcwd();
chdir($usesecimage); // Go to the WSN directory
require 'start.php';
if (isset($_REQUEST['seed'])) $seed = $_REQUEST['seed']; else $seed = false;
$correct = securityimagevalue($seed);
if (strtolower($_POST['securityimage']) != $correct) die("You did not type the value from the image correctly. Press the back button.");
chdir($curr_path); // Return to original directory
}
so, your file should stay like this:
<?php
$adminemail = 'info#blueriverwm.co.uk'; // type your actual email address in place of you#yourdomain.com
$usesecimage = ''; // the path to a WSN Links, Gallery, KB or Forum install if you wish to borrow its security image prompt
$autoresponse = ''; // type the URL of a text file which should be used as the autoresponder body text
$controlvars = ' thankspage submitteremail ccsubmitter messagetosubmitter ';
$messagetoadmin = "A user has filled out a form with this content:
";
if (!isset($_POST['messagetosubmitter'])) $messagetosubmitter = "You have submitted a form with the content listed below. Your submission will be reviewed, please be patient in awaiting a response.
";
else $messagetosubmitter = $_POST['messagetosubmitter'];
while(list($key, $value) = each($_POST))
{
if (!stristr($controlvars, ' '. $key .' '))
{
$messagetoadmin .= $key .': '. $value .'
';
$messagetosubmitter .= $key .': '. $value .'
';
}
}
$submitter = $_POST['submitteremail'];
if ($submitter == '') $submitter = 'info#innco.uk';
if (strstr($submitter, "\n") || strlen($submitter) > 50) die("Begone, foul spammer.");
session_start();
if(empty($_POST['TermsOfBusiness']))
{
error_reporting(0);
echo "You must agree to our Terms of Business. Please <a href='javascript: history.go(-1)'>click here</a> to return to the form";
}
if ($_POST['ccsubmitter'] == 'yes')
{
mail($submitteremail, 'Form Submitted: '. stripslashes($_POST['subject']), stripslashes($messagetosubmitter), 'From: '. $adminemail);
}
if ($autoresponse != '')
{
$body = geturl($autoresponse);
mail($submitteremail, 'Re: '. stripslashes($_POST['subject']), stripslashes($body), 'From: '. $adminemail);
}
header('Location: '. $_POST['thankspage']);
// just in case redirect doesn't work
die('<meta http-eqiv="refresh" content="0;url='. $_POST['thankspage'] .'">');
if (!function_exists('geturl'))
{
function geturl($url)
{
if (extension_loaded('curl'))
{
$user_agent = 'Mozilla/4.0 (compatible; MSIE 6.02; PHP)';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt ($ch, CURLOPT_HEADER, false);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 15); // timeout after 5 seconds
curl_setopt ($ch, CURLOPT_TIMEOUT, 15); // timeout after 5 seconds
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec ($ch);
curl_close ($ch);
// curl_error($ch); // for debugging
return $result;
}
if (version_compare("4.3.0", phpversion(), "<"))
{
$filecontents = #file_get_contents($url);
}
else
{
$fd = #fopen($url, 'rb');
$filecontents = "";
do
{
$data = #fread($fd, 8192);
if (strlen($data) == 0)
{
break;
}
$filecontents .= $data;
} while(true);
#fclose ($fd);
}
return $filecontents;
}
}
?>
Expanding on CuSS's answer.. This is unnecessary as well.
if ($usesecimage)
{
$curr_path = getcwd();
chdir($usesecimage); // Go to the WSN directory
require 'start.php';
if (isset($_REQUEST['seed'])) $seed = $_REQUEST['seed']; else $seed = false;
$correct = securityimagevalue($seed);
if (strtolower($_POST['securityimage']) != $correct) die("You did not type the value from the image correctly. Press the back button.");
chdir($curr_path); // Return to original directory
}

How to use Constant Contact API?

I want to use API of the constant contact and want to insert user email using PHP while user register to the site.
please reply if any help.
Thanks in advance.
// fill in your Constant Contact login and API key
$ccuser = 'USERNAME_HERE';
$ccpass = 'PASS_HERE';
$cckey = 'APIKEY_HERE';
// fill in these values
$firstName = "";
$lastName = "";
$emailAddr = "";
$zip = "";
// represents the contact list identification number(s)
$contactListId = INTEGER_OR_ARRAY_OF_INTEGERS_HERE;
$contactListId = (!is_array($contactListId)) ? array($contactListId) : $contactListId;
$post = new SimpleXMLElement('<entry></entry>');
$post->addAttribute('xmlns', 'http://www.w3.org/2005/Atom');
$title = $post->addChild('title', "");
$title->addAttribute('type', 'text');
$post->addChild('updated', date('c'));
$post->addChild('author', "");
$post->addChild('id', 'data:,none');
$summary = $post->addChild('summary', 'Contact');
$summary->addAttribute('type', 'text');
$content = $post->addChild('content');
$content->addAttribute('type', 'application/vnd.ctct+xml');
$contact = $content->addChild('Contact');
$contact->addAttribute('xmlns', 'http://ws.constantcontact.com/ns/1.0/');
$contact->addChild('EmailAddress', $emailAddr);
$contact->addChild('FirstName', $firstName);
$contact->addChild('LastName', $lastName);
$contact->addChild('PostalCode', $zip);
$contact->addChild('OptInSource', 'ACTION_BY_CUSTOMER');
$contactlists = $contact->addChild('ContactLists');
// loop through each of the defined contact lists
foreach($contactListId AS $listId) {
$contactlist = $contactlists->addChild('ContactList');
$contactlist->addAttribute('id', 'http://api.constantcontact.com/ws/customers/' . $ccuser . '/lists/' . $listId);
}
$posturl = "https://api.constantcontact.com/ws/customers/{$ccuser}/contacts";
$authstr = $cckey . '%' . $ccuser . ':' . $ccpass;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $posturl);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $authstr);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/atom+xml"));
curl_setopt($ch, CURLOPT_HEADER, false); // Do not return headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); // If you set this to 0, it will take you to a page with the http response
$response = curl_exec($ch);
curl_close($ch);
// returns true on success, false on error
return (!is_numeric($response));
The developers of ConstantContact have launched PHP library to handle such kind of tasks.
Following version is for older PHP versions (5.2 or lesser). Download code from here: https://github.com/constantcontact/ctct_php_library
Following is an example to add a subscriber's email in your constant contact lists.
After downloading the above library, use following code to add an email in Constant Contact list(s).
session_start();
include_once('ConstantContact.php'); // Set path accordingly
$username = 'YOUR_CONSTANT_CONTACT_USER_NAME';
$apiKey = 'YOUR_API_KEY';
$password = 'YOUR_CONSTANT_CONTACT_PASSWORD';
$ConstantContact = new Constantcontact("basic", $apiKey, $username, $password);
$emailAddress = "new_email#test.com";
// Search for our new Email address
$search = $ConstantContact->searchContactsByEmail($emailAddress);
// If the search did not return a contact object
if($search == false){
$Contact = new Contact();
$Contact->emailAddress = $emailAddress;
//$Contact->firstName = $firstName;
//$Contact->lastName = $lastName;
// represents the contact list identification link(s)
$contactList = LINK_OR_ARRAY_OF_LINKS_HERE;
// For example,
// "http://api.constantcontact.com/ws/customers/USER_NAME/lists/14";
$Contact->lists = (!is_array($contactList)) ? array($contactList) : $contactList;
$NewContact = $ConstantContact->addContact($Contact);
if($NewContact){
echo "Contact Added. This is your newly created contact's information<br /><pre>";
print_r($NewContact);
echo "</pre>";
}
} else {
echo "Contact already exist.";
}
Note: The latest version can be found on the GitHub links given in following URL: http://developer.constantcontact.com/libraries/sample-code.html
But I am not sure if the above example code works with the newer library or not.
If you can't get this to work, you might have to add this curl_setopt:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

Categories