How safe is a curl function from being sniffed? - php

Hi instead of using the Paypal API I designed a webpage using php and curl to check whether a certain email is verified on Paypal or not. In order to do so I have to allow the script to login for me on Paypal's website. Now I am using a fake paypal account just to check if an email is verified or not, but my question is how secure is that username and password that is being entered onto paypal's website. If it is unsecure and can be easily sniffed out by someone monitoring the server communications, how can I protect against that?
Please note I am not using Paypal's API because it requires way too much work to incorporate onto your website, and it requires extra fields to return if an email is verified (first name, last name, etc).
Here's the code:
<?php
//email address to check
$verifyEmail = 'randomemail#blah.com';
//paypal login info
$loginEmail = '###';
$password = '###';
if (!isLogin($loginEmail, $password)) {
echo 'Login failed';
} else if (isVerified($verifyEmail)) {
echo 'Verified';
} else {
echo 'Not verified';
}
#########################################
function isVerified($verifyEmail) {
$url = 'https://www.paypal.com/us/verified/pal='.$verifyEmail;
$response = curl_get($url);
if(strpos($response, '<td class="emphasis">Verified</td>')) {
return true;
} else {
return false;
}
}
function isLogin($email, $password) {
// Get login page
$response = curl_get('https://www.paypal.com/us/cgi-bin/webscr?cmd=_login-run');
$postFields = getHiddenFormInputs($response, 'login_form');
if (!$postFields) {
return false;
}
// Post login
$postFields['login_email'] = $email;
$postFields['login_password'] = $password;
$postFields = serializePostFields($postFields);
$response = curl_get('https://www.paypal.com/us/cgi-bin/webscr?cmd=_login-submit', $postFields);
if(!strpos($response, 'login_cmd=_login-done')) {
return false;
} else {
return true;
}
}
function curl_get($url, $postfields=false) {
static $curl;
if(empty($curl)) {
$cookiejar = 'curl_cookiejar.txt';
#unlink($cookiejar);
$curl = curl_init();
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiejar);
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiejar);
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_MAXREDIRS, 5);
}
curl_setopt($curl, CURLOPT_URL, $url);
if(stripos($url, 'https')!==false) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
}
if ($postfields) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
}
$response = curl_exec($curl);
return $response;
}
function getHiddenFormInputs($html) {
if(!preg_match('|<form[^>]+login_form[^>]+>.*</form>|Usi', $html, $form)) {
return '';
}
if(!preg_match_all('/<input[^>]+hidden[^>]*>/i', $form[0], $inputs)) {
return '';
}
$hiddenInputs = array();
foreach($inputs[0] as $input){
if (preg_match('|name\s*=\s*[\'"]([^\'"]+)[\'"]|i', $input, $name)) {
$hiddenInputs[$name[1]] = '';
if (preg_match('|value\s*=\s*[\'"]([^\'"]*)[\'"]|i', $input, $value)) {
$hiddenInputs[$name[1]] = $value[1];
}
}
}
return $hiddenInputs;
}
function serializePostFields($postFields) {
foreach($postFields as $key => $value) {
$value = urlencode($value);
$postFields[$key] = "$key=$value";
}
$postFields = implode($postFields, '&');
return $postFields;
}
?>

Ignoring the method being used (the API is more robust, and current method could break if they change the login), CURL is as secure as any standard request from a browser. From the script I can see you are using https for the request, so you should be fine.

cURL is not any more or less secure than Internet Explorer or Google Chrome.

Curl request will be as "safe" as going to the site with browser, but you should set CURLOPT_SSL_VERIFYPEER option to true and use CURLOPT_CAINFO to point to curl to the certificate when using HTTPS with CURL.
Check curl_setopt documentation.

Related

why does my function login Curl always return true? CodeIgniter

i try to login through website using cURL, i want to give validation login error. when i fail to login the page will show alert, if succesful to login the page still show alert. . what's wrong with my code, any solution? thanks
Here's my library code:
public function loginIdws($username ,$password){
$url = 'http://forum.idws.id/login/login';
$data = '_xfToken=&cookie_check=1&login='.$username.'&password='.$password.'&redirect=http://forum.idws.id/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR,"cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE,"cookie.txt");
curl_setopt($ch, CURLOPT_TIMEOUT,40000);
curl_setopt($ch, CURLOPT_HEADER,FALSE);
curl_setopt($ch, CURLOPT_NOBODY,FALSE);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/5.0 (Windows NT 6.1; rv:45.0) Gecko/20100101 Firefox/45.0");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_REFERER,$_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_POST,TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$baca = curl_exec($ch);
if ($baca=== false){
return false;
}else
{
return true;
}
$info = curl_getinfo($ch);
curl_setopt($ch,CURLOPT_URL,"http://forum.idws.id/account/");
curl_setopt($ch,CURLOPT_POST, 0);
$baca2 = curl_exec($ch);
return false;
curl_close($ch);
$pecah1 = explode('<fieldset>',$baca2);
$pecah2 = explode('</fieldset>',$pecah1[1]);
echo "<fieldset>";
echo $pecah2[0];
echo "</fieldset>";
}
this is my controller code :
public function loginn(){
$username= $this->input->post('login','true');
$password = $this->input->post('password','true');
if($this->ci_curl->loginIdws($username,$password)===false){
echo "<script> alert('Invalid Username & Password');
window.location.href='index';
</script>";
}else {
$this->load->view('curl/thread');
return true;
}
}
codes after never executed,
$baca = curl_exec($ch);
if ($baca=== false){
return false;
}else
{
return true;
}
because you return result anywhere
also curl_exec() can return different result dependent on your configuration
read more Anthony Hatzopoulos answer
I suggest use Requests for web requests in php
First of all check the response, what's it is returning, my guess, it is returning 'true'/'false', so $response==false is not same as say, $response=='false'. So, you either need to check the value or convert it to boolean before doing a strict check, something like:
$baca = curl_exec($ch);
$loginOk = $baca === 'true'? true: false;
return $loginOk;
OR do:
$baca = curl_exec($ch);
if ($baca == 'false'){
return false;
} else {
return true;
}
and it should as expected.

cURL login into ebay.co.uk [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I've been trying for some time now to use cURL to login to eBay.co.uk. The cookies are being set and the post data is being sent correctly however I am not sure that the cookie file is being read again or even set correctly for that matter since I'm getting a page from eBay that says I need to enable cookies in my browser.
Here is the cURL class I'm using:
class Curl {
private $ch;
private $cookie_path;
private $agent;
public function __construct($userId) {
$this->cookie_path = dirname(realpath(basename($_SERVER['PHP_SELF']))).'/cookies/' . $userId . '.txt';
$this->agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
}
private function init() {
$this->ch = curl_init();
}
private function close() {
curl_close ($this->ch);
}
private function setOptions($submit_url) {
curl_setopt($this->ch, CURLOPT_URL, $submit_url);
curl_setopt($this->ch, CURLOPT_USERAGENT, $this->agent);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch, CURLOPT_COOKIEFILE, $this->cookie_path);
curl_setopt($this->ch, CURLOPT_COOKIEJAR, $this->cookie_path);
}
public function curl_cookie_set($submit_url) {
$this->init();
$this->setOptions($submit_url);
$result = curl_exec ($this->ch);
$this->close();
return $result;
}
public function curl_post_request($referer, $submit_url, $data) {
$this->init();
$this->setOptions($submit_url);
$post = http_build_query($data);
curl_setopt($this->ch, CURLOPT_POST, 1);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($this->ch, CURLOPT_REFERER, $referer);
$result = curl_exec ($this->ch);
$this->close();
return $result;
}
public function curl_clean() {
// cleans and closes the curl connection
if (file_exists($this->cookie_path)) {
unlink($this->cookie_path);
}
if ($this->ch != '') {
curl_close ($this->ch);
}
}
}
Here is the test script, the login details are for a throwaway account, so feel free to test with them:
$curl = new Curl(md5(1)); //(md5($_SESSION['userId']));
$referer = 'http://ebay.co.uk';
$submit_url = "http://signin.ebay.co.uk/aw-cgi/eBayISAPI.dll";
$data['userid'] = "VitoGambino-us";
$data['pass'] = "P0wqw12vi";
$data['MfcISAPICommand'] = 'SignInWelcome';
$data['siteid'] = '0';
$data['co_partnerId'] = '2';
$data['UsingSSL'] = '0';
$data['ru'] = '';
$data['pp'] = '';
$data['pa1'] = '';
$data['pa2'] = '';
$data['pa3'] = '';
$data['i1'] = '-1';
$data['pageType'] = '-1';
$curl->curl_cookie_set($referer);
$result = $curl->curl_post_request($referer, $submit_url, $data);
echo $result;
Here is what the cookie files contents are:
# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.
www.ebay.co.uk FALSE / FALSE 0 JSESSIONID BDE9B23B829CA7DF2CC4D5880F5173A6
.ebay.co.uk TRUE / FALSE 0 ebay %5Esbf%3D%23%5Ecv%3D15555%5E
.ebay.co.uk TRUE / FALSE 1431871451 dp1 bu1p/QEBfX0BAX19AQA**53776c5b^
#HttpOnly_.ebay.co.uk TRUE / FALSE 0 s CgAD4ACBRl4pbYjJjZDk1YTAxM2UwYTU2YjYzYzRhYmU0ZmY2ZjcyODYBSgAXUZeKWzUxOTYzOGI5LjMuMS43LjY2LjguMC4xuMWzLg**
.ebay.co.uk TRUE / FALSE 1400335451 nonsession CgADLAAFRlj/jMgDKACBa/DpbYjJjZDk1YTAxM2UwYTU2YjYzYzRhYmU0ZmY2ZjcyODcBTAAXU3dsWzUxOTYzOGI5LjMuMS42LjY1LjEuMC4xhVUTMQ**
.ebay.co.uk TRUE / FALSE 1526479451 lucky9 4551358
I was able to figure it out.
eBay uses a pretty tricky method for logging in. It's a combination of cookies, hidden fields and a javascript redirect after successful login.
Here's how I solved it.
Newly modified class:
class Curl {
private $ch;
private $cookie_path;
private $agent;
// userId will be used later to keep multiple users logged
// into ebay site at one time.
public function __construct($userId) {
$this->cookie_path = dirname(realpath(basename($_SERVER['PHP_SELF']))).'/cookies/' . $userId . '.txt';
$this->agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
}
private function init() {
$this->ch = curl_init();
}
private function close() {
curl_close ($this->ch);
}
// Set cURL options
private function setOptions($submit_url) {
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
curl_setopt($this->ch, CURLOPT_URL, $submit_url);
curl_setopt($this->ch, CURLOPT_USERAGENT, $this->agent);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($this->ch, CURLOPT_COOKIEFILE, $this->cookie_path);
curl_setopt($this->ch, CURLOPT_COOKIEJAR, $this->cookie_path);
}
// Grab initial cookie data
public function curl_cookie_set($submit_url) {
$this->init();
$this->setOptions($submit_url);
curl_exec ($this->ch);
echo curl_error($this->ch);
}
// Grab hidden fields
public function get_form_fields($submit_url) {
curl_setopt($this->ch, CURLOPT_URL, $submit_url);
$result = curl_exec ($this->ch);
echo curl_error($this->ch);
return $this->getFormFields($result);
}
// Send login data
public function curl_post_request($referer, $submit_url, $data) {
$post = http_build_query($data);
curl_setopt($this->ch, CURLOPT_URL, $submit_url);
curl_setopt($this->ch, CURLOPT_POST, 1);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($this->ch, CURLOPT_REFERER, $referer);
$result = curl_exec ($this->ch);
echo curl_error($this->ch);
$this->close();
return $result;
}
// Show the logged in "My eBay" or any other page
public function show_page( $submit_url) {
curl_setopt($this->ch, CURLOPT_URL, $submit_url);
$result = curl_exec ($this->ch);
echo curl_error($this->ch);
return $result;
}
// Used to parse out form
private function getFormFields($data) {
if (preg_match('/(<form name="SignInForm".*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('Form not found.');
}
}
// Used to parse out hidden field names and values
private function getInputs($form) {
$inputs = array();
$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);
if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}
// Destroy cookie and close curl.
public function curl_clean() {
// cleans and closes the curl connection
if (file_exists($this->cookie_path)) {
unlink($this->cookie_path);
}
if ($this->ch != '') {
curl_close ($this->ch);
}
}
}
The actual code in use:
$curl = new Curl(md5(1)); //(md5($_SESSION['userId']));
$referer = 'http://ebay.com';
$formPage = 'http://signin.ebay.com/aw-cgi/eBayISAPI.dll?SignIn';
// Grab cookies from main page, ebay.com
$curl->curl_cookie_set($referer);
// Grab the hidden form fields and then set UsingSSL = 0
// Login with credentials and hidden fields
$data = $curl->get_form_fields($formPage);
$data['userid'] = "";
$data['pass'] = "";
$data['UsingSSL'] = '0';
// Post data to login page. Don't echo this result, there's a
// javascript redirect. Just do this to save login cookies
$formLogin = "https://signin.ebay.com/ws/eBayISAPI.dll?co_partnerId=2&siteid=3&UsingSSL=0";
$curl->curl_post_request($referer, $formLogin, $data);
// Use login cookies to load the "My eBay" page, viola, you're logged in.
$result = $curl->show_page('http://my.ebay.com/ws/eBayISAPI.dll?MyeBay');
// take out Javascript so it won't redirect to actualy ebay site
echo str_replace('<script', '<', $result);
I used some of the code posted here, thanks to drew010!

Faking Post Request with PHP Curl - Rejection

I am trying to build a script that posts information into the RoyalMail tracking system and extracts the output.
What I currently have is getting an error from their server - see the link, somehow it is detecting that I am not using their website as per normal and throwing me an error.
Things I think I have taken into account:
Using an exact copy of their form by parsing it beforehand (the post parameters)
Saving the cookies between each request
Accepting redirect headers
Providing a refer header that is actually valid (the previously visited page)
Does anyone know anything else I need to check or can figure out what I am doing wrong?
A full copy of the source is at EDIT: please see my answer below
Websites usually use 2 ways to detect if you are a human or a bot: HTTP REFERER and USER AGENT. I suggest you use Curl it specified user agent and referer (replace 'http://something/' with real URL of a page you would normally visit before navigating to the url you want to download with PHP):
<?php
$url = 'http://track2.royalmail.com/portal/rm/track';
$html = file_get_contents2($url, '');
$post['_dyncharset'] = 'ISO-8859-1';
$post['trackConsigniaPage'] = 'track';
$post['/rmg/track/RMTrackFormHandler.value.searchCompleteUrl'] = '/portal/rm/trackresults?catId=22700601&pageId=trt_rmresultspage';
$post['_D:/rmg/track/RMTrackFormHandler.value.searchCompleteUrl'] = '';
$post['/rmg/track/RMTrackFormHandler.value.invalidInputUrl'] = '/portal/rm/trackresults?catId=22700601&pageId=trt_rmresultspage&keyname=track_blank';
$post['_D:/rmg/track/RMTrackFormHandler.value.invalidInputUrl'] = '';
$post['/rmg/track/RMTrackFormHandler.value.searchBusyUrl'] = '/portal/rm/trackresults?catId=22700601&pageId=trt_busypage&keyname=3E_track';
$post['_D:/rmg/track/RMTrackFormHandler.value.searchBusyUrl'] = '';
$post['/rmg/track/RMTrackFormHandler.value.searchWaitUrl'] = '/portal/rm/trackresults?catId=22700601&timeout=true&pageId=trt_timeoutpage&keyname=3E_track';
$post['_D:/rmg/track/RMTrackFormHandler.value.searchWaitUrl'] = '';
$post['/rmg/track/RMTrackFormHandler.value.keyname'] = '3E_track';
$post['_D:/rmg/track/RMTrackFormHandler.value.keyname'] = '';
$post['/rmg/track/RMTrackFormHandler.value.previousTrackingNumber'] = '';
$post['_D:/rmg/track/RMTrackFormHandler.value.previousTrackingNumber'] = '';
$post['/rmg/track/RMTrackFormHandler.value.trackingNumber'] = 'ZW791944749GB';
$post['_D:/rmg/track/RMTrackFormHandler.value.trackingNumber'] = '';
$post['/rmg/track/RMTrackFormHandler.track.x'] = '50';
$post['/rmg/track/RMTrackFormHandler.track.y'] = '14';
$post['_D:/rmg/track/RMTrackFormHandler.track'] = '';
$post['/rmg/track/RMTrackFormHandler.value.day'] = '19';
$post['_D:/rmg/track/RMTrackFormHandler.value.day'] = '';
$post['/rmg/track/RMTrackFormHandler.value.month'] = '5';
$post['_D:/rmg/track/RMTrackFormHandler.value.month'] = '';
$post['/rmg/track/RMTrackFormHandler.value.year'] = '2012';
$post['_D:/rmg/track/RMTrackFormHandler.value.year'] = '';
$post['_DARGS'] = '/portal/rmgroup/apps/templates/html/rm/rmTrackResultPage.jsp';
$url2 = 'http://track2.royalmail.com/portal/rm?_DARGS=/portal/rmgroup/apps/templates/html/rm/rmTrackAndTraceForm.jsp';
$html2 = file_get_contents2($url2, $url, $post);
echo $html2;
function file_get_contents2($address, $referer, $post = false)
{
$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $address);
curl_setopt($c, CURLOPT_USERAGENT, $useragent);
curl_setopt($c, CURLOPT_HEADER, 0);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
if ($post)
{
$postF = http_build_query($post);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $postF);
}
curl_setopt($c, CURLOPT_COOKIEJAR, 'cookie.txt');
//curl_setopt($c, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($c, CURLOPT_REFERER, $referer);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
if (!$data = curl_exec($c))
{
return false;
}
return $data;
}
The above updated code returned me:
Item ZW791944749GB was posted at 1 High Street RG17 9TJ on 19/05/12 and is being progressed through our network for delivery.
So it seems it works.
I have now fixed it, the problem was with PHP curl and following redirects, it seems that it doesn't always post the request data and sends a GET request when following.
To deal with this I disabled curl follow location with curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); and then built a follow location system myself that works recursively. Essentially it extracts the location header from the response, checks for a 301 or a 302 and then runs the method again as required.
This means the information will definitely be POSTED again.
I also improved the user agent string, simply copying my current one on the basis it won't be blocked for a long while as in 2012 it is in active use!
Here is a final copy of the curl class (in case the link dies - been down voted for that in the past) which is working:
/**
* Make a curl request respecting redirects
* Also supports posts
*/
class pegCurlRequest {
private $url, $postFields = array(), $referer = NULL, $timeout = 3;
private $debug = false, $postString = "";
private $curlInfo = array();
private $content = "";
private $response_meta_info = array();
static $cookie;
function __construct($url, $postFields = array(), $referer = NULL, $timeout = 3) {
$this->setUrl($url);
$this->setPost($postFields);
$this->setReferer($referer);
$this->setTimeout($timeout);
if(empty(self::$cookie)) self::$cookie = tempnam("/tmp", "pegCurlRequest"); //one time cookie
}
function setUrl($url) {
$this->url = $url;
}
function setTimeout($timeout) {
$this->timeout = $timeout;
}
function setPost($postFields) {
if(is_array($postFields)) {
$this->postFields = $postFields;
}
$this->updatePostString();
}
function updatePostString() {
//Cope with posting
$this->postString = "";
if(!empty($this->postFields)) {
foreach($this->postFields as $key=>$value) { $this->postString .= $key.'='.$value.'&'; }
$this->postString= rtrim($this->postString,'&'); //Trim off the waste
}
}
function setReferer($referer) {
//Set a referee either specified or based on the url
$this->referer = $referer;
}
function debugInfo() {
//Debug
if($this->debug) {
echo "<table><tr><td colspan='2'><b><u>Pre Curl Request</b><u></td></tr>";
echo "<tr><td><b>URL: </b></td><td>{$this->url}</td></tr>";
if(!empty(self::$cookie)) echo "<tr><td><b>Cookie String: </b></td><td>".self::$cookie."</td></tr>";
if(!empty($this->referer)) echo "<tr><td><b>Referer: </b></td><td>".$this->referer."</td></tr>";
if(!empty($this->postString)) echo "<tr><td><b>Post String: </b></td><td>".$this->postString."</td></tr>";
if(!empty($this->postFields)) {
echo "<tr><td><b>Post Values:</b></td><td><table>";
foreach($this->postFields as $key=>$value)
echo "<tr><td>$key</td><td>$value</td></tr>";
echo "</table>";
}
echo "</td></tr></table><br />\n";
}
}
function debugFurtherInfo() {
//Debug
if($this->debug) {
echo "<table><tr><td colspan='2'><b><u>Post Curl Request</b><u></td></tr>";
echo "<tr><td><b>URL: </b></td><td>{$this->url}</td></tr>";
if(!empty($this->referer)) echo "<tr><td><b>Referer: </b></td><td>".$this->referer."</td></tr>";
if(!empty($this->curlInfo)) {
echo "<tr><td><b>Curl Info:</b></td><td><table>";
foreach($this->curlInfo as $key=>$value)
echo "<tr><td>$key</td><td>$value</td></tr>";
echo "</table>";
}
echo "</td></tr></table><br />\n";
}
}
/**
* Make the actual request
*/
function makeRequest($url=NULL) {
//Shorthand request
if(!is_null($url))
$this->setUrl($url);
//Output debug info
$this->debugInfo();
//Using a shared cookie
$cookie = self::$cookie;
//Setting up the starting information
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 Safari/536.11" );
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
//register a callback function which will process the headers
//this assumes your code is into a class method, and uses $this->readHeader as the callback //function
curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(&$this,'readHeader'));
//Some servers (like Lighttpd) will not process the curl request without this header and will return error code 417 instead.
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
//Referer
if(empty($this->referer)) {
curl_setopt($ch, CURLOPT_REFERER, dirname($this->url));
} else {
curl_setopt($ch, CURLOPT_REFERER, $this->referer);
}
//Posts
if(!empty($this->postFields)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postString);
}
//Redirects, transfers and timeouts
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
//Debug
if($this->debug) {
curl_setopt($ch, CURLOPT_VERBOSE, true); // logging stuffs
curl_setopt($ch, CURLINFO_HEADER_OUT, true); // enable tracking
}
//Get the content and the header info
$content = curl_exec($ch);
$response = curl_getinfo($ch);
//get the default response headers
$headers = curl_getinfo($ch);
//add the headers from the custom headers callback function
$this->response_meta_info = array_merge($headers, $this->response_meta_info);
curl_close($ch); //be nice
//Curl info
$this->curlInfo = $response;
//Output debug info
$this->debugFurtherInfo();
//Are we being redirected?
if ($response['http_code'] == 301 || $response['http_code'] == 302) {
$location = $this->getHeaderLocation();
if(!empty($location)) { //the location exists
$this->setReferer($this->getTrueUrl()); //update referer
return $this->makeRequest($location); //recurse to location
}
}
//Is there a javascript redirect on the page?
elseif (preg_match("/window\.location\.replace\('(.*)'\)/i", $content, $value) ||
preg_match("/window\.location\=\"(.*)\"/i", $content, $value)) {
$this->setReferer($this->getTrueUrl()); //update referer
return $this->makeRequest($value[1]); //recursion
} else {
$this->content = $content; //set the content - final page
}
}
/**
* Get the url after any redirection
*/
function getTrueUrl() {
return $this->curlInfo['url'];
}
function __toString() {
return $this->content;
}
/**
* CURL callback function for reading and processing headers
* Override this for your needs
*
* #param object $ch
* #param string $header
* #return integer
*/
private function readHeader($ch, $header) {
//This is run for every header, use ifs to grab and add
$location = $this->extractCustomHeader('Location: ', '\n', $header);
if ($location) {
$this->response_meta_info['location'] = trim($location);
}
return strlen($header);
}
private function extractCustomHeader($start,$end,$header) {
$pattern = '/'. $start .'(.*?)'. $end .'/';
if (preg_match($pattern, $header, $result)) {
return $result[1];
} else {
return false;
}
}
function getHeaders() {
return $this->response_meta_info;
}
function getHeaderLocation() {
return $this->response_meta_info['location'];
}
}
Well first of all, you are talking about the Royal Mail. So I'm not sure if this simple little trick would trip them up...
But what you could try is spoofing your user agent with a quick ini_set() -
ini_set('user_agent', 'Mozilla/5.0 (X11; CrOS i686 1660.57.0) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.46 Safari/535.19'
That's an Ubuntu chrome user agent string.
The cURL user agent string would look quite different. For example:
curl/7.15.5 (i686-redhat-linux-gnu) libcurl/7.15.5 OpenSSL/0.9.8b zlib/1.2.3 libidn/0.6.5
It's a long shot - but they might be rejecting requests that are not originating from recognized browsers.

Paypal NVP with php error

I am trying to get up and running using Paypal's NVP interface for my website to process my custom cart. I've downloaded their sample code (here) and have tried to run unaltered without success. Any function I choose (e.g. express checkout sale) gives the curl_errno() error: Error Number: 3 Error Message: No URL set! I have tried this both on localhost and on my hosted site.
hash_call() is the function processing the call to Paypal. The code which calls hash_call() is also included below.Their code that sets urls is:
$returnURL =urlencode($url.'/ReviewOrder.php?currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType);
$cancelURL =urlencode("$url/SetExpressCheckout.php?paymentType=$paymentType" );
I thought the cancelURL line looked off and modified it to:
$cancelURL =urlencode($url.'/SetExpressCheckout.php?paymentType='.$paymentType );
Neither have worked. Any help would be appreciated. I've never worked with curl.
require_once 'CallerService.php';
session_start();
if(! isset($_REQUEST['token'])) {
/* The servername and serverport tells PayPal where the buyer
should be directed back to after authorizing payment.
In this case, its the local webserver that is running this script
Using the servername and serverport, the return URL is the first
portion of the URL that buyers will return to after authorizing payment
*/
$serverName = $_SERVER['SERVER_NAME'];
$serverPort = $_SERVER['SERVER_PORT'];
$url=dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);
$currencyCodeType=$_REQUEST['currencyCodeType'];
$paymentType=$_REQUEST['paymentType'];
$personName = $_REQUEST['PERSONNAME'];
$SHIPTOSTREET = $_REQUEST['SHIPTOSTREET'];
$SHIPTOCITY = $_REQUEST['SHIPTOCITY'];
$SHIPTOSTATE = $_REQUEST['SHIPTOSTATE'];
$SHIPTOCOUNTRYCODE = $_REQUEST['SHIPTOCOUNTRYCODE'];
$SHIPTOZIP = $_REQUEST['SHIPTOZIP'];
$L_NAME0 = $_REQUEST['L_NAME0'];
$L_AMT0 = $_REQUEST['L_AMT0'];
$L_QTY0 = $_REQUEST['L_QTY0'];
$L_NAME1 = $_REQUEST['L_NAME1'];
$L_AMT1 = $_REQUEST['L_AMT1'];
$L_QTY1 = $_REQUEST['L_QTY1'];
/* The returnURL is the location where buyers return when a
payment has been succesfully authorized.
The cancelURL is the location buyers are sent to when they hit the
cancel button during authorization of payment during the PayPal flow
*/
$returnURL =urlencode($url.'/ReviewOrder.php?currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType);
$cancelURL =urlencode($url.'/SetExpressCheckout.php?paymentType='.$paymentType );
/* Construct the parameter string that describes the PayPal payment
the varialbes were set in the web form, and the resulting string
is stored in $nvpstr
*/
$itemamt = 0.00;
$itemamt = $L_QTY0*$L_AMT0+$L_AMT1*$L_QTY1;
$amt = 5.00+2.00+1.00+$itemamt;
$maxamt= $amt+25.00;
$nvpstr="";
/*
* Setting up the Shipping address details
*/
$shiptoAddress = "&SHIPTONAME=$personName&SHIPTOSTREET=$SHIPTOSTREET&SHIPTOCITY=$SHIPTOCITY&SHIPTOSTATE=$SHIPTOSTATE&SHIPTOCOUNTRYCODE=$SHIPTOCOUNTRYCODE&SHIPTOZIP=$SHIPTOZIP";
$nvpstr="&ADDRESSOVERRIDE=1$shiptoAddress&L_NAME0=".$L_NAME0."&L_NAME1=".$L_NAME1."&L_AMT0=".$L_AMT0."&L_AMT1=".$L_AMT1."&L_QTY0=".$L_QTY0."&L_QTY1=".$L_QTY1."&MAXAMT=".(string)$maxamt."&AMT=".(string)$amt."&ITEMAMT=".(string)$itemamt."&CALLBACKTIMEOUT=4&L_SHIPPINGOPTIONAMOUNT1=8.00&L_SHIPPINGOPTIONlABEL1=UPS Next Day Air&L_SHIPPINGOPTIONNAME1=UPS Air&L_SHIPPINGOPTIONISDEFAULT1=true&L_SHIPPINGOPTIONAMOUNT0=3.00&L_SHIPPINGOPTIONLABEL0=UPS Ground 7 Days&L_SHIPPINGOPTIONNAME0=Ground&L_SHIPPINGOPTIONISDEFAULT0=false&INSURANCEAMT=1.00&INSURANCEOPTIONOFFERED=true&CALLBACK=https://www.ppcallback.com/callback.pl&SHIPPINGAMT=8.00&SHIPDISCAMT=-3.00&TAXAMT=2.00&L_NUMBER0=1000&L_DESC0=Size: 8.8-oz&L_NUMBER1=10001&L_DESC1=Size: Two 24-piece boxes&L_ITEMWEIGHTVALUE1=0.5&L_ITEMWEIGHTUNIT1=lbs&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType."&PAYMENTACTION=".$paymentType;
/* Make the call to PayPal to set the Express Checkout token
If the API call succeded, then redirect the buyer to PayPal
to begin to authorize payment. If an error occured, show the
resulting errors
*/
$resArray=hash_call("SetExpressCheckout",$nvpstr);
*********************************************************************************
/**
* hash_call: Function to perform the API call to PayPal using API signature
* #methodName is name of API method.
* #nvpStr is nvp string.
* returns an associtive array containing the response from the server.
*/
function hash_call($methodName,$nvpStr)
{
//declaring of global variables
global $API_Endpoint,$version,$API_UserName,$API_Password,$API_Signature,$nvp_Header, $subject, $AUTH_token,$AUTH_signature,$AUTH_timestamp;
// form header string
$nvpheader=nvpHeader();
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
//WARNING: this would prevent curl from detecting a 'man in the middle' attack
$ch = curl_init();
//curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
//curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt ($ch, CURLOPT_CAINFO, "c:/xampp/apache/cacert.pem");
//in case of permission APIs send headers as HTTPheders
if(!empty($AUTH_token) && !empty($AUTH_signature) && !empty($AUTH_timestamp))
{
$headers_array[] = "X-PP-AUTHORIZATION: ".$nvpheader;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_array);
curl_setopt($ch, CURLOPT_HEADER, false);
}
else
{
$nvpStr=$nvpheader.$nvpStr;
}
//if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
//Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
if(USE_PROXY)
curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT);
//check if version is included in $nvpStr else include the version.
if(strlen(str_replace('VERSION=', '', strtoupper($nvpStr))) == strlen($nvpStr)) {
$nvpStr = "&VERSION=" . urlencode($version) . $nvpStr;
}
$nvpreq="METHOD=".urlencode($methodName).$nvpStr;
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
//getting response from server
$response = curl_exec($ch);
//convrting NVPResponse to an Associative Array
$nvpResArray=deformatNVP($response);
$nvpReqArray=deformatNVP($nvpreq);
$_SESSION['nvpReqArray']=$nvpReqArray;
if (curl_errno($ch)) {
// moving to display page to display curl errors
$_SESSION['curl_error_no']=curl_errno($ch) ;
$_SESSION['curl_error_msg']=curl_error($ch);
$location = "APIError.php";
header("Location: $location");
} else {
//closing the curl
curl_close($ch);
}
return $nvpResArray;
}
Try this class,
<?php
class ZC_Paypal
{
public $API_USERNAME;
public $API_PASSWORD;
public $API_SIGNATURE='xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
public $API_ENDPOINT;
public $USE_PROXY;
public $PROXY_HOST;
public $PROXY_PORT;
public $PAYPAL_URL;
public $VERSION;
public $NVP_HEADER;
public $SSLCERTPATH;
function __construct($PROXY_HOST, $PROXY_PORT, $IS_ONLINE = FALSE, $USE_PROXY = FALSE, $VERSION = '51.0', $api_url)
{
/*$this->API_USERNAME = $API_USERNAME;
$this->API_PASSWORD = $API_PASSWORD;
$this->API_SIGNATURE = $API_SIGNATURE;*/
//$this->API_ENDPOINT = 'https://api-3t.sandbox.paypal.com/nvp';
$this->API_ENDPOINT = $api_url;
$this->USE_PROXY = $USE_PROXY;
if($this->USE_PROXY == true)
{
$this->PROXY_HOST = $PROXY_HOST;
$this->PROXY_PORT = $PROXY_PORT;
}
else
{
$this->PROXY_HOST = '127.0.0.1';
$this->PROXY_PORT = '808';
}
if($IS_ONLINE == FALSE)
{
$this->PAYPAL_URL = 'https://api-3t.sandbox.paypal.com/nvp';
}
else
{
$this->PAYPAL_URL = 'https://api-3t.paypal.com/nvp';
}
$this->VERSION = $VERSION;
}
function hash_call($methodName,$nvpStr,$uname,$pwd,$api_url,$sslcerpath)
{
$this->API_ENDPOINT = $api_url;
$this->API_PASSWORD = $pwd;
$this->API_USERNAME = $uname;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->API_ENDPOINT);
//curl_setopt($ch, CURLOPT_SSLCERT, $sslcerpath);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
if($this->USE_PROXY)
{
curl_setopt ($ch, CURLOPT_PROXY, $this->PROXY_HOST.":".$this->PROXY_PORT);
}
$nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode($this->VERSION)."&PWD=".urlencode($this->API_PASSWORD)."&USER=".urlencode($this->API_USERNAME)."&SIGNATURE=".urlencode($this->API_SIGNATURE).$nvpStr;
curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
$response = curl_exec($ch);
$nvpResArray=$this->deformatNVP($response);
$nvpReqArray=$this->deformatNVP($nvpreq);
$_SESSION['nvpReqArray']=$nvpReqArray;
if (curl_errno($ch))
{
die("CURL send a error during perform operation: ".curl_errno($ch));
}
else
{
curl_close($ch);
}
return $nvpResArray;
}
function deformatNVP($nvpstr)
{
$intial=0;
$nvpArray = array();
while(strlen($nvpstr))
{
$keypos= strpos($nvpstr,'=');
$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
$keyval=substr($nvpstr,$intial,$keypos);
$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
$nvpArray[urldecode($keyval)] =urldecode( $valval);
$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
}
return $nvpArray;
}
function __destruct()
{
}
}
and call above class like,
....
$currencyCode="USD";
//$paymentAction = urlencode("Sale");
$paymentAction = urlencode("Authorization");
$nvpRecurring = '';
$methodToCall = 'doDirectPayment';
$nvpstr='&PAYMENTACTION='.$paymentAction.'&AMT='.$amount.'&CREDITCARDTYPE='.$creditCardType.'&ACCT='.$creditCardNumber.'&EXPDATE='.$padDateMonth.$expDateYear.'&CVV2='.$cvv2Number.'&FIRSTNAME='.$firstName.'&LASTNAME='.$lastName.'&STREET='.$address1.'&CITY='.$city.'&STATE='.$state.'&ZIP='.$zip.'&COUNTRYCODE='.$country.'&CURRENCYCODE='.$currencyCode.$nvpRecurring;
$paypalPro = new ZC_Paypal( '', '', FALSE, FALSE,'51.0',Zend_Registry::get("admin_paypal_pro_url"));
$resArray = $paypalPro->hash_call($methodToCall,$nvpstr,Zend_Registry::get("admin_paypal_user_name"), Zend_Registry::get("admin_paypal_password"),Zend_Registry::get("admin_paypal_pro_url"),Zend_Registry::get("admin_paypal_ssl_path"));
$ack = strtoupper($resArray["ACK"]);
//echo '<pre>'; print_r($resArray); exit;
if($ack!="SUCCESS")
{
if(!in_array($resArray["L_LONGMESSAGE0"], array('Internal Error', 'CURL send a error during perform operation: 6')))
echo $resArray["L_LONGMESSAGE0"];
else
echo 'Transaction Failed, Try again later.';
}
else{
// if success .....
}
pass credential in respective variable,i am using zend, so try to use core php here...

Login via Google Apps

How can I authenticate my users via our their Google Apps account.
I also need access to their email.
I've read Oauth is needed but I have no idea if that is correct.
I'm using PHP.
I use this code in a library I wrote to pull contact information from gmail. http://www.oriontechnologysolutions.com/programming/libgoog_php.
This particular function will validate an account and pass back an Auth Token used to access Google Services.
function login() {
$response = Array();
if(isset($this->domain))
$email = $this->username . '#' . $this->domain;
else
$email = $this->username;
$requestString = "service=".$this->service."&Email=".urlencode($email)."&Passwd=".urlencode($this->passwd)."&source=".self::source;
$c = curl_init();
curl_setopt($c, CURLOPT_URL, self::loginUrl);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, $requestString);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($c);
$httpCode = curl_getinfo($c, CURLINFO_HTTP_CODE);
foreach(explode("\n", $res) as $line) {
if(strpos($line, "=") != false) {
gooDebug("Exploding $line\n", 4);
list($name, $value) = explode("=", $line);
$response[$name] = $value;
}
}
if($httpCode !=200)
return($response);
$this->authTok = $response['Auth'];
return($this->authTok);
}

Categories