They say you learn something new every day.

Posts tagged ‘php’

Sending eMail (01/05/2012)

As much as I may hate it, sometimes you have to send eMail with code. Like democracy, eMail is the worst form of communication, except for all the others.

Each coding language has different ways of sending eMail. I had to send some messages with PHP today, so I put this little function together:

function send_email($from, $to, $subject, $message)
{
$headers = “From: “.$from.”\r\n”;
$headers .= “Reply-To: “.$from.”\r\n”;
$headers .= “Return-Path: “.$from.”\r\n”;
$headers .= “Content-type: text/html\r\n”;
mail($to,$subject,$message,$headers);

It turns out you can’t use bcc in PHP (it’s blocked for security reasons, bizarrely). So when I wanted to bcc someone, I just had to call the same function twice with different email addresses.

Advertisements

Twitter API (21/04/2012)

I’m building a little web application, and for part of it, I want to use the Twitter API, but by God the documentation is complex.

Luckily, I’ve found Matt Harris’s Twitter API Functions. I’ve been playing with them all day, and finally discovered, thanks to Stack Overflow (as ever) that there’s a slight tweak you need to make because of a change in December 2011.

In the code below I’ve got a little function to post tweets. The line in bold is the one that was missing and was causing me to pull my hair out:

 <?php

$tweet_text = ‘Hello Twitter’;
print “Posting…\n”;
$result = post_tweet($tweet_text);
print “Response code: ” . $result . “\n”;

FUNCTION post_tweet($tweet_text) {

require_once(‘tmhOAuth.php’);

$connection = new tmhOAuth(array(
  ‘consumer_key’ => ‘xxx’,
  ‘consumer_secret’ => ‘xxx’,
  ‘user_token’ => ‘xxx’,
  ‘user_secret’ => ‘xxx’,
‘curl_ssl_verifypeer’ => false
));

$connection->request(‘POST’, $connection->url(‘1/statuses/update’), array(‘status’ => $tweet_text));
return $connection->response[‘code’];

}

?> 

Client side (25/02/2012)

I was reading an article in .Net Magazine the other day and someone had asked a developer:

“Is it better to run your code on the server side or the client side?”

 And the developer said something along the lines of:

“Client side. This will scale better since the users’ computers will do all the work”.

It’s kind of obvious really, but I realised I’ve been doing this wrong. Take my wordcount tool, for example (the design of which is beginning to look a bit crappy to me, which is good, because it means I’m getting better at designing things). It’s built in PHP, which means it uploads all the content to my server and runs the commands on my server.

If you think about it, this is kind of stupid for two reasons:

  1. I’m having to submit a load of data over the internet, which is slow.
  2. I’m having to run all the commands on my server. Which doesn’t scale and means my computer is doing the work.

This is a prime example of when doing it on the user’s computer would be better.

So I’ve started rebuilding it in javascript. It turns out I’m a bit rusty at javascript, and also PHP has some “lovely” built in functions (like a wordcount functions). I think I see what Jeff meant about PHP now. It’s such a weird language:

PHP isn’t so much a language as a random collection of arbitrary stuff, a virtual explosion at the keyword and function factory

Nevertheless, I still quite like it, but it makes it quite difficult to translate form PHP to javascript. I’m going to have to rewrite my wordcount code more or less from scratch.

This is no bad thing though – it’ll be some good javascript practice.

Hi again, Fidelity (09/02/2012)

I think I was too quick to re-judge High Fidelity. It’s actually really good.

Or rather, it’s got really good. I think, thinking about the beginning, it has got better. And there are definitely some bits that could probably do with a slight tweak. But other bits that are like this, that are just fantastic:

First of all, — actually, first of all and last of all — this business about not sleeping with Ian. How do I know she’s telling the truth? She could have been sleeping with him for weeks, months, for all I know. And anyway, she only said that she hasn’t slept with him yet, and she said that on Saturday, five days ago. Five days! She could have slept with him five times since then! (She could have slept with him twenty times since then, but you know what I mean.) And even if she hasn’t, she was definitely threatening to. What does ‘yet’ mean, after all? ‘I haven’t seen Resevoir Dogs yet.’ What does that mean? It means you’re going to go, doesn’t it?

‘Barry, if I were to say to you that I haven’t seen Reservoir Dogs yet, what would that mean?’

Barry looks at me.

‘Just … come on, what would it mean to you? That sentence? ‘I haven’t seen Reservoir Dogs yet?’ ‘

‘To me, it would mean that you’re a liar. Either that or you’ve gone potty. You saw it twice. Once with Laura, once with me and Dick. We had that conversation about who killed Mr. Pink or whatever fucking color he was.’

‘Yeah, yeah, I know. But say I hadn’t seen it and I said to you, ‘I haven’t seen Reservoir Dogs yet,’ what would you think?’

‘I’d think, you’re a sick man. And I’d feel sorry for you.’

‘No, but would you think, from that one sentence, that I was going to see it?’

‘I’d hope you were, yeah, otherwise I would have to say that you’re not a friend of mine.’

‘No, but — ‘

‘I’m sorry, Rob, but I’m struggling here. I don’t understand any part of this conversation. You’re asking me what I’d think if you told me that you hadn’t seen a film that you’ve seen. What am I supposed to say?’

‘Just listen to me. If I said to you — ‘

’ — ‘I haven’t seen Reservoir Dogs yet,’ yeah, yeah, I hear you — ‘

‘Would you … would you get the impression that I wanted to see it?’

‘Well … you couldn’t have been desperate, otherwise you’d have already gone.’

‘Exactly. We went first night, didn’t we?’

‘But the word ‘yet’ … yeah, I’d get the impression that you wanted to see it. Otherwise you’d say you didn’t fancy it much.’

‘But in your opinion, would I definitely go?’

‘How am I supposed to know that? You might get run over by a bus, or go blind, or anything. You might go off the idea. You might be broke. You might just get sick of people telling you you’ve really got to go.’

I don’t like the sound of that. ‘Why would they care?’

‘Because it’s a brilliant film. It’s funny, and violent, and it’s got Harvey Keitel and Tim Roth in it, and everything. And a cracking sound track.’

Maybe there’s no comparison between Ian sleeping with Laura and Reservoir Dogs after all. Ian hasn’t got Harvey Keitel and Tim Roth in him. And Ian’s not funny. Or violent. And he’s got a crap sound track, judging from what we used to hear through the ceiling. I’ve taken this as far as it will go. But it doesn’t stop me worrying about the ‘yet.’

The conversation here is amazing and very funny. And the way it jumps from the thought process to the conversation is very neat. I think that’s an interesting trick to segue between sections. It’s so slick you nearly don’t notice it.

I also love the rhythm of the conversation. Both speakers are pulling in different directions and it works so well. You get a feel for their characters, as well as being driven forwards by the plot.

I think the other two things to take away from this is the variance and rhythm of the sentences. You can have simple sentences with long words, or you can have long sentences with simple words.

I ran High Fidelity through the Uber Word Count tool that I wrote a while back. The tool, I notice now, needs some tweaking and styling. And I’m glad I can see that now, as it means I’m better than I was when I wrote it.

To be honest, it didn’t really tell me that much, other than most of the words were very short, but it was interesting to see the results. And how long the novel was, and how many different words were used.

I think if there’s one thing to take away from this, though, it’s conversation. Conversation, conversation, conversation in novels.

Backup to the Drawing Board (06/01/2012)

Continuing my plan to backup my life, I turned to all the images for this blog. Yesterday I figured out how to back up the content to another WordPress blog, using If This Then That. The next stage is to backup all the images.

I store all of the images on my website so that they’re all in one place. In one way, this is a bit silly, because it means I bear all the bandwidth costs. But, hey, apparently I’ve got 7TB of monthly bandwidth! Considering this site is just a log for me, I think I’ll be okay.

The upside of this is that because all of the pictures are stored in one place, they’re very easy to backup.

But, remembering back to my requirements yesterday:

  1. It must be automatic.
  2. It must be free.
  3. The process must not affect my life or computer use. 

Now that I have If This Then That set up, this shouldn’t be too hard. I want the system to automatically copy a picture to Dropbox each time I add one to my site.

There are three things I’ll need to do to achieve this:

  1. Write a script to recursively list all the files in my site
  2. Turn this into an RSS Feed
  3. Set up an IFTT script to import the contents on this RSS Feed into DropBox

My web server runs PHP so I’ll need to get my PHP thinking cap on.

PHP was one of the first server side scripting languages I learnt. But I haven’t touched it for a while now, and going back to it, it feels really weird.

Why, for example is, the command to replace elements of a string str_replace() rather than, say, replace()? It’s like they’re trying to make this harder!

It’s strange because PHP is considered an easy hackers language, but playing around with it now, after using vb, it feels a bit clumsy.

Anyway, once I’d reminded myself of the syntax, I put together the script.

The first bit was the command to recursively list a directory. Now, there is a PHP class for recursively listing directories, but because of my server setup I couldn’t use that.

So I had to write my own (with a bit of help from the Internet).

function getDirectory($path = ‘.’,$URL)
{

// Directories to ignore when listing output
$ignore = array(‘.’, ‘..’);

// Open the directory
$dh = @opendir($path);

// Loop through the directory
while(false !== ($file=readdir($dh)))
{

// Check that this file is not to be ignored
if( !in_array( $file, $ignore ) )
{

   // If it’s a directory iterate over that
   if( is_dir( “$path/$file” ) )
   { getDirectory(“$path/$file”,$URL);}

   // If it’s a file print out it’s name.
   elseif (strpos($file,”.php”) === FALSE)
   { echo $URL.$filename; }

}

}

// Close the directory handle
closedir( $dh );

}

 One of the key bits is this:

$ignore = array(‘.’, ‘..’);

if( !in_array( $file, $ignore ) )

I’ve looked into listing directories before, but had problems with the “.” and “..”. This neat checks solves that.

The other thing I had to do was produce the full URL so DropBox can download files:

$URL =’http://’.$_SERVER[“SERVER_NAME”].$_SERVER[“REQUEST_URI”];
$URL = substr($URL,0,strrpos($URL, “/”));

This gets the address of the file running, and then trims off the filename. It was the easiest way I could find of doing it.

The next stage was to create an RSS Feed:

//Send headers to Browser

header(“Content-Type: application/rss+xml”);

//Current Date in Correct Format

$now = date(“r”);

// Output beginning to RSS Feed
echo “

Backup File feed
http://www.imagedissectors.com/downloads/tumblr/index.php
Backup Feed
$now
$now

  ITEM TITLE
  URL TO ITEM
  GUIDE
  DATE PUBLISHED
”;

Once this was written, configuring ITTT was easy.

IFTTT Appearence

IFTTT seems to cache the feed and then compare it to it’s cached version to work out what’s a “new feed item”. This confused me at first, but now it means I don’t have to mess around with dates.

It also seems to have a cap of 29 items in one transaction. Again, this threw me at first, but all it means is that I needed to do an initial backup of everything, and then IFTTT does incremental backups from now on.

Part 2 of my backup strategy is complete.

Tag Cloud