Post and request from webpages - php

I have a system which records every member's IP address, browser and operating system.
I would like to somehow implement this.
Is there anyway in which I can post the users IP to their website, pulling values such as ISP and country, and store them in my local MySQL database for quick access when running queries on certain abusive users?

IP to location isn't always accurate and can easily be overcome, but this might help you

PHP has native support for Maxmind's GeoIP services. See this PECL extension for details.

check this site out : http://ipinfodb.com/ip_location_api.php
they offer API to pass an ip address to there services to return geolocation back in either XML/JSON, which can then be parsed on your PHP script.
An example of how to use it looks like this:
<?php
include('ip2locationlite.class.php');
//Load the class
$ipLite = new ip2location_lite;
$ipLite->setKey('<your_api_key>');
//Get errors and locations
$locations = $ipLite->getCity($_SERVER['REMOTE_ADDR']);
$errors = $ipLite->getError();
//Getting the result
echo "<p>\n";
echo "<strong>First result</strong><br />\n";
if (!empty($locations) && is_array($locations)) {
foreach ($locations as $field => $val) {
echo $field . ' : ' . $val . "<br />\n";
}
}
echo "</p>\n";
//Show errors
echo "<p>\n";
echo "<strong>Dump of all errors</strong><br />\n";
if (!empty($errors) && is_array($errors)) {
foreach ($errors as $error) {
echo var_dump($error) . "<br /><br />\n";
}
} else {
echo "No errors" . "<br />\n";
}
echo "</p>\n";
?>
maybe this will get you moving in the right direction?

If you really want to pull data from http://www.iplocation.net/, then here is a quick dirty function. but to use this function you need to download and include PHP Simple HTML DOM Parser
Here is the code
<?php
require_once( "path to simplehtmldom.php" );
$ip_info = ip_info( "223.196.190.40", 1 );
print_r( $ip_info );
/**
* It will output...
Array
(
[IP Address] => 223.196.190.40
[Country] => India
[Region] => Maharashtra
[City] => Pune
[ISP] => Idea Isp Subscriber Ip Pool
)
**/
/**
* ip_info()
* #param $ip - IP address you want to fetch data from
* #param $provider IP provider ( 1 = IP2Location, 2 = IPligence, 3 = IP Address Labs, 4 = MaxMind )
* #return array
*/
function ip_info( $ip = "127.0.0.1", $provider = 1 ) {
$indx = array(
1 => 10,
2 => 11,
3 => 12,
4 => 13
);
$data = array();
$url = "http://www.iplocation.net/index.php";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_FRESH_CONNECT, true );
curl_setopt( $ch, CURLOPT_FORBID_REUSE, true );
curl_setopt( $ch, CURLOPT_HEADER, false );
curl_setopt( $ch, CURLOPT_NOBODY, false );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $ch, CURLOPT_BINARYTRANSFER, false );
curl_setopt( $ch, CURLOPT_REFERER, $url );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, "query=".urlencode( $ip )."&submit=Query" );
$response = curl_exec( $ch );
$html = str_get_html( $response );
if ( $table = $html->find( "table", $indx[$provider] ) ) {
if ( $tr1 = $table->find( "tr", 1 ) ) {
if ( $headers = $tr1->find( "td" ) ) {
foreach( $headers as $header ) {
$data[trim( $header->innertext )] = null;
}
}
}
if ( $tr2 = $table->find( "tr", 3 ) ) {
reset( $data );
if ( $values = $tr2->find( "td" ) ) {
foreach( $values as $value ) {
$data[key( $data )] = trim( $value->plaintext );
next( $data );
}
}
}
}
unset( $html, $table, $tr1, $tr2, $headers, $values );
return $data;
}
?>

Related

PHP Request failed on SSL

Hello I would like to get some data from a url. I already tried to make a request through the console, postman, browset - all of them worked correctly. But if I make a request using php (guzzle, symfony http client) it fails on SSL. Does anybody know how to get response from this url by curl? Thanks!
Please try the following code ( That's worked for me ):
<?php
function curl( $url, $data = array(), $headers = array(), $ssl_required = false ) {
$handle = curl_init( $url );
curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
// Set post data if exist
if ( !empty( $data ) ) {
curl_setopt( $handle, CURLOPT_POST, true );
curl_setopt( $handle, CURLOPT_POSTFIELDS, $data );
}
// Set custom headers if exist
if ( count( $headers ) )
curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
// If url was ssl, need to true
if ( $ssl_required )
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec( $handle );
curl_close( $handle );
return $output;
}
echo curl("https://www.skroutz.gr/c/900/fakoi-epafhs.json");

PHP - Insert a variable into an array

Say we have this array
$args = array('responseType' => 'Xml',
'serverName' => 'vl18278.dinaserver.com',
'command' => 'Vps_GetUsedSpace',
) ;
This array composes an URL to send through cURL. I need to replace vl18278.dinaserver.com with a variable $vps, but when I replace it, the URL show a %5B0%5D just before the = sign of the attribute serverName:
responseType=Xml&serverName%5B0%5D=vl18278.dinaserver.com&command=Vps_GetUsedSpace
If I dont replace the vl18278.dinaserver.com, the URL is correct.
What is wrong with my code? Why are those %5B0%5D getting into my URL? :(
Thanks in advance.
Complete code:
<?php
$listavps = simplexml_load_file('servers.xml');
foreach ($listavps->servers->server as $vps) {
$urlApi = 'url.php';
$username = 'user';
$password = 'pass';
$args = array('responseType' => 'Xml',
'serverName' => 'vl18278.dinaserver.com',
'command' => 'Vps_GetUsedSpace',
) ;
$args = ( is_array ( $args ) ? http_build_query ( $args, '', '&' ) : $args );
$headers = array();
$handle = curl_init($urlApi);
if( $handle === false ) // error starting curl
{
$error = '0 - Couldn\'t start curl';
}
else
{
curl_setopt ( $handle, CURLOPT_FOLLOWLOCATION, true );
curl_setopt ( $handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $handle, CURLOPT_URL, $urlApi );
curl_setopt( $handle, CURLOPT_USERPWD, $username.':'.$password );
curl_setopt( $handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt( $handle, CURLOPT_TIMEOUT, 60 );
curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, 4); // set higher if you get a "28 - SSL connection timeout" error
curl_setopt ( $handle, CURLOPT_HEADER, true );
curl_setopt ( $handle, CURLOPT_HTTPHEADER, $headers );
$curlversion = curl_version();
curl_setopt ( $handle, CURLOPT_USERAGENT, 'PHP '.phpversion().' + Curl '.$curlversion['version'] );
curl_setopt ( $handle, CURLOPT_REFERER, null );
curl_setopt ( $handle, CURLOPT_SSL_VERIFYPEER, false ); // set false if you get a "60 - SSL certificate problem" error
curl_setopt ( $handle, CURLOPT_POSTFIELDS, $args );
curl_setopt ( $handle, CURLOPT_POST, true );
$response = curl_exec ( $handle );
echo $args;
if ($response)
{
$response = substr( $response, strpos( $response, "\r\n\r\n" ) + 4 ); // remove http headers
// parse response
$responseSimpleXml = simplexml_load_string($response);
if( $responseSimpleXml === false )
{
// invalid xml response
}
else
{
// parse response
$errorCode = $responseSimpleXml->response->responseCode ;
echo $errorCode;
if( $errorCode == 1000 ) // success
{
$usado = $responseSimpleXml->response->data->total_space;
$capacidad = $responseSimpleXml->response->data->space_limit;
echo 'Usado: '.$usado.'</br>Total: '.$capacidad.'.';
}
else // normal errors
{
$errors = $responseSimpleXml->response->errors;
foreach( $errors->error as $error )
{
// process error
}
}
}
}
else // http response code != 200
{
$error = curl_errno ( $handle ) . ' - ' . curl_error ( $handle );
}
curl_close($handle);
}
}
?>
Your variable $server must be an array, because, once decoded, %5B0%5D is [0].
My guess is to use $server[0] instead of $server wherever you replace the value. Without the replacement code, it is hard to determine.
I solved this using rawurlencode in the $listavps variable before using it.
<?php
$listavps = simplexml_load_file('servers.xml');
foreach ($listavps->servers->server as $key => $tag) {
$vps = rawurlencode ($tag);
$urlApi = 'url.php';
$username = 'user';
$password = 'pass';
$args = array('responseType' => 'Xml',
'serverName' => $vps,
'command' => 'Vps_GetUsedSpace',
) ;

PHP-GoogleAPI: URL shorther API doesnot provide short URL on localhost

am developing web application with a lot of forms enclosed in it.
I am using google's public link generation API.
<?php
include 'config.php';
include 'php/lib/google_api/googleURL_shortener.php';
?>
<html>
<head></head>
<body>
<?php
try {
$key = "AIzaSyCzDa3nhryO23Aa-0VlxasYkZ-PPqeWfrY";
$googleApi = new GoogleURL($key);
$publicLink = '';
$url = BASE_URL.'form_operation/index.php? id=54ccb4db64363d9c1100002d';
$publicLink = $googleApi->encode($url);
echo $publicLink;
} catch (Exception $ex) {
echo $ex;
}
?>
</body>
</html>
i have included google shortener API library Code for api library is this
<?php
class GoogleURL
{
private $apiURL = 'https://www.googleapis.com/urlshortener/v1/url';
function __construct($apiKey)
{
$this->apiURL = $this->apiURL . '?key=' . $apiKey;
}
public function encode($url)
{
$data = $this->cURL($url, true);
return isset($data->id) ? $data->id : 'No data present' ;
}
public function decode($url)
{
$data = $this->cURL($url, false);
return isset($data->analytics->allTime->shortUrlClicks) ? $data- >analytics->allTime->shortUrlClicks : 0 ;
}
private function cURL($url, $post = true)
{
$ch = curl_init();
if ($post) {
curl_setopt( $ch, CURLOPT_URL, $this->apiURL );// cURL defined
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json') );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode(array('longUrl' => $url)) );
}
else {
curl_setopt( $ch, CURLOPT_URL, $this->apiURL . '&projection=FULL&shortUrl=' . $url );
}
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
$json = curl_exec($ch);
curl_close($ch);
return (object) json_decode($json);
}
}
?>
I am getting null output every time i call API from localhost.
I am getting following reply
stdClass Object
(
[error] => stdClass Object
(
[errors] => Array
(
[0] => stdClass Object
(
[domain] => usageLimits
[reason] => ipRefererBlocked
[message] => There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.
[extendedHelp] => https://console.developers.google.com
)
)
[code] => 403
[message] => There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.
)
)
what can be done about it??

AWS Apache PHP works from outside but fails when tried to invoke using IP within

I have an AWS setup with Apache/PHP server on Port 80 and a REST Tomcat server on 8080.
If I try to access REST Services using IP Address A.B.C.D:8080/restapp from outside it works.
However if I try invoking from PHP code on the same box, it throws an internal error. Need your expert help in debugging this:
Checklist:
Security Profile:
8080 and 80 opened for 0.0.0.0/0
URL to be invoked: http://ec2-A-B-C-D.us-west-1.compute.amazonaws.com/myapp/ba-simple-proxy1.php?url=http://ec2-A-B-C-D.us-west-1.compute.amazonaws.com:8080/restapp/rest/user
ERROR RESPONSE:
"NetworkError: 500 Internal Server Error - http://ec2-A-B-C-D.us-west-1.compute.amazonaws.com/myapp/ba-simple-proxy1.php?url=http://ec2-A-B-C-D.us-west-1.compute.amazonaws.com:8080/restapp/rest/user"
Code Snippet from PHP - ba-simple-proxy1.php:
//print $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 = 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 );
//print $ch;
$status = curl_getinfo( $ch );
curl_close( $ch );
}
Turns out the php_curl lib was not part of PHP5 installation. I installed it and everything works fine now.

Twitter Single Sign On OAuth PHP without third party API

I have been given a task to develop a a single sign on system using Twitter and I am not allowed to use third party API's. I am however allowed to use CURL and PHP. What would be the best way to do this. so far I have this but it does not work. It outputs the error "Failed to validate oauth signature and token"
I would like some advice on how to go about doing this.
$fields = array(
'oauth_callback' => 'http://www.mydomain.co.uk/redirect.php'
);
//url-ify the data for the POST
foreach( $fields as $key=>$value ) {
$fields_string .= $key.'='.$value.'&';
}
rtrim( $fields_string, "" );
echo $fields_string;
$curl = curl_init( "https://api.twitter.com/oauth/request_token" );
//Send auth data to twiter
curl_setopt( $curl, CURLOPT_POST, count( $fields ) );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $fields_string );
//Will return json object
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
$result = curl_exec($curl);
//debugger
if( $debug ){
if( ! curl_errno( $curl ) ) {
$info = curl_getinfo( $curl );
echo 'Took ' . $info[ 'total_time' ] . ' seconds to send a request to ' . $info[ 'url' ];
}
}
curl_close( $curl );
echo $result;
I would suggest use of the PEAR HTTP_OAUTH library. There is no reason to re-invent the wheel.

Categories