html5 getting and using coordinates to get address without map - php

I want to get the address of the user abit more precisely than what IP shows it to be, so I used HTML geocoder which gets me the lat and long - so far so good. However i want to get the address from this without displaying any map just the street adress - city - country as plain text to do some work in background. So far as I see google reverse geocoding is always involved with displaying a map. So is there a way to get around this? I could use the php function below but i just cant pass the html 5 var to php as it is.
php
function GetAddress( $lat, $lng )
{
// Construct the Google Geocode API call
//
$URL = "http://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&sensor=false";
// Extract the location lat and lng values
//
$data = file( $URL );
foreach ($data as $line_num => $line)
{
if ( false != strstr( $line, "\"formatted_address\"" ) )
{
$addr = substr( trim( $line ), 22, -2 );
break;
}
}
return $addr;
}
$address = GetAddress();
print_r($address);
?>

The approach I would take would be something akin to this...(tested and works)
<div id='geo_results'></div>
<script type='text/javascript' charset='utf-8'>
window.onload=function(){
navigator.geolocation.getCurrentPosition( geo_success, geo_failure );
function geo_success(pos){
var lat=pos.coords.latitude;
var lng=pos.coords.longitude;
var xhr=new XMLHttpRequest();
xhr.onreadystatechange = function() {
if( xhr.readyState==4 && xhr.status==200 ){
geo_callback.call( this, xhr.responseText );
}
}
xhr.open( 'GET', '/fetch.php?lat='+lat+'&lng='+lng, true );
xhr.send( null );
}
function geo_failure(){
alert('failed');
}
function geo_callback(r){
var json=JSON.parse(r);
/* process json data according to needs */
document.getElementById('geo_results').innerHTML=json.results[0].formatted_address;
console.info('Address: %s',json.results[0].formatted_address);
}
}
</script>
and the php page would send the request to google via curl
/* fetch.php */
<?php
/*
Modified only to filter supplied variables to help avoid nasty surprises
*/
$options=array( 'flags' => FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_ENCODE_HIGH );
$lat=filter_input( INPUT_GET, 'lat', FILTER_SANITIZE_ENCODED, $options );
$lng=filter_input( INPUT_GET, 'lng', FILTER_SANITIZE_ENCODED, $options );
$url="http://maps.googleapis.com/maps/api/geocode/json?latlng={$lat},{$lng}&sensor=false";
$curl=curl_init( $url );
/*
If CURLOPT_RETURNTRANSFER is set to FALSE
there is no need to echo the response
at the end
*/
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE );
curl_setopt( $curl, CURLOPT_AUTOREFERER, TRUE );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE );
curl_setopt( $curl, CURLOPT_FRESH_CONNECT, TRUE );
curl_setopt( $curl, CURLOPT_FORBID_REUSE, TRUE );
curl_setopt( $curl, CURLINFO_HEADER_OUT, FALSE );
curl_setopt( $curl, CURLOPT_USERAGENT, 'curl-geolocation' );
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 15 );
curl_setopt( $curl, CURLOPT_TIMEOUT, 90 );
curl_setopt( $curl, CURLOPT_HEADER, FALSE );
$response=curl_exec( $curl );
echo $response;
?>

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");

Using Google Text-To-Speech API to save speech audio

I am trying to implement methods discussed in this question to write a php function that downloads an audio file for a given string, but I can't seem to get around google's abuse protection. Results are sporadic, sometimes I get an audio file and other times it's an empty 2KB mp3 due to a response with "Our systems have detected unusual traffic from your computer network". Here is what I've got so far ( note the $file has a location in my code but for the purposes of this I've omitted it ) :
function downloadMP3( $url, $file ){
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_REFERER, 'http://translate.google.com/' );
curl_setopt( $curl, CURLOPT_USERAGENT, 'stagefright/1.2 (Linux;Android 5.0)' );
$output = curl_exec( $curl );
curl_close( $curl );
if( $output === false ) {
return false;
}
$fp = fopen( $file, 'wb' );
fwrite( $fp, $output );
fclose( $fp );
return true;
}
$word = "Test";
$file = md5( $word ) . '.mp3';
if ( !file_exists( $file ) ) {
$url = 'http://translate.google.com/translate_tts?q=' . $word . '&tl=en&client=t';
downloadMP3( $url, $file );
}
Try another service, I just found one that works even better than Google Translate; Google Text-To-Speech API

Is it possible to download YouTube video links through PHP with resumable?

Is it possible to download youtube video links through php with resumable. I can easily fetch the download links through youtube-dl.
In PHP resumable, it needs to be known the size of the video. But from the link i can't fetch out the size, so is it possible to make resumable through PHP.
Let say the link is: [mp4]
https://r10---sn-hp576n7z.googlevideo.com/videoplayback?mt=1415174349&itag=22&fexp=915516%2C930666%2C932404%2C934601%2C947209%2C947215%2C948124%2C952302%2C952901%2C953912%2C957103%2C957201&key=yt5&upn=xe1em66NCSc&sparams=gcr%2Cid%2Cip%2Cipbits%2Citag%2Cmime%2Cmm%2Cms%2Cmv%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&ipbits=0&ratebypass=yes&gcr=us&mv=u&id=o-ANmao-OacohTVjp7yijSePI5a3vvlERcSs6uL3WLfOA7&ms=au&expire=1415196179&sver=3&ip=176.576.184.114&mime=video%2Fmp4&requiressl=yes&source=youtube&mm=31&signature=29046D03C1EC013A78BD20E4CDD362BBA62ADF4B.A0E2E8E104769DD664202597A91F0888F9E554B3
Try this to get filesize:
<?php
/**
* Returns the size of a file without downloading it, or -1 if the file
* size could not be determined.
*
* #param $url - The location of the remote file to download. Cannot
* be null or empty.
*
* #return The size of the file referenced by $url, or -1 if the size
* could not be determined.
*/
function curl_get_file_size( $url ) {
// Assume failure.
$result = -1;
$curl = curl_init( $url );
// Issue a HEAD request and follow any redirects.
curl_setopt( $curl, CURLOPT_NOBODY, true );
curl_setopt( $curl, CURLOPT_HEADER, true );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $curl, CURLOPT_USERAGENT, 'user_agent_string' );
$data = curl_exec( $curl );
curl_close( $curl );
if( $data ) {
$content_length = "unknown";
$status = "unknown";
if( preg_match( "/^HTTP\/1\.[01] (\d\d\d)/", $data, $matches ) ) {
$status = (int)$matches[1];
}
if( preg_match( "/Content-Length: (\d+)/", $data, $matches ) ) {
$content_length = (int)$matches[1];
}
// http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
if( $status == 200 || ($status > 300 && $status <= 308) ) {
$result = $content_length;
}
}
return $result;
}
Usage:
$file_size = curl_get_file_size($url);

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.

Post and request from webpages

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;
}
?>

Categories