I am trying to implement spam checks for websites, Like I have website A,B,C,D... I am creating a centralized spam check filter say xyz.com/spamcheck.php
I am using CURL to post the data from website A to xyz.com/spamcheck.php
and in my spamcheck.php I am using Akismet Fuspam library to validate it and return the response back to my website A, based on the response from my spamcheck i will decide to send mail or discard.
So far i am not able to post values to my spamcheck.php through CURL and get response back from it.
// DATA PROCESSING
$data = array();
$data['ip'] = get_client_ip();
$data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
$data['referrer'] = $_SERVER['HTTP_REFERER'];
$data['comment_author'] = $_POST['first_name'];
$data['comment_author_email'] = $_POST['email'];
$data['comment_content'] = $_POST['message'];
$params = json_encode($data);
$url = "https://www.my-spam-check-url.com/spamcheck.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only!
$spamResult = curl_exec($ch);
curl_close($ch);
$spamResult = json_decode($spamResult,true);
print_r($spamResult);
I expect the output to be TRUE or FALSE. I am getting Blank response
spamcheck.php
// Include Akismet F-U-Spam function.
include 'includes/akismet.fuspam.php';
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
/*API KEY - 123XYZ*/
$comment = array();
$key = "123XYZ";
$type = "check-spam";
/* Get Posted Data from website */
$postedIp = $data['ip'];
$postedUserAgent = $data['user_agent'];
$postedReferrer = $data['referrer'];
$postedcomment_author = $data['comment_author'];
$postedcomment_author_email = $data['comment_author_email'];
$postedcomment_content = $data['comment_content'] ;
/* Data Processing End */
if(empty($postedIp) || $postedIp == 'UNKNOWN' || $postedIp == ''){
$ip = get_client_ip();
}
if(empty($postedUserAgent) || $postedUserAgent == ''){
$user_agent = $_SERVER['HTTP_USER_AGENT'];
}
if(empty($postedReferrer) || $postedReferrer == ''){
$referrer = $_SERVER['HTTP_REFERER'];
}
$permalink = $blog = $authUrl = "https://www.example.net/";
$comment['blog'] = $blog;
$comment['user_ip'] = $ip;
$comment['user_agent'] = $user_agent;
$comment['referrer'] = $referrer;
$comment['permalink'] = $permalink;
$comment['comment_type'] = "ContactUs";
$comment['comment_author'] = $postedcomment_author;
$comment['comment_author_email'] = $postedcomment_author_email;
$comment['comment_author_url'] = $authUrl;
$comment['comment_content'] = $postedcomment_content;
$spamCheckResult = fuspam( $comment , $type , $key );
echo $spamCheckResult;
I am looking at your code, I cant be sure if print_r is how you are checking but if so, keep in mind that:
print_r(true) will output 1, while print_r(false) will output "", blank.
Maybe use var_dump instead for debugging?
BR
If your spamcheck.php is working as per your written code than before echo in last use ob_clean();. so i will remove space or any other before return your actual result.
Related
Today i have some php cURL code that must show to user his loacation like: ip, country, city it have.. And if the user is bot - do nothing. So, i do it like this, but it's not working properly. Only ip is shown and nothing else.. Please help.. And let the power be with you.. Thank to all for help.
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$apiurl = "https://api.2ip.ua/geo.json?ip=$ip";
//--
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiurl");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
//--
curl_close ($ch);
//- **************-//
$pieces = explode('"', $contents);
$country = $pieces['7'];
$city = $pieces['11'];
$city2 = $pieces['13'];
echo "Your IP is :" . $ip . " and country " .$country. " and city " .$city;
?>
Don't use explode!, the answer of the api is a JSON, instead you got to do this:
$data = json_decode($contents, true);
$country = $data['country'];
$city = $data['city'];
and so on for any other field you need.
BTW you can also improve the IP detection with this code that support multiple detection with ipv4 and ipv6 support
if (isset($_SERVER['REMOTE_HOST'])) {
$ip = $_SERVER['REMOTE_HOST'];
} elseif (isset($_SERVER['HOST'])) {
$ip = $_SERVER['HOST'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$host = '';
}
$ip = str_replace("::ffff:","",$ip);//::ffff:127.127.127.127 en caso de jugo ipv6
Regards and vote up
First, don't use explode, use json_decode instead and then there is something wrong with the SSL-Certificate of your API so use http instead.
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$apiurl = "http://api.2ip.ua/geo.json?ip=";
$contents = file_get_contents($apiurl . $ip);
$json = json_decode($contents);
$country = $json->country;
$city = $json->city;
echo "Your IP is :" . $ip . " and country " . $country . " and city " . $city;
how to get country name from user IP address
I have IP addresses of user i get the country name of user base on user IP address
how it is possible in php ?
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
Try this
function ip_details($IPaddress)
{
$json = file_get_contents("http://ipinfo.io/{$IPaddress}");
$details = json_decode($json);
return $details;
}
$IPaddress = 'Your ip address of user';
$details = ip_details("$IPaddress");
//echo $details->city;
echo $details->country;
//echo $details->org;
//echo $details->hostname;
For getting IP address you can use the function given by you or simply you can use
$_SERVER['REMOTE_ADDR']
to get the IP address of the user use as follow:
$ip = $_SERVER['REMOTE_ADDR']; // ip = 8.8.8.8
$country = file_get_contents('http://ipinfo.io/8.8.8.8/country'); // for more info visit [enter link description here][1]
echo $country; // output = US | UK | IN as per ip (just one country code)
Although this post has a correct answer, I have a small modification on it : using curl instead of file_get_contents because :
ipinfo.io documents suggests that.
file_get_contents doesn't have try catch pattern.
You can set a timeout request easily to prevent script waiting long for response.
Note :
Without Token, you will reach the limitation soon, so to gain free 50.000 requests/month (currently) it's better to add token in end of url :
function ip_details($ip) //return country code based on ip
{
if(empty($ip)) return "";
$url="http://ipinfo.io/{$ip}?token=XXXXX";
//trigger url
$curl = curl_init();
curl_setopt($curl, CURLOPT_TIMEOUT, 3); // wait 3 seconds to response
curl_setopt($curl, CURLOPT_URL, $url);
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$json = curl_exec($curl);
if (curl_errno($curl)) {
return "";
}
//curl_close($curl);
$details = json_decode($json);
$country = (empty($details->country)) ? "" : $details->country;
return $country;
}
You can do this, which includes currency:
<?
function resolveIP($ip) {
$string = file_get_contents("https://ipsidekick.com/{$ip}");
$json = json_decode($string);
return $json;
}
$ip = '17.142.160.59';
$json = resolveIP($ip);
echo "Country name: {$json->country->name}\n";
echo "Currency name: {$json->currency->name}\n";
echo "Public holiday: {$json->currency->holiday}\n";
?>
Get Current country name and country lat long value :
$IPaddress = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$details = $this->ip_details("$IPaddress");
$country_name = $details->country_name;
$geocode_stats = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=$country_name&sensor=false");
$output_deals = json_decode($geocode_stats);
$latLng = $output_deals->results[0]->geometry->location;
echo $lat = $latLng->lat;
echo $lng = $latLng->lng;
I am using the following code to get user's IP and get it sent to my email address (I'm using a third party email API):
<?php
$ip1 = $_SERVER['REMOTE_ADDR'];
$ip2 = $_SERVER['HTTP_X_FORWARDED_FOR']
$ip3 = $_SERVER['HTTP_FORWARDED'];
$ua = $_SERVER['HTTP_USER_AGENT'];
$to = 'abc#xyz.com';
$sub = 'test';
$msg = "$ip1, $ip2 and $ip3 on $ua \n ...other texts...";
$post = "key=blah&to=$to&sub=$sub&msg=$msg";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURL_POSTFIELDS, $post);
curl_setopt($ch, CURL_RETURNTRANSFER, 1);
$mailres = curl_exec ($ch);
?>
The API just retrieves the $_POST data and uses mail() to send email.
But when I execute the code I get the mail with the user's IP stored in $ip1 only. For eg, if user's IP is 1.1.1.1 then I get only:
1.1.1.1,
No user agent and other texts are sent.What could be the problem?
try this way first, just to be sure that you debug something real:
$text = '';
if (isset($_SERVER['REMOTE_ADDR'])) {
$text .= $_SERVER['REMOTE_ADDR'].', ';
} else {
$text .= 'NO _SERVER[\'REMOTE_ADDR\'] HERE, ';
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$text .= $_SERVER['HTTP_X_FORWARDED_FOR'].', ';
} else {
$text .= 'NO _SERVER[\'HTTP_X_FORWARDED_FOR\'] HERE, ';
}
if (isset($_SERVER['HTTP_FORWARDED'])) {
$text .= $_SERVER['HTTP_FORWARDED'].', ';
} else {
$text .= 'NO _SERVER[\'HTTP_FORWARDED\'] HERE, ';
}
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$text .= ' on '.$_SERVER['HTTP_USER_AGENT'].', ';
} else {
$text .= 'NO _SERVER[\'HTTP_USER_AGENT\'] HERE, ';
}
$text .= "\n ...other texts...";
mail ($to, $sub, $text );
but with curl it should be:
$post = array("key"=>'blah',
'to'=>$to,
'sub'=>$sub,
'msg'=>$msg);
and
curl_setopt($ch, CURL_POSTFIELDS, json_encode($post));
http://benalman.com/code/projects/php-simple-proxy/examples/simple/
I am exactly following above Blog for Using PHP Proxy setting for Cross Domain. I am using XHR. I am able to successful to use GET method. But While using POST I am getting error CODE 200 and Empty XML in reply object.
However when i am using the simple XHR Code without phpproxy with below setting of google. chrome.exe --disable-web-security. I am successful for GET and POST both.
I am sure i am wrong somewhere in XHR.Send(Mydata). But if i was wrong in this method than i could not have been able to send success full post method.
Please help. I am novice in PHP i am sure i am missing something in PHP code that would enable me to post successfull. Below is crux of PHP code.
$enable_jsonp = true;
$enable_native = false;
$valid_url_regex = '/.*/';
$url = $_GET['url'];
if (!$url)
{
// Passed url not specified.
$contents = 'ERROR: url not specified';
$status = array(
'http_code' => 'ERROR'
);
}
else if (!preg_match($valid_url_regex, $url)) {
// Passed url doesn't match $valid_url_regex.
$contents = 'ERROR: invalid url';
$status = array(
'http_code' => 'ERROR'
);
}
else
{
$ch = curl_init($url);
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
}
if ($_GET['send_cookies'])
{
$cookie = array();
foreach ($_COOKIE as $key => $value)
{
$cookie[] = $key . '=' . $value;
}
if ($_GET['send_session'])
{
$cookie[] = SID;
}
$cookie = implode('; ', $cookie);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_GET['user_agent'] ? $_GET['user_agent'] : $_SERVER['HTTP_USER_AGENT']);
list($header, $contents) = preg_split('/([\r\n][\r\n])\\1/', curl_exec($ch), 2);
$status = curl_getinfo($ch);
curl_close($ch);
}
// Split header text into an array.
$header_text = preg_split('/[\r\n]+/', $header);
if ($_GET['mode'] == 'native')
{
if (!$enable_native)
{
$contents = 'ERROR: invalid mode';
$status = array(
'http_code' => 'ERROR'
);
}
// Propagate headers to response.
foreach ($header_text as $header)
{
if (preg_match('/^(?:Content-Type|Content-Language|Set-Cookie):/i', $header))
{
header($header);
}
}
print $contents;
}
else
{
// $data will be serialized into JSON data.
$data = array();
// Propagate all HTTP headers into the JSON data object.
if ($_GET['full_headers'])
{
$data['headers'] = array();
foreach ($header_text as $header)
{
preg_match('/^(.+?):\s+(.*)$/', $header, $matches);
if ($matches)
{
$data['headers'][$matches[1]] = $matches[2];
}
}
}
// Propagate all cURL request / response info to the JSON data object.
if ($_GET['full_status'])
{
$data['status'] = $status;
}
else
{
$data['status'] = array();
$data['status']['http_code'] = $status['http_code'];
}
// Set the JSON data object contents, decoding it from JSON if possible.
$decoded_json = json_decode($contents);
$data['contents'] = $decoded_json ? $decoded_json : $contents;
// Generate appropriate content-type header.
$is_xhr = strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
header('Content-type: application/' . ($is_xhr ? 'json' : 'x-javascript'));
// Get JSONP callback.
$jsonp_callback = $enable_jsonp && isset($_GET['callback']) ? $_GET['callback'] : null;
// Generate JSON/JSONP string`enter code here`
$json = json_encode($data);
print $jsonp_callback ? "$jsonp_callback($json)" : $json;
}
How can I determine a user's current location based on IP address (I guess it works this way).
<?php
$user_ip = getenv('REMOTE_ADDR');
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip"));
$country = $geo["geoplugin_countryName"];
$city = $geo["geoplugin_city"];
?>
Edited
Change freegeoip.net into ipinfo.io
<?php
function get_client_ip()
{
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
} else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
} else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
} else if (isset($_SERVER['HTTP_FORWARDED'])) {
$ipaddress = $_SERVER['HTTP_FORWARDED'];
} else if (isset($_SERVER['REMOTE_ADDR'])) {
$ipaddress = $_SERVER['REMOTE_ADDR'];
} else {
$ipaddress = 'UNKNOWN';
}
return $ipaddress;
}
$PublicIP = get_client_ip();
$json = file_get_contents("http://ipinfo.io/$PublicIP/geo");
$json = json_decode($json, true);
$country = $json['country'];
$region = $json['region'];
$city = $json['city'];
?>
<?php
$query = #unserialize (file_get_contents('http://ip-api.com/php/'));
if ($query && $query['status'] == 'success') {
echo 'Hey user from ' . $query['country'] . ', ' . $query['city'] . '!';
}
foreach ($query as $data) {
echo $data . "<br>";
}
?>
Try this code using this source. *It works!
Try this code using the hostip.info service:
$country=file_get_contents('http://api.hostip.info/get_html.php?ip=');
echo $country;
// Reformat the data returned (Keep only country and country abbr.)
$only_country=explode (" ", $country);
echo "Country : ".$only_country[1]." ".substr($only_country[2],0,4);
As PHP relies on a server, the real-time location can’t be provided. Only a static location can be provided. It is better to avoid to rely on the JavaScript for a location rather than using PHP.
But there is a need to post the JavaScript data to PHP, so that it can easily be accessible to a program on the server.
An IP address gives you a quite unreliable location. You could Ajax the location upon load with JavaScript if it isn't critical to have the location at first. (Also, the user needs to give you its permission to access it.)
HTML5 Geolocation
The old freegeoip API is now deprecated and will be discontinued on 2018-07-01.
The new API is from ipstack. You have to create the account in ipstack. Then you can use the access key in the API URL.
$url = "http://api.ipstack.com/122.167.180.20?access_key=ACCESS_KEY&format=1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
$city = $response->city; // You can get all the details like longitude, latitude from the '$response'.
For more information, check at freegeoip (GitHub).