I’ve been banging my head on the wall trying to get this work for the past week. I just started again from scratch and logged everything that I did and it still does not work. Here are the steps i’ve taken:
1) Create a new App ID Identifier using a new bundle id (the old one did not have push notifications)
a) made sure push notifications were added to the app id and proceeded to the last step, this resulted in an app id with push notifications in the ‘configurable’ state.
b) I then went to edit the app id and saw that i could create a new production or development certificate so i did both using the steps listed
2) Created two new provisioning profiles, one for dev and one for production, both are using the new bundle id
3) import the new provisioning profiles into Xcode and make sure that those are the ones selected in the build settings
4) create the .p12 files by using the keychain and exporting the .cer files for dev and production
5) create the .pem file from the .p12 files using these commands:
openssl pkcs12 -in VX-Mobile-Dev.p12 -out apns-dev.pem -nodes -clcerts
openssl pkcs12 -in VX-Mobile-Prod.p12 -out apns-prod.pem -nodes -clcerts
6) Next created a php script (that i blatantly ripped off from another blog) that i run from the command line of one of my virtual machines. In the same folder as that file i put the pans-prod.pem file. Here is the contents of that file
Note, for the device token i simply run the app from Xcode where it already successfully connects to the apns server and gets a device token which gets logged out into the console, for testing purposes i am just copying the new token into the file each time.
File contents:
// set time limit to zero in order to avoid timeout
set_time_limit(0);
// charset header for output
header('content-type: text/html; charset: utf-8');
// this is the pass phrase you defined when creating the key
$passphrase = '{passphrase is hidden to you!}';
// you can post a variable to this string or edit the message here
if (!isset($_POST['msg'])) {
$_POST['msg'] = "Notification message here!";
}
// function for fixing Turkish characters
function tr_to_utf($text) {
$text = trim($text);
$search = array('Ü', 'Þ', 'Ð', 'Ç', 'Ý', 'Ö', 'ü', 'þ', 'ð', 'ç', 'ý', 'ö');
$replace = array('Ãœ', 'Åž', 'Ğž', 'Ç', 'Ä°', 'Ö', 'ü', 'ÅŸ', 'ÄŸ', 'ç', 'ı', 'ö');
$new_text = str_replace($search, $replace, $text);
return $new_text;
}
// tr_to_utf function needed to fix the Turkish characters
$message = tr_to_utf($_POST['msg']);
// load your device ids to an array
$deviceIds = array(
'97c8c0a77e1380d052d17352e33b1f2224f082a3436ee90310cf88c7278329e7'
);
// this is where you can customize your notification
$payload = '{"aps":{"alert":"' . $message . '","sound":"default"}}';
$result = 'Start' . "\r\n";
////////////////////////////////////////////////////////////////////////////////
// start to create connection
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'apns-prod.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
echo count($deviceIds) . " devices will receive notifications.\r\n";
foreach ($deviceIds as $item) {
// wait for some time
sleep(1);
// Open a connection to the APNS server
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp) {
exit("Failed to connect: $err $errstr" . "\r\n");
} else {
echo 'Apple service is online. ' . "\r\n";
}
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result) {
echo 'Undelivered message count: ' . $item . "\r\n";
} else {
echo("\r\nRESULT\r\n\r\n");
var_dump($result);
echo("\r\n\r\n");
echo 'Delivered message count: ' . $item . "\r\n";
}
if ($fp) {
fclose($fp);
echo 'The connection has been closed by the client' . "\r\n";
}
}
echo count($deviceIds) . " devices have received notifications.\r\n";
// set time limit back to a normal value
set_time_limit(30);
Please help.
Turns out i was almost there. The only problem was that i should have been using the sandbox endpoint.
ssl://gateway.sandbox.push.apple.com:2195
Also, in response to RJV Kumar, once i got it working i tried it with both my prod and my dev certificate and it worked in both cases. This seems suspicious to me but whatever i'm just glad that its working.
[UPDATE]
While the steps in this post are technically correct, i learned that you should NOT create a new App ID if you actually want to be able to release a new version of your app. Instead of doing this you should simply add push notifications to your current App ID.
Related
I have attached two different PDF files (mnlocalXampp and rnlocalXampp) that is phpinfo of two different pcs. I have checked both information and seem that both have same information and using same version of PHP but I'm receiving email in mnlocalXampp but not in rnlocalXampp. I also activated openssl in both but i am still not receiving email in rnlocalxampp. Can anyone please look at both the files and let me know what difference in that files and how to configure.
<?php
require 'email_class/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = 'cp-in-10.webhostbox.net'; //Sets the SMTP hosts of your Email hosting, this for Godaddy
$mail->Port = '465'; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = 'mn#infotech.com'; //Sets SMTP username
$mail->Password = 'xxxxxxx'; //Sets SMTP password
$mail->SMTPSecure = 'ssl'; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = 'mn#infotech.com'; //Sets the From email address for the message
$mail->FromName = "mn"; //Sets the From name of the message
$mail->AddAddress("m#infotech.com"); //Adds a "To" address
$mail->AddCC("m#infotech.com"); //Adds a "Cc" address
$mail->WordWrap = 50; //Sets word wrapping on the body of the message to a given number of characters
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$mail->IsHTML(true); //Sets message type to HTML
$mail->Subject = 'Project CMS'; //Sets the Subject of the message
$mail->Body = $message; //An HTML or plain text message body
$mail->AddStringAttachment($doc, 'doc.pdf', 'base64', 'application/pdf');
$mail->Send(); ?>
The above sample code is email configuration of mnlocaXampp. For the rnlocalXampp I'm using different Port(Port number: 25), Hosting, SSL enabled.
mnlocalXampp
rnlocalXampp
Thanks in advance
Difficult to know where to start.
You've based your code on an obsolete example and you're using an old version of PHPMailer, so get the latest, and base your code on the examples provided.
You're not defining $doc before you use it.
addStringAttachment is the wrong method to use if you're trying to send a local file; use addAttachment instead.
The definition of $headers is pointless.
There's no point in CC'ing an address you're already sending to.
You have no error checking anywhere.
Resolving some of the above items may help to fix your problem.
I have a form which requires a google reCAPTCH to be ticked. It is working perfectly on Local but does not work when I put it on the development server. I have replaced the registered keys to the ones appointed to me by Google.
It keeps outputting the error message.
The method in my form is post.
I do not understand why it doesn't work. Can someone please help me?
Here is my code:
$secretKey = "#######";
$captcha = $_POST['g-recaptcha-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
$throwErrorMessage = "You are a robot! ";
$throwError = 1;
$isvalid = False;
};
What version of ReCAPTCHA are you using? The docs on Google website here are pretty different than your code. In particular, you use the function file_get_contents while the documentation uses recaptcha_check_answer like in this example:
<?php
require_once('recaptchalib.php');
$privatekey = "your_private_key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again."."(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
}
?>
Can you post the error message?
I am trying to setup SwiftMailer on my server. I am using the example configuration from the SwiftMailer docs for testing. I have a paid G Suite account but haven't finished setting up SSL on the server yet. I am running Cent OS 6.8 and Apache 2.2. I have googled everything I can think of and tried all the proposed solutions with no success.
My script is as follows, obviously my email address and credentials are correct in the real script. I appreciate any advice.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('swiftmailer-5.x/lib/swift_required.php');
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp-relay.gmail.com', 25)
->setUsername('myemail#mydomain.com')
->setPassword('*****')
;
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Swift Mailer Test')
->setFrom(array('my from address'))
->setBody('Here is the message itself')
;
// Send the message
$failedRecipients = array();
$numSent = 0;
$to = array('another#email.com' => 'Joe');
foreach ($to as $address => $name)
{
if (is_int($address)) {
$message->setTo($name);
} else {
$message->setTo(array($address => $name));
}
$numSent += $mailer->send($message, $failedRecipients);
}
printf("Sent %d messages\n", $numSent);
?>
When I run this script I get the following very vague error:
"Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host smtp-relay.gmail.com [Connection timed out #110]' in /var/www/html/appreciate-erp/swiftmailer-5.x/lib/classes/Swift/Transport/StreamBuffer.php:269 Stack trace: #0 /var/www/html/appreciate-erp/swiftmailer-5.x/lib/classes/Swift/Transport/StreamBuffer.php(62): Swift_Transport_StreamBuffer->_establishSocketConnection() #1 /var/www/html/appreciate-erp/swiftmailer-5.x/lib/classes/Swift/Transport/AbstractSmtpTransport.php(113): Swift_Transport_StreamBuffer->initialize(Array) #2 /var/www/html/appreciate-erp/swiftmailer-5.x/lib/classes/Swift/Mailer.php(79): Swift_Transport_AbstractSmtpTransport->start() #3 /var/www/html/appreciate-erp/mailtest.php(42): Swift_Mailer->send(Object(Swift_Message), Array) #4 {main} thrown in /var/www/html/appreciate-erp/swiftmailer-5.x/lib/classes/Swift/Transport/StreamBuffer.php on line 269"
As of https://support.google.com/a/answer/176600, it seems like SMTP Relay on G-Suite applies IP address restriction. The "could not connect" error would fit as the result of a missing configuration or the attempt to connect from another IP address as the one configured. Hope this helps!
I am trying to build a small app that will take a multipart/form-data to send a form with two data items:
username - a text field
file - an image file
The app blocks are attached in the picture to this mail. I do not know how to send multipart/form-data with both files and text-based form data. Need your suggestions on this. Can you please help?
For those who are not acquainted with the Content-Type=multipart/form data, here is a one liner about it:
The content type "application/x-www-form-urlencoded" is inefficient
for sending large quantities of binary data or text containing
non-ASCII characters. The content type "multipart/form-data" should be
used for submitting forms that contain files, non-ASCII data, and
binary data.
More details can be found in:
https://www.w3.org/TR/html401/interact/forms.html#successful-controls
I have found ways to achieve it using get and put methods. I would want to achieve this using the Post method.
The php server code is:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$user = $_POST["username"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Upload failed with reason = $uploadFailureReason <br>";
}
else {
echo "Upload Sucessful <br>";
$pyscript = '/home/ubuntu/workdir/src/httppython.py';
$python = '/home/ubuntu/.virtualenvs/cv/bin/python';
$filePath = $target_file;
$cmd = "$python $pyscript --image $filePath --user $user";
//echo "command = $cmd ";
exec("$cmd", $output);
echo "<input type=button onClick=\"location.href='upload_new.html'\" value='New Upload'>"
}
?>
Background: I'm working on an api which I host on ec2 servers. I just finish the login and set up an nginx loadbalancer which redirect to the said server's internal ip's. The domain name points to the load balancer.
This used to work well with code igniter, but now I keep getting an "invalid host" problem.
I tried googling it and it found some things about trusted proxies so I installed what fideloper made and tried his post as well (I've followed a guide by fideloper on laravel-4-trusted-proxies and used and tried his trusted sample on github: fideloper/TrustedProxy) but I still get the same error:
UnexpectedValueException
Invalid Host "api.myserver.im, api.myserver.im"
// as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
// check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
if ($host && !preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host)) {
throw new \UnexpectedValueException(sprintf('Invalid Host "%s"', $host));
}
Can someone help me?
I had the same issue as well. I had to resort to modifying the UrlGenerator.php file, which is part of the framework (bad I know...) just to get this to work.
So here's my "temporary" solution.
Create an array value to your app.php config file. e.g:
return array(
'rooturl' => 'https://www.youractualdomainname.com',
...
Next add the below modification in your UrlGenerator.php file <-- (trunk/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php)
<?php namespace Illuminate\Routing;
use Config;
...
protected function getRootUrl($scheme, $root = null)
{
$approoturl = Config::get('app.rooturl');
$root = isset($approoturl) ? $approoturl : $this->request->root();
return $root;
// if (is_null($root))
// {
// $root = $this->forcedRoot ?: $this->request->root();
// }
// $start = starts_with($root, 'http://') ? 'http://' : 'https://';
// return preg_replace('~'.$start.'~', $scheme, $root, 1);
}
Do note that composer update will revert your modification.