Unable to submit forms to be analyzed - microsoft-cognitive

I have created my Form Recognizer AI, trained it, and received the modelID but when I actually go to implement this in Powershell it errors out, telling me it cannot read the file so I suspect it has something to do with my file being sent.
This is for form-recognizer 2.0, any suggestions?
cls
$aiFormRecognizerKey = '{apiKey}'
$aiFormRecognizerEndPoint = 'https://{Url}.cognitiveservices.azure.com/'
$aiModelToUse = 'f11f43a7-6207-4dc9-9e8a-fc58677047f1'
$headers = #{
"Ocp-Apim-Subscription-Key" = $aiFormRecognizerKey
"Content-Type" = "application/pdf"
}
$FormFields = #{
"form-data" = Get-Item C:\temp\test3.pdf
"type" = "application/pdf"
}
$analyzedDocumentLocation = (Invoke-WebRequest ($aiFormRecognizerEndPoint + 'formrecognizer/v2.0- preview/custom/models/' + $aiModelToUse + '/analyze' ) -Method "POST" -Headers ($headers) -Body $FormFields ).Headers.'Operation-Location'
$analyzedDocumentLocation
$uriTest = 'https://{url}.cognitiveservices.azure.com/formrecognizer/v2.0- preview/custom/models/5b4cb7c4-406f-400d-b53e-7d50fecd4a1d/analyzeresults/b07b863e-0aa5-4e1d-9a64- 73eb18c1f793'
Invoke-WebRequest -uri $uriTest -Method "GET" -Headers ($headers)
Edit:
Here is the solution for anyone curious such as myself:
cls
$aiFormRecognizerKey = '{Key}'
$aiFormRecognizerEndPoint =
'https://{MyEndPoint}.cognitiveservices.azure.com/'
$aiModelToUse = '{TrainedModelId}'
$headers = #{
"Ocp-Apim-Subscription-Key" = $aiFormRecognizerKey
}
$analyzedDocumentLocation = (Invoke-WebRequest -InFile C:\temp\test1.pdf -
ContentType "application/pdf" -uri ($aiFormRecognizerEndPoint +
'formrecognizer/v2.0-preview/custom/models/' + $aiModelToUse + '/analyze' )
-Method "POST" -Headers ($headers)).Headers.'Operation-Location'
$analyzedDocumentLocation
$uriTest = $analyzedDocumentLocation[0]
$FileStream.Close()
Start-Sleep -s 10
(Invoke-WebRequest -uri $uriTest -Method "GET" -Headers ($headers)).Content

It looks like your request body is attempting to use multipart/form-data which is no longer supported in v2.0 (although if it were, you would need to use that value in your Content-Type header).
Instead, you should pass the file content directly in the body parameter. Here's an end-to-end sample for PowerShell:
# Config
$headers = #{ "Ocp-Apim-Subscription-Key" = "your_key" }
$endpoint = "https://your_region.cognitiveservices.azure.com/formrecognizer/v2.0-preview"
# Train
$body = #{
"source" = "https://your_azure_storage_container_sas_url";
"sourceFilter" = #{ "prefix" = "optional" }
} | ConvertTo-Json
$resp = Invoke-WebRequest "$endpoint/custom/models" -Method "POST" -Headers $headers -Body $body -ContentType "application/json"
$location = $resp.Headers.Location[0]
$modelId = $location.Substring($location.LastIndexOf('/') + 1)
Write-Output "ModelId: $modelId"
# Wait for training
$status = $null
do {
Start-Sleep -Seconds 5
$resp = Invoke-WebRequest $location -Headers $headers
$body = $resp.Content | ConvertFrom-Json
$status = $body.modelInfo.status
Write-Output "Training... $status"
} while ($status -eq "creating")
if ($status -ne "ready") {
throw "Training failed"
}
# Analyze
$content = Get-Content -Raw /path/to/your/file.pdf -ReadCount 0
$contentType = "application/pdf"
$resp = $content | Invoke-WebRequest "$endpoint/custom/models/$modelId/analyze" -Method "POST" -Headers $headers -ContentType $contentType
$location = $resp.Headers.'Operation-Location'[0]
# Wait for analysis
$status = $null
do {
Start-Sleep -Seconds 5
$resp = Invoke-WebRequest $location -Headers $headers
$body = $resp.Content | ConvertFrom-Json
$status = $body.status
Write-Output "Analyzing... $status"
} while ($status -eq "notStarted" -or $status -eq "running")
if ($status -ne "succeeded") {
throw "Analysis failed"
}
# Output
Write-Output $resp.Content
Note that I'm piping $content (the PDF) into Invoke-WebRequest. You might also be able to load the file into memory and pass using the -Body parameter.
Hope this helps!

Related

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

Get user's ISP, country and city by 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');

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