PHP redirect based on IP location - php

I have a multilingual site with an 'index.php' sitting on example.com domain. This index.php should have this redirection code so when users go to 'example.com' they get redirected to either the French or English version of the site.
In its simplest form I'd like the conditional statement to read:
If IP is based in France redirect to example.com/fr else if anywhere else in the world redirect to example.com/en
How might I set this up using PHP?

Have a look at http://www.geoplugin.com/webservices/php and use a cache to store the IP address as not to make the request every time.
<?php
error_reporting(-1);
ini_set("display_errors", "On");
$ch = curl_init('http://www.geoplugin.net/php.gp?ip={the IP address, used mine for example}');
if (!$ch) {
die('Failed CURL');
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$serverResponse = curl_exec($ch);
if (!$serverResponse) {
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
throw new Exception('HTTP error: ' . $code);
}
die(print_r($serverResponse));
Will result in:
Array
(
[geoplugin_request] => My IP
[geoplugin_status] => 206
[geoplugin_credit] => Some of the returned data includes GeoLite data created by MaxMind, available from <a href=\'http://www.maxmind.com\'>http://www.maxmind.com</a>.
[geoplugin_city] =>
[geoplugin_region] =>
[geoplugin_areaCode] => 0
[geoplugin_dmaCode] => 0
[geoplugin_countryCode] => GB
[geoplugin_countryName] => United Kingdom
[geoplugin_continentCode] => EU
[geoplugin_latitude] => 51.5
[geoplugin_longitude] => -0.13
[geoplugin_regionCode] =>
[geoplugin_regionName] =>
[geoplugin_currencyCode] => GBP
[geoplugin_currencySymbol] => £
[geoplugin_currencySymbol_UTF8] => £
[geoplugin_currencyConverter] => 0.6003
)
So use the country code.

Related

TCP connection reset by peer - Salesforce - PHP

Suddenly we start getting “TCP connection reset by peer” response from “Salesforce” after sending lead information using web services.
Technical Stack used at our end:
OS: Redhat Linux (RHEL)
Web Server: APACHE
Web Scripting Language: PHP
Used CURL for sending the details.
Code snippet for sending lead generation requested to Salesforce is ….
/*****************************************************************************************************/
/* Purpose : Sending request to sales-force for lead generation
/* Inputs : $pStrPostArr :: Post data array.
/* Returns : None.
/* Created By : Jaiswar Vipin Kumar R.
/*****************************************************************************************************/
function send($pStrPostArr = array()){
/* if post data is empty then do needful */
if (empty($pStrPostArr)){
/* return status */
return false;
}
/* set POST variables */
$strDestiantionURL = 'https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8';
/* removed used index */
unset($pStrPostArr['desitnationURL']);
/* if destination URL is not set then do needful */
if (empty($strDestiantionURL)){
/* return status */
return false;
}
/* variable initialization */
$strFields = '';
/* url-ify the data for the POST */
foreach($pStrPostArr as $strKey=>$strValue) {
if($strFields == ''){
$strFields .= $strKey.'='.$strValue;
}else{
$strFields .= '&'.$strKey.'='.$strValue;
}
}
// rtrim($strFields,'&');
if(isset($_COOKIE['debug'])){
//print_r($pStrPostArr);
echo $strFields;exit;
}
/* open connection */
$ch = curl_init($strDestiantionURL);
/* set the url, number of POST vars, POST data */
curl_setopt($ch,CURLOPT_URL,$strDestiantionURL);
curl_setopt($ch,CURLOPT_POST,count($pStrPostArr));
curl_setopt($ch,CURLOPT_POSTFIELDS,$strFields);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
/* execute post */
$this->_strReponse = curl_exec($ch);
/* Request Body */
$this->_strRequestBody = curl_getinfo($ch);
if($this->_strReponse === FALSE){
$this->_strError = curl_error($ch);
}
/* close connection */
curl_close($ch);
}
And Send Lead Information DataSet is :
Array
(
[desitnationURL] => https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8
[first_name] => Jaiswar
[last_name] => Vipin+Kumar+R
[company] => PocketApp
[job_title__c] =>
[country_c__c] =>
[appdetail] => app development & designing
[email] => vipin.jaiswar%40pocketapp.co.uk
[phone] => %2B919773596947
[Lead_Budget__c] => Undisclosed
[description] => Fill+out+the+form+below+with+your+requirments+and+we+will+get+back+to+you+as+soon+as+possible.+Alternatively%2C+send+an+email+to+sales%40pocketapp.co.uk+or+give+us+a+call+on+%2B44+20+7183+4388
[oid] => XXXXXXXXXXXXXXX
[sfga] => XXXXXXXXXXXXXXX
[retURL] => https://www.pocketapp.co.uk/thank-you/
[lead_source] => Web
[source__c] => https://www.semrush.com/siteaudit/campaign/472189/review/
[medium__c] => -
[campaign__c] => -
[term__c] => -
[content__c] =>
[Visitor_ID__c] => -
[gclid__c] => -
[Count_of_Sessions__c] => 1
[Count_of_Pageviews__c] => 1
[00ND0000006RIpG] =>
[00ND0000006RHJY] =>
[00ND0000006RHJd] =>
[00ND0000006RHJi] =>
[00ND0000006RHJs] =>
[00ND0000006RHJn] =>
[00ND00000064Guy] =>
[00ND00000064Gv3] =>
)
Can you please assist us, what changes we need to make our end to make this start working as it was?
Salesforce moved the web2lead endpoint, you need to change your destination URL to use webto.salesforce.com instead of www.salesforce.com
see this KB article.

CyberSource Secure Acceptance integration with REST Api in php

I'm trying to integrate Cyber Source Payment gateway in php using REST API. And I found following reference link in github
After required changes finally I can able to login (Authenticate) to Cyber source but, Im getting below error. (I can check the logs from Cyber Source)
req_reference_number: 474 => ERROR 101 - Request parameters are invalid or missing
signed: true
Array
(
[auth_trans_ref_no] => 474
[decision] => ERROR
[message] => Request parameters are invalid or missing
[reason_code] => 101
[req_access_key] => 5e00e27842d73381b0**************
[req_amount] => 569
[req_bill_to_address_city] => Mountain View
[req_bill_to_address_country] => US
[req_bill_to_address_line1] => 1 My Apartment
[req_bill_to_address_line2] => 2 nd street
[req_bill_to_address_postal_code] => 94043
[req_bill_to_address_state] => CA
[req_bill_to_email] => someemail#somedomain.com
[req_bill_to_forename] => Elavarasan
[req_bill_to_phone] => 6508764564
[req_bill_to_surname] => Natarajan
[req_currency] => USD
[req_customer_ip_address] => 127.0.0.1
[req_device_fingerprint_id] => v1rh0p44gpnhag1a7mfp9tst25
[req_item_0_code] => KFLTFDIV
[req_item_0_name] => KFLTFDIV
[req_item_0_quantity] => 1
[req_item_0_sku] => sku001
[req_item_0_unit_price] => 20.00
[req_item_1_code] => KFLTFD70
[req_item_1_name] => KFLTFD70
[req_item_1_quantity] => 1
[req_item_1_sku] => sku002
[req_item_1_unit_price] => 10.00
[req_line_item_count] => 2
[req_locale] => en-us
[req_merchant_defined_data1] => MDD1
[req_merchant_defined_data2] => MDD2
[req_merchant_defined_data3] => MDD3
[req_merchant_defined_data4] => MDD4
[req_merchant_descriptor] => Krungsri
[req_override_custom_cancel_page] => http://localhost/cyphp/sa-wm/response.php
[req_override_custom_receipt_page] => http://localhost/cyphp/sa-wm/response.php
[req_profile_id] => *******************************
[req_reference_number] => 474
[req_transaction_type] => sale
[req_transaction_uuid] => 5aa6329409169
[required_fields] => payment_method
[signature] => IJ0iEsOJLZe2W4dNrogdzp8op8Evon2wU1KvA3W6SzM=
[signed_date_time] => 2018-03-12T07:57:00Z
[signed_field_names] => decision,req_access_key,req_profile_id,req_transaction_uuid,req_transaction_type,req_reference_number,req_amount,req_currency,req_line_item_count,req_locale,req_override_custom_receipt_page,req_override_custom_cancel_page,auth_trans_ref_no,req_item_0_code,req_item_0_name,req_item_0_quantity,req_item_0_sku,req_item_0_unit_price,req_item_1_code,req_item_1_name,req_item_1_quantity,req_item_1_sku,req_item_1_unit_price,req_bill_to_forename,req_bill_to_surname,req_bill_to_email,req_bill_to_phone,req_bill_to_address_line1,req_bill_to_address_line2,req_bill_to_address_city,req_bill_to_address_state,req_bill_to_address_country,req_bill_to_address_postal_code,req_customer_ip_address,req_device_fingerprint_id,req_merchant_defined_data1,req_merchant_defined_data2,req_merchant_defined_data3,req_merchant_defined_data4,req_merchant_descriptor,required_fields,reason_code,message,signed_field_names,signed_date_time
[utf8] => ✓
)
If I rename or remove any parameter, then authentication is failed. So I hope that, I'm passing some wrong value. But I couldn't find out which one is..
I tried to change almost every field values which I'm passing, but every time getting same error
ERROR 101 - Request parameters are invalid or missing
Finally I found sample code (php) from Cyber Source, we just have to configure as per the credential. Here is the link
Source Code
You have to define you Secret key in security.php file
define ('SECRET_KEY', '7f15d699ff14461b9a84*****');
And,
access_key and profile_id in signeddatafields.php file
<input type="hidden" name="access_key" value="5e00e27842d73******">
<input type="hidden" name="profile_id" value="43C533AC-****-****-****-*********">
That's it.
I only did the SOAP as well, but after a look at their rest v1 example, it looks like the api key and secret key are passed to create a paytoken in the Apiclient. An authorization payment should be something like this(after u install the sdk):
<?php
use \CyberSource\Authorizations as Authorizations;
use \CyberSource\Configuration as Configuration;
class CyberSource {
private $config;
function __construct($apiKey, $secretKey) {
// pass apikey and secretkey to configuration
$this->config = new Configuration($apiKey, $secretKey);
}
private function runAuth($this->config) {
$api = new Authorizations($this->config);
$jsonPayload = // ur json request payload
try{
// pass the request json payload object
$response = $api->createAuthorization($jsonPayload);
} catch (\E $e) {
//throw error here
}
}
}
if you have to use v2 then u need to read this pdf there are several things you need to add to the header for account authentication.

make same Rest call from azure to sugarcrm return different result

my sugarcrm site local on a linux ubantu site , and I write some PHP files make rest call to this site , these PHP files on azure cloud.
I find even for a simple rest call , sometimes it will return correct result , but sometimes it return "Invalid session" , just like below :
Array ( [name] => Invalid Session ID [number] => 11 [description] => The session ID is invalid )
I mean when I refresh the request php constently , what it return is not certain . If I locate these PHP file in my local machine , not azure , then no matter how many request I test , all will get correct result.
my rest request 's sequence is :
first login with admin username and pwd like below :
$url = "http://crm.abc.xyz/service/v4_1/rest.php";
ini_set('max_execution_time', 300);
function restRequest($method, $arguments){
global $url;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$post = array(
"method" => $method,
"input_type" => "JSON",
"response_type" => "JSON",
"rest_data" => json_encode($arguments),
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($curl);
curl_close($curl);
return json_decode($result,1);
}
$carrierID = '9';
$userAuth = array(
'user_name' => 'admin',
'password' => md5('XXXXXXX'),
);
$appName = 'My SuiteCRM REST Client';
$nameValueList = array();
$args = array(
'user_auth' => $userAuth,
'application_name' => $appName,
'name_value_list' => $nameValueList);
$result = restRequest('login',$args);
$sessId = $result['id'];
once get return session id into variable $sessId , use this session to make other rest call :
$entryArgs = array(
'session' => $sessId,
'module_name' => 'Accounts',
'query' => "carrierid_c ='999'",
'max_results' => 2,
'deleted' => 0,
);
$result = restRequest('get_entry_list',$entryArgs);
print_r($result);
when print_r($result); sometimes it display :
Array ( [result_count] => 0 [total_count] => 0 [next_offset] => 0 [entry_list] => Array ( ) [relationship_list] => Array ( ) )
mean no this account , this is correct ,
but somethimes it display :
Array ( [name] => Invalid Session ID [number] => 11 [description] => The session ID is invalid )
My guess is when the request send to ubantu site from azure , it maybe from different instance , so sugarcrm at ubantu recv same user 's request from different IP and think it is fake session , I do not know if this guess is correct , also do not know how to fix it in azure , appreciate for your help .
I have find the answer , azure do send request to sugarcrm var different IP , to avoid "invalid session " , I need uncheck "validate client IP" in system setting ----> advance

Retrieve YouTube video details, including description from video URL using PHP?

After searching stackoverflow, I've found: How can I retrieve YouTube video details from video URL using PHP?
using the following code (I have changed to https instead of http and also added $_GET['v'] for getting video code from browser URL):
function get_youtube($url) {
$youtube = "https://www.youtube.com/oembed?url=". $url ."&format=json";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
return json_decode($return, true);
}
$url = 'https://www.youtube.com/watch?v=' . $_GET['v'];
// Display Data
echo '<pre>';
print_r(get_youtube($url));
echo '</pre>';
I was able to get the following result:
Array
(
[thumbnail_url] => https://i.ytimg.com/vi/AhN5MbTJ0pk/hqdefault.jpg
[version] => 1.0
[type] => video
[html] => <iframe width="480" height="270" src="https://www.youtube.com/embed/AhN5MbTJ0pk?feature=oembed" frameborder="0" allowfullscreen></iframe>
[provider_url] => https://www.youtube.com/
[thumbnail_width] => 480
[width] => 480
[thumbnail_height] => 360
[author_url] => https://www.youtube.com/user/AndreasChoice
[author_name] => AndreasChoice
[title] => GROSS SMOOTHIE CHALLENGE! ft. Tealaxx2
[height] => 270
[provider_name] => YouTube
)
Which is great, but I also need to retrieve the full 'description' of the video that is missing. How can I achieve this? Thank you.
In order to receive the description of a video you have 2 options.
Use an API.
Crawl the website.
The API that you need is under googleapis.com domain.
The url that you need to use is:
https://www.googleapis.com/youtube/v3/videos?id=VIDEO_ID&key=YOUR_API_KEY&fields=items(id,snippet(description))&part=snippet
Notice that you have to change the VIDEO_ID and YOUR_API_KEY.
To get an API key follow these instructions: link.
Building a web crawler is more complex.
Try following this tutorial to build your own web crawler here

Perl - LWP API Post

I'm trying to post a new item to a listing website using LWP. The listing website provides an example of how to post the data but using PHP, I’ve therefore tried to reproduce the solution but in Perl.
This is the PHP example.
$postData = array('type' => 'fixedPrice',
'item' => array(
'id_country' => 0,
'id_category' => 80,
'fixed_price' => '1.00',
'currency' => 'EUR',
'title' => 'My title',
'personal_reference' => 'My personal ref',
));
//RESOURCE CALL WITH POST METHOD
$url = 'http://correct.server.address/item?token=MyPersonalToken';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, http_build_query($postData) );
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$xml_response = curl_exec($ch);
My Perl solution:
#!/usr/bin/perl
### Module requests ###
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request::Common;
use XML::LibXML;
use Data::Dumper;
### Make Request to get the session Token ###
my $url = "http://correct.server.address/seller";
my $api = "APIKEY";
my $userAgent = LWP::UserAgent->new();
my $request = HTTP::Request->new(POST => $url . "?apikey=" . $api);
my $response = $userAgent->request($request);
### Display error if request to server fails ###
unless ($response->is_success) {
print "Content-type: text/html\n\n";
print "Error: " . $response->status_line;
exit;
}
### Assign response xml to $xml_token ###
my $xml_token = $response->content;
### Parse XML through XML::LibXML module ###
my $parser = XML::LibXML->new();
my $tree = $parser->parse_string($xml_token);
my $root = $tree->getDocumentElement;
my $token = $root->getElementsByTagName('token');
### Make Request to add Item - PROBLEM STARTS HERE ###
my $postURL = "http://correct.server.address/item" . "?token=" . $token;
my %item_data = (type => "fixedPrice",
item => {
id_country => "0",
id_category => "728",
fixed_price => "1.00",
currency => "GBP",
title => "Test item",
personal_reference => "12345"
}
);
my $userAgentReq2 = LWP::UserAgent->new();
my $requestReq2 = HTTP::Request->new(POST => $postURL);
$requestReq2->header(content_type => 'multipart/form-data');
$requestReq2->content(\%item_data);
my $responseReq2 = $userAgentReq2->request($requestReq2);
### Display error if request to server fails ###
unless ($responseReq2->is_success) {
print "Content-type: text/html\n\n";
print "<p>Error Message: " . $responseReq2->status_line;
print "</p><p>Output of test data sent: \n";
print Dumper(\%item_data);
print "</p><p>Dumped Response: \n";
print Dumper($responseReq2);
print "</p><p>\n";
print "Token: $token\n";
print "</p><p>\n";
print "Response: " . $responseReq2->as_string;
print "</p>\n";
exit;
}
### Assign response xml to $xml_responseReq2 ###
my $xml_responseReq2 = $responseReq2->content;
### Display Token ###
print "Content-type: text/html\n\n";
print "<p>Response: $xml_responseReq2</p>\n";
print Dumper($responseReq2);
exit;
My first post request to retrieve the session token works correctly and I receive the token. However my second post request trying to add the item fails.
This is the dumped response:
$VAR1 = bless( {
'_content' => 'Not a SCALAR reference at /usr/lib/perl5/site_perl/5.8.8/LWP/Protocol/http.pm line 203.
',
'_rc' => 500,
'_headers' => bless( {
'client-warning' => 'Internal response',
'client-date' => 'Fri, 21 Mar 2014 12:13:34 GMT',
'content-type' => 'text/plain',
'::std_case' => {
'client-warning' => 'Client-Warning',
'client-date' => 'Client-Date'
}
}, 'HTTP::Headers' ),
'_msg' => 'Not a SCALAR reference',
'_request' => bless( {
'_content' => {
'item' => {
'currency' => 'GBP',
'id_category' => '728',
'id_country' => '0',
'personal_reference' => '12345',
'title' => 'Test item',
'fixed_price' => '1.00'
},
'type' => 'fixedPrice'
},
'_uri' => bless( do{\(my $o = 'http://correct.server.address/item?token=986aee823d54a7c2d50651c1b272c455')}, 'URI::http' ),
'_headers' => bless( {
'user-agent' => 'libwww-perl/6.05',
'content-type' => 'multipart/form-data'
}, 'HTTP::Headers' ),
'_method' => 'POST'
}, 'HTTP::Request' )
}, 'HTTP::Response' );
Please can someone help me as to where I’m going wrong, many thanks in advance!
The following appears to achieve what you want.
my %item_data = (type => "fixedPrice",
'item[id_country]' => "0",
'item[id_category]' => "728",
'item[fixed_price]' => "1.00",
'item[currency]' => "GBP",
'item[title]' => "Test item",
'item[personal_reference]' => "12345"
);
my $userAgentReq2 = LWP::UserAgent->new();
my $responseReq2 = $userAgentReq2->post($postURL,[%item_data]);
PHP allows you to create POST variables that get automatically deserialized into nested structures; for example, you can have form fields called item[0] and item[1] and so forth and those will appear in your server-side PHP script as an array of values. But HTTP does not have any concept of arrays; post data are simple key and value pairs.
The sample client-side PHP code is trying to build a nested array structure which PHP's curl interface will automatically translate into HTTP field names. It's been a million years since I've done any PHP, but I think the field names would end up being item[0][id_country], item[0][id_category], and so on. This is how PHP "cheats" HTTP to put complex structure into POSTs.
Perl's LWP library does not support building field names out of nested structures this way. That's why you're getting this error:
Not a SCALAR reference at /usr/lib/perl5/site_perl/5.8.8/LWP/Protocol/http.pm line 203.
'
In your POST arguments, the item key is pointing to a hash reference, but LWP expects to only see a plain scalar or scalar reference there.
So you'll need to change your LWP POST parameters to something like the following. (If this is not exactly right, you can use a HTTP sniffer on the PHP code to figure out what the actual field names are that it generates.)
my %item_data = (type => "fixedPrice",
'item[0][id_country]' => "0",
'item[0][id_category]' => "728",
'item[0][fixed_price]' => "1.00",
'item[0][currency]' => "GBP",
'item[0][title]' => "Test item",
'item[0][personal_reference]' => "12345"
);

Categories