Get user's ISP, country and city by ip? - ip

How to get user's ISP, country and city by ip without any other service. I looked in some solutions with whatismyipaddress.com but they don't allow anymore http://whatismyipaddress.com/ip/194.153.145.104 by curl it returns - You appear to be an automated script. Site terms and conditions do not allow for automated/script access. For API details see http://whatismyipaddress.com/api
And their API don't allow to get Geolocation data. Here is what i have tested:
$ip='194.153.145.104';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://whatismyipaddress.com/ip/' . $ip);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$data = explode("\n", curl_exec($curl));
$isp = null;
$country = null;
$city = null;
$MaxIndex = count($data) - 1;
for ($i = 0; $i < $MaxIndex; $i++){
if (strpos($data[$i], '<th>ISP:</th>') !== false){
$isp = str_replace('<td>', '', $data[$i + 1]);
$isp = str_replace('</td>', '', $isp);
break;
}
if (strpos($data[$i], '<th>Country:</th>') !== false){
$country = str_replace('<td>', '', $data[$i + 1]);
$country = str_replace('</td>', '', $country);
break;
}
if (strpos($data[$i], '<th>City:</th>') !== false){
$city = str_replace('<td>', '', $data[$i + 1]);
$city = str_replace('</td>', '', $city);
break;
}
}
print_r($data);
echo "ISP: ".$isp."<br />Country: ".$country."<br />City: ".$city;

They probably check if the User-Agent header in the request is that of a valid Browser.
Add this to your script and it should work:
curl_setopt($curl,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

Related

wordpress wp_mail throws error: could not instantiate mail function

I have two forms in my website. Both were working fine. but suddenly now they are not working. Emails are not going from both the forms.
// This function gets called when user clicks on submit button
<script type="text/javascript">
var $ = jQuery;
function sendMessage(){
var name = $('[name="name"]').val();
var email = $('[name="email"]').val();
var phone = $('[name="phone"]').val();
var message = $('[name="message"]').val();
var filter = /^[7-9][0-9]{9}$/;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(name == '')
{
$('.name-error').show();
}
else
{
$('.name-error').hide();
}
if(email == '')
{
$('.email-error').show();
}
else
{
$('.email-error').hide();
}
if(phone == '')
{
$('.phone-error').show();
}
else
{
$('.phone-error').hide();
}
if(message == '')
{
$('.message-error').show();
}
else
{
$('.message-error').hide();
}
if(name != '' && email != '' && phone != '' && message != ''){
if(emailReg.test(email)){
if(filter.test(phone)){
var data = {
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
action: 'send_mails',
formdata: $("#contact").serialize()
};
var myRequest = jQuery.post(data.url, data, function(response){
console.log(response)
});
myRequest.done(function(){
$('#msg').html("<p class='msg' style='background-color:#dff0d8; border-color: #d6e9c6; color:#3c763d; padding:10px; border-radius:4px;'>The Email has been sent successfully!</p>").fadeIn('slow');
$('#msg').delay(5000).fadeOut('slow');
});
$("#contact").trigger("reset");
$('#msg').html("<p class='msg' style='background-color:#dff0d8; border-color: #d6e9c6; color:#3c763d; padding:10px; border-radius:4px;'>The Email has been sent successfully!</p>").fadeIn('slow');
$('#msg').delay(5000).fadeOut('slow');
}
else
{
alert("Provide valid mobile number");
}
}
else
{
alert("Provide valid Email Id");
}
}
else
{
// alert("Kindly enter all the details");
return false;
}
}
</script>
This is function from functions.php file.
function send_mails()
{
$formData = $_POST['formdata'];
$data = array();
parse_str($formData, $data);
$name = $data['name'];
$email = $data['email'];
$phone = $data['phone'];
$message = $data['message'];
$msg = "A new enquiry has been posted on the website\n";
$msg.= "Name: ".$name."\n";
$msg.= "Email: ".$email."\n";
$msg.= "Phone: ".$phone."\n";
$msg.= "Message: ".$message."\n";
$headers = array('Content-Type: text/html; charset=UTF-8');
//echo $msg;
$admin_email = get_option( 'admin_email' );
// print_r($admin_email);
$res = wp_mail('email',"Enquiry",$msg,$headers);
if($res)
{
echo "Mail has been sent";
}
else
{
echo "Could not send mail";
debug_wpmail($res);
}
die();
}
add_action('wp_ajax_send_mails', 'send_mails');
add_action('wp_ajax_nopriv_send_mails', 'send_mails');
debug_wpmail returns the error "Could not instantiate mail function". I did not find anything on google.
if ( ! function_exists('debug_wpmail') ) :
function debug_wpmail( $result = false ) {
if ( $result )
return;
global $ts_mail_errors, $phpmailer;
if ( ! isset($ts_mail_errors) )
$ts_mail_errors = array();
if ( isset($phpmailer) )
$ts_mail_errors[] = $phpmailer->ErrorInfo;
print_r('<pre>');
print_r($ts_mail_errors);
print_r('</pre>');
}
endif;
Can you modify this part :
From
$res = wp_mail('email',"Enquiry",$msg,$headers);
To
$res = wp_mail($admin_email,'Enquiry',$msg,$headers);
This happens due to your site haven't been configured with email service provider like Google/SendGrid or SMTP Or It just goes removed. Example configuration can be found below:

Permission denied on Gravity Forms API with Angular

I am working on a mobile App that will get data from a Wordpress installation with Gravity Forms API.
Unfortunately, I always receive:
{"status":401,"response":"Permission denied"}
I guess, there is an error on how I create the signature, but I cannot find anything. Any hint?
HmacSHA1(k,d,_p,_z){
if(!_p){_p='=';}if(!_z){_z=8;}function _f(t,b,c,d){if(t<20){return(b&c)|((~b)&d);}if(t<40){return b^c^d;}if(t<60){return(b&c)|(b&d)|(c&d);}return b^c^d;}function _k(t){return(t<20)?1518500249:(t<40)?1859775393:(t<60)?-1894007588:-899497514;}function _s(x,y){var l=(x&0xFFFF)+(y&0xFFFF),m=(x>>16)+(y>>16)+(l>>16);return(m<<16)|(l&0xFFFF);}function _r(n,c){return(n<<c)|(n>>>(32-c));}function _c(x,l){x[l>>5]|=0x80<<(24-l%32);x[((l+64>>9)<<4)+15]=l;var w=[80],a=1732584193,b=-271733879,c=-1732584194,d=271733878,e=-1009589776;for(var i=0;i<x.length;i+=16){var o=a,p=b,q=c,r=d,s=e;for(var j=0;j<80;j++){if(j<16){w[j]=x[i+j];}else{w[j]=_r(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);}var t=_s(_s(_r(a,5),_f(j,b,c,d)),_s(_s(e,w[j]),_k(j)));e=d;d=c;c=_r(b,30);b=a;a=t;}a=_s(a,o);b=_s(b,p);c=_s(c,q);d=_s(d,r);e=_s(e,s);}return[a,b,c,d,e];}function _b(s){var b=[],m=(1<<_z)-1;for(var i=0;i<s.length*_z;i+=_z){b[i>>5]|=(s.charCodeAt(i/8)&m)<<(32-_z-i%32);}return b;}function _h(k,d){var b=_b(k);if(b.length>16){b=_c(b,k.length*_z);}var p=[16],o=[16];for(var i=0;i<16;i++){p[i]=b[i]^0x36363636;o[i]=b[i]^0x5C5C5C5C;}var h=_c(p.concat(_b(d)),512+d.length*_z);return _c(o.concat(h),512+160);}function _n(b){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s='';for(var i=0;i<b.length*4;i+=3){var r=(((b[i>>2]>>8*(3-i%4))&0xFF)<<16)|(((b[i+1>>2]>>8*(3-(i+1)%4))&0xFF)<<8)|((b[i+2>>2]>>8*(3-(i+2)%4))&0xFF);for(var j=0;j<4;j++){if(i*8+j*6>b.length*32){s+=_p;}else{s+=t.charAt((r>>6*(3-j))&0x3F);}}}return s;}function _x(k,d){return _n(_h(k,d));}return _x(k,d);
}
CalculateSig (stringToSign) {
var hash = this.HmacSHA1(stringToSign, this.privateKey, '','');
var base64 = btoa(hash);
return encodeURIComponent(base64);
}
CreateSig (method, route, future_unixtime) {
let stringToSign = this.publicKey + ":" + method + ":" + route + ":" + future_unixtime;
return this.CalculateSig(stringToSign);
}
getFutureUnixTime() {
let expiration = 3600;
let unixtime = Math.round((new Date()).getTime() / 1000);
return unixtime + expiration;
}
getData () {
let route = "forms/1/entries";
let future_unixtime = this.getFutureUnixTime();
let sig = this.CreateSig("GET", route, future_unixtime);
var url = this.domain + route + '?api_key=' + this.publicKey + '&signature=' + sig + '&expires=' + future_unixtime;
return this.http.get(url).map(res => res.json());
}
Have you tried just returning the url and seeing if it's response is 200.
Im using a similar request
//creating request URL
$method = "GET";
$expires = strtotime("+60 mins");
$string_to_sign = sprintf("%s:%s:%s:%s", $api_key, $method, $route, $expires);
$sig = calculate_signature( $string_to_sign, $private_key );
$url = $api_url . $route . '?api_key=' . $api_key . '&signature=' . $sig . '&expires=' . $expires;
and then using cUrl to query the url
$curl_response = $this->getCurl($url);
...
function getCurl($url){
//Initialize cURL.
$ch = curl_init();
//Set the URL that you want to GET by using the CURLOPT_URL option.
curl_setopt($ch, CURLOPT_URL, $url);
//Set CURLOPT_RETURNTRANSFER so that the content is returned as a variable.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Set CURLOPT_FOLLOWLOCATION to true to follow redirects.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
//Execute the request.
$data = curl_exec($ch);
//Close the cURL handle.
curl_close($ch);
//Print the data out onto the page.
$url_response = json_decode($data);
$curl_status = $url_response->status;
//forms retrieved successfully
return $url_response->response;
}
function calculate_signature($string, $private_key) {
$hash = hash_hmac("sha1", $string, $private_key, true);
$sig = rawurlencode(base64_encode($hash));
return $sig;
}

ReplyMarkup in php telegram bot

I have problem with my telegram bot.I want to make Keybaord for my bot. When I run my telegram api url from my browser it works:
https://api.telegram.org/mybottoken/sendmessage?chat_id=93119306&text=something&reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]], "one_time_keyboard":true};
but
When I want run to this url($sendto Variable) in my php file this not work.
my php code is:
<?php
define('BOT_TOKEN', '183690241:AAHgluc7D9g0DF_InurfBj2YdBgPE7fmymo');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
$array = array();
// read incoming info and grab the chatID
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
$chatText = $update["message"]["text"];
// compose reply
$reply = sendMessage();
// send reply
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply."&reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]], "one_time_keyboard":true};
file_get_contents($sendto);
function sendMessage(){
global $chatID;
global $chatText;
if ($chatText =="/start") {
$message = "Salam - Roboate Megat Hastam";
}
elseif ($chatText =="Khoobi?") {
$message = "Merc - Shomaa khobi?";
}
elseif ($chatText =="Chand salete?") {
$message = "Be Tu Che!";
}
else
{
$message = "No Command";
}
return rawurlencode($message);
}
?>
please help where i made mistake.
thanks all guys.
Try this code:
var_dump($keyboard = json_encode($keyboard = [
'keyboard' => [
['Yes'],['No'],['Maybe'],
['1'],['2'],['3'],
] ,
'resize_keyboard' => true,
'one_time_keyboard' => true,
'selective' => true
]),true);
function sendKeyboard($chat_id, $keyboard) {
$text = "Merc - Shomaa khobi?";
file_get_contents(API_URL ."sendMessage?chat_id=".$chat_id."&reply_markup=".$keyboard."&text=".urlencode($text));
}
if($message == "/start"){
sendKeyboard($chat_id, $keyboard);
}

Upload image/video to facebook asynchronously using php sdk 4

I am trying to upload video/image to facebook albumb using php sdk 4 asynchronously.I googled and found that php asynchronous call be sent using fsockopen. However, it is not working for facebook request. I have two files, one for checking login and getting token. Then second file is called for uploading the file to facebook. Below is the code for first file:
// start session
session_start();
Yii::import('application.vendor.*');
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// init app with app id and secret
FacebookSession::setDefaultApplication('xxxxx', 'yyyy');
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://website.com/user/login/page/view/fb-share-php1' );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
}catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb'] = $session;
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
//$session = new FacebookSession( $session->getToken() );
// graph api request for user data
//$request = new FacebookRequest( $session, 'GET', '/me' );
//$response = $request->execute();
backgroundPost('http://website.com/user/login/page/view/fb-share-php');
// get response
//$graphObject = $response->getGraphObject()->asArray();
// print profile data
//echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
}else {
// show login url
echo 'Login';
}
function backgroundPost($url){
$parts=parse_url($url);
//print_r($parts);exit;
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
echo "test";
return false;
} else {
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ". 0 ."\r\n";
$out .= "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n";
$out .= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
// print_r($out);exit;
fwrite($fp, $out);
fclose($fp);
return true;
}
}
And second file is:
// start session
session_start();
Yii::import('application.vendor.*');
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
$session = $_SESSION['fb'] ;
file_put_contents('file.txt', serialize($session));
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/photos', array(
'source' => '#/var/www/website-root/images/add_more.png',
'message' => 'User provided message'
)
))->execute()->getGraphObject();
file_put_contents('files.txt', serialize($session));
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
Finally, I figured out the way to achieve it. Now, I am using facebook javascript sdk with php sdk. Following is the process:
1)Get access token from javascript sdk(first file) and pass it to background along with the url of image/video. Code may be modified, if image/video is being uploaded through source.
2) php file(2nd file) containing function for executing backend-process(which is in third file) receives the posted data and and call the third file(in the form of url) and pass the data to it as well.
3) File(s) are uploaded to facebook through php sdk 4(third file)
Below is the code for first file containing javascript sdk code:
<script>
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function() {
FB.init({
appId : 'your app id',
xfbml : true,
version : 'v2.0'
});
FB.login(function(response){
console.log(response);
if (response.status === 'connected') {
var data = new Array();
alert('Logged into your app and Facebook.');
//type: 0 for photo and type:1 for video. Create data array dynamically for real word applications
data[0]= {url: 'http://url-of-video-file.mov',privacy : 'SELF', message: "title of video", type:1};
data[1]= {url: 'http://url-to-image-file.png',privacy : 'SELF', message: "photo caption", type:0};
$.ajax({
url: 'http://url-of-second-file/containing-code-for/backend-process',
data: {data: data, accessToken:response.authResponse.accessToken},
type: 'POST',
success:function(){
alert("photo uploaded");
}
});
},{scope:'email'});
}
</script>
Now code of second file which receives data and execute back-end process:
<?php
//session_start();
ignore_user_abort(true);
set_time_limit(0);
function backgroundPost($url){
$parts=parse_url($url);
//print_r($parts);exit;
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
echo "test";
return false;
} else {
$vars = $_POST;
$content = http_build_query($vars);
//file_put_contents('url.txt',$content);exit;
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ". strlen($content) ."\r\n";
//$out .= "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n";
$out .= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
// print_r($out);exit;
fwrite($fp, $out);
fwrite($fp,$content);
fclose($fp);
return true;
}
}
backgroundPost('http://link-to-third-file/containing-code-for-facebook-upload');
Now code of third file, which will actually upload the files. Please note, video files need to be downloaded before it can be uploaded.
<?php
// start session
//session_start();
error_reporting(1);
ignore_user_abort(true);
set_time_limit(0);
#ini_set('display_errors', 1);
//include facebook library through autoload
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// init app with app id and secret
FacebookSession::setDefaultApplication('app_id','secret_key' );
$session = new FacebookSession( $_POST['accessToken'] );
foreach($_POST['data'] as $key => $data){
if($data['type'] == 1){
$ext = substr($data['url'],strrpos($data['url'],'.'));
$file = '/path/to/temp/location/for/saving/video/'.time().$ext;
if(file_put_contents($file,file_get_contents($data['url']))){
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/videos', array(
'source' => '#'.$file,
'title' => $data['message'],
'privacy' => json_encode(array('value' => $data['privacy'])),
'published' => true
)
))->execute()->getGraphObject()->asArray();
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}else{
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/photos', array(
'url' => $data['url'],
'message' => $data['message'],
'privacy' => json_encode(array('value' => $data['privacy'])),
'published' => true
)
))->execute()->getGraphObject()->asArray();
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}
?>

I can push notification to one device but fail to push in a loop

I code my push notification service as shown below. It will gain token stored in test_db and then send it. The problem is that I don't receive notification from all my device. But, if I send notification to one specific device and I uncomment **//if( $row['pushtoken']=='bfd53a383e0f65bc96b43f3547548ec13d4c46d61526d7b6be5d7ed581563e77')**, the device will receive a notification. It is very weird. Here is my code:
$link = mysql_connect('localhost', 'root', '111111');
if (!$link) {
error_log( "mysql_connect fail\n");
die('could not connect: ' . mysql_error());
}
else
{
$is_db_selected = mysql_select_db('test_db',$link);
if($is_db_selected)
{
$sql = "select * from pushtoken;";
error_log($sql);
$result = mysql_query($sql, $link);
if ($result)
{
echo "ready to push notification\n";
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'aps_dev.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 10, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT , $streamContext);
if (!$apns)
exit("Failed to connect: $error $errorString" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
ob_flush();
flush();
$payload['aps'] = array('alert' => 'xman give mortal 7 messages!!!', 'badge' => 1, 'sound' => 'default');
$payload = json_encode($payload);
while ($row = mysql_fetch_assoc($result))
{
***//if( $row['pushtoken']=='bfd53a383e0f65bc96b43f3547548ec13d4c46d61526d7b6be5d7ed581563e77')***
{
echo "push notification one by one\n";
$deviceToken = $row['pushtoken'];
$apnsMessage = chr(0) . pack("n", 32) . pack('H*', $deviceToken) .pack("n", strlen($payload)). $payload;
if(fwrite($apns, $apnsMessage,strlen($apnsMessage))==FALSE)
{
echo "can't write to socket!<br />";
}
ob_flush();
flush();
//fclose($apns);
echo "token is ".$deviceToken ."\n";
//break;
}
}
//socket_close($apns);
fclose($apns);
} else {
error_log ('error select pushtoken: ' . mysql_error() . "\n");
}
}
}
You may want to check that all of the tokens are valid. In the past I had an issue where if I had a dev token in my DB and tried to use the production push server all the messages that were sent after the message using the dev token would fail to be delivered.

Resources