Posts Tagged ‘PHP’

If you’re developing an iPhone, iPod Touch or iPad app and get stuck, the internet definitely is your friend. You can find lots of helpful resources on different coding forums or sites like this one.

However, sometimes the information there is just not enough or you might have an idea and don’t know how to get started.
Well, this is where our new service might come in handy.

As of now, you can schedule a 1 on 1 session with one of our coders and he/she will help you.

Sessions will be held via iChat and our coder will share his/her screen with you. This way, you can exactly see what is going on and therefore learn much faster. If you like, we’ll also do a screen recording for free, so you can watch it later again and again at no extra cost.

Some session examples:

* Your first app: How to build proper view hierarchy.
* SQLite database programming.
* Server communication – How to submit and retrieve data from a webserver.
* In app purchases.
* Push notifications.
* 3D game development
* etc…

Our live coding sessions are available in both english and german language.

If you’re interested, just send an email to lindmandesignsupport[at]me.com and we’ll provide you with details on pricing, etc…

I recently discovered, that push notifications containing the word “(null)” (without the quotes) do not get pushed. They don’t break your APNS connection, simply never reach the recipient’s device.
Most likely, Apple wants to avoid some injection and I’m pretty sure, there are more words out there, that will not push.

In PHP, you can take simple precautions, to work around this:

$message = "(null) bla bla bla bla bla"; //this is our message
$messageFiltered = str_replace("(null)", "", $message);

I discovered this, when trying to push an iCal calendar event. Sometimes, iCal does not add the sender’s name, but (null) instead.

Hope, this is helpful to someone out there.
In case, you know more “forbidden words”, please leave a comment.

When your PHP-MYSQL implementation has to deal with special characters (umlauts), you might wanna pay close attention to your setup. Usually, it doesn’t work right out of the box and if only one tiny piece of your puzzle is missing, chances are high your characters won’t get displayed as desired.

Let’s assume we have some data in our MYSQL database we simply wanna get via PHP. Standard procedure would be something like this:

Connect to database:

<?
$conn = mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db('databaseName', $conn) or die(mysql_error());
?>

Get data and print them on screen:

$sql = mysql_fetch_array(mysql_query("SELECT * FROM myTable"), MYSQL_ASSOC);
echo $sql['fieldInTable'];

In case you are using characters in english language only, the above will work as expected.

But what if your data contain umlauts, like “Ö”, “Ü”, “ß”, etc…? Well, you might see some weird letters instead and that’s what probably brought you here, right? :)

If you do some quick internet research on this topic, you will find countless discussions and possible solitions. However, if none of them worked for you so far, try the following:

Connect to database:

<?
$conn = mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db('databaseName', $conn) or die(mysql_error());
mysql_query("SET NAMES 'utf8'"); //this is new
mysql_query("SET CHARACTER SET 'utf8'"); //this is new
?>

Get data and print them on screen:

$sql = mysql_fetch_array(mysql_query("SELECT * FROM myTable"), MYSQL_ASSOC);
echo utf8_decode($sql['fieldInTable']); //this is new

In case it still doesn’t work, make sure your PHP document is UTF-8 encoded. Depending on the code editor you are using, you should easily be able to change encoding.
For example, in CODA it works like this:

It took me quite some time to figure this out, so hopefully you might find it helpful.

The following script connects to a mailbox, reads an email, fetches some important data and then deletes the email.

This is probably useful, if you want to automatically empty your mailbox on a regular basis and store data in a database.


<?
$mailbox = imap_open("{localhost:143/notls}INBOX", "your@emailaddress.com", "mailboxPassword");  //connects to mailbox on your server

if ($mailbox == false) {
 echo "<p>Error: Can't open mailbox!</p>";
 echo imap_last_error();
}
else {

 //Check number of messages
 $num = imap_num_msg($mailbox);

 //if there is a message in your inbox
 if( $num > 0 ) { //this just reads the most recent email. In order to go through all the emails, you'll have to loop through the number of messages
 $email = imap_fetchheader($mailbox, $num); //get email header

 $lines = explode("\n", $email);

 // data we are looking for
 $from = "";
 $subject = "";
 $to = "";
 $splittingheaders = true;

 for ($i=0; $i < count($lines); $i++) {
 if ($splittingheaders) {
 // this is a header
 $headers .= $lines[$i]."\n";

 // look out for special headers
 if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
 $subject = $matches[1];
 }
 if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
 $from = $matches[1];
 }
 if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
 $to = $matches[1];
 }

 }
 }

 //We can just display the relevant information in our browser, like below or write some method, that will put that information in a database
 echo "FROM: ".$from."<br>";
 echo "TO: ".$to."<br>";
 echo "SUBJECT: ".$subject."<br>";
 echo "BODY: ".imap_qprint(imap_body($mailbox, $num));

 //delete message
 imap_delete($mailbox,$num);
 imap_expunge($mailbox);
 }
 else {
 echo "No more messages";
 }

 imap_close($mailbox);
}
?>

If you’re an iPhone, iPod Touch or iPad developer, you might have heard about Apple’s push notification service. It’s a convenient way to send messages to your users or even allow them to communicate with each other (via your server). You can find great tutorials on the internet, that show you how you can get started. I can especially recommend:

http://blog.boxedice.com/2009/07/10/how-to-build-an-apple-push-notification-provider-server-tutorial/
and
http://mobiforge.com/developing/story/programming-apple-push-notification-services

I admit, it really depends on the scale of your service and the possible message load, but you might wanna pay close attention to the following statement, which can be found in the official Apple docs:

Refrain from opening and closing the connections to the APNs for each push notification that you want to send. Rapid opening and closing of connections to the APNs will be deemed as a Denial-of-Service (DOS) attack and may prevent your provider from sending push notifications to your applications.

What does this mean?


It means, that you should retain an open connection to APNS and not open/close it every time you send a message. Most php scripts out there dealing with APNS exactly do that! They open a connection, send a single message or a couple of messages from your database and then close the connection. As I already mentioned, it depends on how you are using APNS. If you send messages every hour or every couple of hours, you should be fine and there is probably nothing to worry about.

However, if you are rather looking for a dynamic way of pushing (user to user via your server), you of course wanna avoid putting all messages in a queue and sending them out every hour.

What you need in this case, is something a bit more advanced.

[I don't claim for this solution to be the best one - it certainly is not - but it GET'S THE JOB DONE]

So, let’s take a look at it, shall we?

1) We need to create an empty php script. You can do this in a text editor or whatever php editor you prefer. Name it PushScript.php or give it some other meaningful name.


<?

set_time_limit(0); //Keep process running forever...

$timeNow = strtotime("now"); //get current time and time + 2 hours. I read, that an idle connection might time out after 2 hours, so we will later use this information to re-connect

$inTwoHours = strtotime("+ 2 hours"); 

First, we set time limit to 0. This makes sure, that the php script does not accidentally time out.
Next, we get the current time and another time stamp (+2 hours). We will later use this to close connection to APNS and re-open it.

Why are we doing that?

Well, I read on several blogs, that Apple might close an idle connection after some time. Some people report, that it can actually stay open for several days, but keeping it down to 2 hours, will most likely give us the least trouble.


//connect to APNS - ONLY 1 time after script is started
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'nameOfDevCertificateInSameFolder.pem');
$apnsConnection = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
error_log(date('Y-m-d H:i')." - Successfully connected to APNS", 3, 'PushLog.log'); //log, that we are successfully connected - used for debugging

The script runs from top to bottom and when we call it we wanna make sure, that our server makes a connection to APNS.


//let's start our "deamon"
while (true) {

 //here we are sending a single message to a single device every 60 seconds. In theory you could run some mySQL query to empty a queue.

 $deviceToken = '************************************************'; // your device token here

 $message = 'Hi, I'm a push message!';
 $badge = (int)$argv[2];
 $sound = 'soundFile.caf'; //name of the sound file inside the XCode project.
 // Construct the notification payload
 $body = array();
 $body['aps'] = array('alert' => $message);
 if ($badge)
 $body['aps']['badge'] = $badge;
 if ($sound)
 $body['aps']['sound'] = $sound;

 $payload = json_encode($body);
 $msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
 error_log(date('Y-m-d H:i')." - Pushing message to APNS", 3, 'PushLog.log'); //another log entry
 fwrite($apnsConnection, $msg); //this pushes the message to APNS

This is actually our “deamon”. It will loop and loop and because we set the time limit to 0, this process won’t get killed. Look at the code comments, it’s pretty much self explanatory.


//now let's close and re-open connection every 2 hours
 if (strtotime("now") >= $inTwoHours) {
 $timeNow = strtotime("now");
 $inTwoHours = strtotime("+ 2 hours");

 //close APNS connection
 fclose($apnsConnection);
 error_log(date('Y-m-d H:i')." - Closing connection to APNS", 3, 'PushLog.log');

 //re-open APNS connection
 //connect to APNS - ONLY 1 time after script is started
 $ctx = stream_context_create();
 stream_context_set_option($ctx, 'ssl', 'local_cert', 'apns-dev.pem');
 // assume the private key passphase was removed.
 // stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);
 $apnsConnection = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);

 error_log(date('Y-m-d H:i')." - Reconnecting to APNS", 3, 'PushLog.log');
 }

Now, we’re using the time stamps, we created earlier. In case our old time stamp has expired (script ran longer than 2 hours), we renew it.

Finally:


sleep(60); // loop every X seconds
?>

Pause the loop for X seconds, until we start it again.

That’s pretty much it :)

When reading the code, you might have noticed, that we’re sometimes writing information to PushLog.log. I can highly recommend this. It will show you how many times you actually connect/disconnect and send a message. This way, you can see what your script is doing and that it does, what we want it to do.

In order to get this up and running, create the php file and the PushLog.log file (simple text file – just make sure, it has a .log suffix, instead of .txt).

Put both files, plus your push certificate into the same folder on your webserver and you’re good to go. Now, you only need to call the php script from your browser or terminal and you got your very own php deamon.

Hope, this is helpful. In case, you can’t get it to work, make sure the solution from the tutorials above works. Then use my script.

Happy pushing :)

[Code posted without any warranty whatsoever];

An App, you might like:
We recommend…
You might also like…
Get Adobe Flash playerPlugin by wpburn.com wordpress themes