Archive for ‘PHP’

23/01/2016

Laravel vs. AngularJS

I have been spending some time keeping my PHP skills sharp, and have been dabbling with rewriting/updating a front end for my personal home-hosted websites.

I started off with Laravel, and was pleasantly surprised with how quick and easy it was to get off up and running  (manipulating data with CRUD), thanks to the excellent docs, and my forays into PHP MVC stuff (the yii framework) in the past.

Part way through however, I chanced upon this youtube video, and such was the simplicity demonstrated in the examples, I was inspired to go knock together a quick proof of concept.

After one PHP script (less than 50 lines) to spit out all the data I wanted as json, I had a tabulated data viewer with powerful live filtering.

Next on my list is to evaluate how easy it is to implement the search/filtering with the Laravel side, and compare my options for implementing a CRUD system on the single page AngularJS site.

An interesting exercise – I don’t feel like my time has been wasted by doubling up on the work.

Advertisements
17/06/2013

Display your Twitter feed from a website

I have put up several posts on how to display recent Tweets in a webpage with PHP. However, Twitter has switched to it’s API v1.1 from today, so all of my previous articles have become obsolete. The easiest thing to do is to use Twitters own widget: https://twitter.com/settings/widgets. If you log in with your Twitter account, there is a simple wizard that generates some html that can be pasted directly into your webpage.

25/04/2013

Identify a (web) link in a string with PHP

If you want to process some text and output the same text with HTML links automatically created for you, then look no further:

$newstring = preg_replace('!(http|ftp|scp)(s)?:\/\/[a-zA-Z0-9.?&_/]+!', "<a href=\"\\" target='_blank'>\</a>",$sting);

Tags:
20/02/2013

Displaying your latest Tweet in PHP – updated

Back in 2011 I posted a method for displaying your latest tweet in php. However times change, and the twitter API has been changed beyond all recognition. I have updated my script to interpret the JSON response from the latest iteration of the API:

$username = "cytedesign";
$feed = "https://api.twitter.com/1/statuses/user_timeline/" . $username . ".json?count=1&include_rts=1&callback=?";

function parse_feed($feed) {
$stepOne = explode('"text":"', $feed);
$stepTwo = explode('","source"', $stepOne[1]);
$tweet = $stepTwo[0];
$tweet = htmlspecialchars_decode($tweet,ENT_QUOTES);
$tweet = str_replace("\/", "/", $tweet);
return $tweet;
}

$twitterFeed = file_get_contents($feed);
echo('&quot;'.parse_feed($twitterFeed).'&quot;');

I have been very busy with a brand new job that has been keeping me very busy, with more of a focus on developing desktop applications. I intend to start blogging a little again here as I get more comfortable with my new job.

Tags: , ,
25/06/2011

More mobile browser detection testing

My standard method of mobile browser detection as detailed in my previous post here involves the PHP function preg_match(). Unfortunately for me, having compiled a stripped down version PHP to run on ARM linux, the preg_match() function was not included (probably because I used the disable-all switch during compilation).

Anyhow I was quite quickly able to come up with a workaround using strpos():

//Read the user agent string, and convert to lowercase
$useragent=strtolower($_SERVER['HTTP_USER_AGENT']);


//Array of mobile browsers
$mobile_browser=array('android','avantgo','blackberry','blazer','compal','elaine','fennec','hiptop','iemobile','iphone','ipod','iris','kindle','lge ','maemo','midp','mmp','opera mobi','opera mini','palm os','phone','pixi','pre','plucker','pocket','psp','symbian','treo','vodafone','wap','windows ce','windows phone','xda','xiino/i');


//initialise counter
$i=0;


//iterate thorough array
foreach($mobile_browser as $val) {
$pos = strpos($useragent, $val);
//if the array element is not in the user agent string, do nothing
if($pos === false) {
}
//else increment the counter
else {
$i++;
}
}
if ($i == 0) {
echo "Load normal site";
}
else {
echo "Load mobile site";
}

I also found a great way to test all mobile browsers, using the user agent switcher for Firefox.

02/05/2011

Using PHP to calculate a simple checksum

There is a very specific set of rules for sending a message in most protocols, and the checksum is sent at the end of a message to make sure no corruption has occurred in transmission.

In the instance of sending a card number to the access control application I have been using PHP to integrate with in an ongoing project, the following was laid down with the protocol:

“The end of a message is made up of the checksum of the message (hex byte), created by XORing all the ASCII values together of all the characters of the message up to this point, not including the checksum itself.”

The code I wrote uses the XOR (^) operator a lot, and evaluates equations inside a string value, which I’ve never had to do before. Also as the message must be sent in hex format, I’ve used the dechex() function to convert decimal values. I have endeavoured to comment the code as fully as possible:

//Get card data from previous page
$card = $_GET['card'];
$part3 = $card;
echo "Card number: $card";
//The first part of the message 0030 session, 0D addcard (13)
$message = '00300D';
$part2 = $message;
//Add the card string
$message .= $card;
//Add the rest of the message
$part4 = '00030000000001000000000000';
$message .= '00030000000001000000000000';
echo "Message before assembly: $message";
//Determine the total length of the message, + the >, hex byte length,
//ASCII null character and hex byte checksum
$length = (strlen($message))+6;
echo "Decimal data length: $length";
//Convert the value to hex
$length = dechex ( $length );
//Convert lowercase hex letters to uppercase so the XOR checksum calculations are correct.
//First inialise $caps_length variable
$caps_length = '';
//Iterate through each of the length value, replaceing lowercase letters with uppercase
for ($i = 0, $j = strlen($length); $i < $j; $i++) {
if ('0' == $length[$i]) {$caps_length .='0';}
elseif ('1' == $length[$i]) {$caps_length .='1';}
elseif ('2' == $length[$i]) {$caps_length .='2';}
elseif ('3' == $length[$i]) {$caps_length .='3';}
elseif ('4' == $length[$i]) {$caps_length .='4';}
elseif ('5' == $length[$i]) {$caps_length .='5';}
elseif ('6' == $length[$i]) {$caps_length .='6';}
elseif ('7' == $length[$i]) {$caps_length .='7';}
elseif ('8' == $length[$i]) {$caps_length .='8';}
elseif ('9' == $length[$i]) {$caps_length .='9';}
elseif ('a' == $length[$i]) {$caps_length .='A';}
elseif ('b' == $length[$i]) {$caps_length .='B';}
elseif ('c' == $length[$i]) {$caps_length .='C';}
elseif ('d' == $length[$i]) {$caps_length .='D';}
elseif ('e' == $length[$i]) {$caps_length .='E';}
elseif ('f' == $length[$i]) {$caps_length .='F';}
}
echo "Hex data length: $caps_length";
//Assemble the string to be sent (note the ASCII null character will not
//affect the checksum calculation so is not included here)
$string = '>';
$string .= $caps_length;
$part1 = $string;
$string .= $message;
echo "Assembled Message: $string";
//Calculate the checksum
//First initialise the variables
$x = 0;
$conversion = '';
//Iterate through each character of the string to convert it to its
//ASCII equivalent, with the ^ to XOR with the next value
for ($i = 0, $j = strlen($string); $i < $j; $i++) {
if ('0' == $string[$i]) {$conversion .='48^';}
elseif ('1' == $string[$i]) {$conversion .='49^';}
elseif ('2' == $string[$i]) {$conversion .='50^';}
elseif ('3' == $string[$i]) {$conversion .='51^';}
elseif ('4' == $string[$i]) {$conversion .='52^';}
elseif ('5' == $string[$i]) {$conversion .='53^';}
elseif ('6' == $string[$i]) {$conversion .='54^';}
elseif ('7' == $string[$i]) {$conversion .='55^';}
elseif ('8' == $string[$i]) {$conversion .='56^';}
elseif ('9' == $string[$i]) {$conversion .='57^';}
elseif ('>' == $string[$i]) {$conversion .='62^';}
elseif ('A' == $string[$i]) {$conversion .='65^';}
elseif ('B' == $string[$i]) {$conversion .='66^';}
elseif ('C' == $string[$i]) {$conversion .='67^';}
elseif ('D' == $string[$i]) {$conversion .='68^';}
elseif ('E' == $string[$i]) {$conversion .='69^';}
elseif ('F' == $string[$i]) {$conversion .='70^';}
}
//Add on an extra 0. Makes no difference to the final value, but in necessary
//so as not to end the expression with ^.
$conversion .='0';
eval("\$checksum = " . $conversion . ";");
$checksum = dechex ( $checksum );
//Convert lowercase hex letters to uppercase
$final_checksum = '';
for ($i = 0, $j = strlen($checksum); $i < $j; $i++) {
if ('0' == $checksum[$i]) {$final_checksum .='0';}
elseif ('1' == $checksum[$i]) {$final_checksum .='1';}
elseif ('2' == $checksum[$i]) {$final_checksum .='2';}
elseif ('3' == $checksum[$i]) {$final_checksum .='3';}
elseif ('4' == $checksum[$i]) {$final_checksum .='4';}
elseif ('5' == $checksum[$i]) {$final_checksum .='5';}
elseif ('6' == $checksum[$i]) {$final_checksum .='6';}
elseif ('7' == $checksum[$i]) {$final_checksum .='7';}
elseif ('8' == $checksum[$i]) {$final_checksum .='8';}
elseif ('9' == $checksum[$i]) {$final_checksum .='9';}
elseif ('a' == $checksum[$i]) {$final_checksum .='A';}
elseif ('b' == $checksum[$i]) {$final_checksum .='B';}
elseif ('c' == $checksum[$i]) {$final_checksum .='C';}
elseif ('d' == $checksum[$i]) {$final_checksum .='D';}
elseif ('e' == $checksum[$i]) {$final_checksum .='E';}
elseif ('f' == $checksum[$i]) {$final_checksum .='F';}
}
echo "Calculation Performed: $conversion";
//Add an if statement in case the checksum is only
//one character Eg. to make 8 into 08 or A into 0A
if (strlen($final_checksum)==1) {
$new_final_checksum = '0';
$new_final_checksum .= $final_checksum;
$final_checksum = $new_final_checksum;
}
echo "Checksum: $final_checksum";
//The final string to be sent to the controller must now be assembled and sent:
$string .=$final_checksum;
$part5 = $final_checksum;
$final_string = $part1 . $part2 . $part3 . chr(0) . $part4 . $part5;
echo "Send this to controller: $final_string";

Sample output from this code:

Card number: 15198392
Message before assembly: 00300D1519839200030000000001000000000000
Decimal data length: 46
Hex data length: 2E
Assembled Message: >2E00300D1519839200030000000001000000000000
Calculation Performed: 62^50^69^48^48^51^48^48^68^49^53^49^57^56^51^57^50^48^48^48^51^
48^48^48^48^48^48^48^48^48^49^48^48^48^48^48^48^48^48^48^48^48^48^0
Checksum: 30
Send this to controller: >2E00300D151983920003000000000100000000000030

I’ve not included all details of the actual message here. If anybody reading this wants clarification or more information, please let me know.

Tags: , ,
30/04/2011

Sending data to a specific port using PHP

I have made a bit of a breakthrough on my back-burner project at work, last mentioned here on 2010 in a post on SQLite connections.

As mentioned in that post there is a door control application that runs on a mini linux PC which my web application manipulates through its SQLite database. The door control application is designed to work with a PC application, and listens to messages from the PC on port 5556. (Apologies for my over-use of the word “application” in this paragraph).

While idly researching the possibility of sending data to port 5556 from a PHP page I found a wonderful explanatory article on devshed.com by the brilliantly named “icarus, (c) Melonfire” entitled “Socket programming with PHP“. With this new-found knowledge at my disposal I was quickly able to start speaking directly to the door control application using a few lines of PHP:

//Don't timeout
set_time_limit(0);

//Socket connection info
$host="10.0.1.230";
$port = 5556;

// open a client connection
$fp = fsockopen ($host, $port, $errno, $errstr);
if (!$fp)
{
$result = "Error: could not open socket connection";
}
echo "Logon Command Sent
";
$message = ">1D003003000001000107D0119435";
$message .= chr(13);
// write the string contained in $message to the socket
fputs ($fp, $message);
sleep(1);
// get the result
//$result = fgets ($fp, 64);
//echo "The controller says: $result";

echo "Keepalive message sent";
$message1 = ">0B00300748";
$message1 .= chr(13);
fputs ($fp, $message1);
sleep(1);
//$result1 = fgets ($fp, 64);
//echo "The controller says: $result1";

echo "Sending card data";
$message2 = ">2E00300D15198392";
$message2 .= chr(0);
$message2 .= "0003000000000100000000000030";
$message2 .= chr(13);
fputs ($fp, $message2);
sleep(1);
//$result2 = fgets ($fp, 64);
//echo "The controller says: $result2";

// close the connection
fclose ($fp);

This code sends a few basic commands and waits for the responses, printing them in html.

This led on to what I am currently working on with regards to this project: generating a checksum in PHP. Separate blog post on that to follow.

Tags: ,
17/03/2011

PHP/MySQL dates

I have posted before as to a MySQL date, i.e. Y-m-d can be converted in a previous post here.

I found myself this evening in need of converting UK dates back into the MySQL format.

Now, the strtotime() function requires a MySQL-style date going in, so doesn’t work in the way I needed it to tonight.

Luckily I found the ukstrtotime() function online, which works great:

function ukstrtotime($str) {
return strtotime(preg_replace("/^([0-9]{1,2})[\/\. -]+([0-9]{1,2})[\/\. -]+([0-9]{1,4})/", "\\2/\\1/\\3", $str));
}

This is then used in the following way:

$mysqldate = date('Y-m-d',ukstrtotime($ukdate));

Tags: , , ,
07/03/2011

Display your latest Tweet in PHP

So on my mobile site (http://cyte.co.uk/mobile) I created a button to link to my Twitter and this very blog you are reading. This got me thinking what I could do to keep the content fresh without much effort. As the mobile site only consists of a couple of lines of text anyway, I thought a “Latest Tweet” section would be good – because it would be ever-changing. After a bit of googling I tweaked a few bits of PHP I found to come up with the following:

<?php
$username = "cytedesign";
$feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=1";

function parse_feed($feed) {
    $stepOne = explode("", $feed);
    $stepTwo = explode("", $stepOne[1]);
    $tweet = $stepTwo[0];
	$tweet = htmlspecialchars_decode($tweet,ENT_QUOTES);
    return $tweet;
}

$twitterFeed = file_get_contents($feed);
echo('"'.parse_feed($twitterFeed).'"');
?>

I was so pleased with this in fact that I will use it on the full version of the site as well, and file it away for my employers’ website when we start company Tweeting.

Tags: ,
02/03/2011

Make your website mobile friendly

With an ever-growing percentage of people with access to mobile web browsers in their pockets, the time is ripe to take steps to optimise your site for mobile users.

I’ll be posting as I go through getting my own site (cyte.co.uk) mobile-ready. The first step is detecting whether your user is viewing your site in a mobile browser.

I accomplished this in just a few minutes with open source php code from detectmobilebrowser.com.

Be careful here. My hosting company want to charge me £3.99 per month for a mobile site, and I also found a few downloadable scripts that wanted payment for commercial use. Right.