Posts tagged ‘PHP’

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

Advertisements
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: , ,
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.

24/11/2010

Converting stored MySQL dates into UK format

You will no doubt be aware that when you save a date in a MySQL database, it must be in the form of Y-m-d.

I had some difficulty wrestling with the date() section of the PHP manual , and experimented for a few minutes on trying the use the SQL SELECT statement itself to get the date data from the database in my preferred UK (d/m/Y) format without sucess.

I was quite pleased therefore when my perseverance paid off, and I was able to work out how to solve my problem with a single line of PHP code:

$ukdate = date('d/m/Y',strtotime($mysqldate));

Tags: , ,
20/11/2010

PHP pagination of search results

Displaying data from a database in a webpage is something every web developer needs to do very frequently. I remember my early attempts at displaying a certain number of records per page like a Google search to be immensely frustrating and difficult to get working.

So this is an instructional example I’ve put together,  which is a mishmash of various example scripts I’ve found over the years, and butchered, adapted and refined to fill my requirements. Feel free to use it, or parts of it to help you:

<?php
//Get the page number (if the search has already been done) and the users input from the search form (q)
 $pagenum = @$_GET['pagenum'];
 
$var = @$_GET['q'];

//Slight protection from sql injection

$trimmed = trim($var);

 

if ($trimmed=="")
{
echo "You didn't enter anything to search.";
exit();
}
// Connect to your Database
mysql_connect("localhost", "dbname", "dbpass") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());
//This checks to see if there is a page number. If not, it will set it to page 1
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
//Edit $data to be your query
$data = mysql_query("SELECT * FROM dbtable WHERE value1 LIKE '%$trimmed%' || value2 LIKE '%$trimmed%' ORDER BY value1") or die(mysql_error());
$rows = mysql_num_rows($data);
//If no rows are returned, tell the user
if ($rows==0)
{
echo "Sorry, your search: &quot;" . $trimmed . "&quot; returned no results";
exit();}
//This is the number of results displayed per page
$page_rows = 8;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//This makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
//This is your query again, the same one... the only difference is we add $max into it
$data_p = mysql_query("SELECT * FROM dbtable WHERE value1 LIKE '%$trimmed%' || value2 LIKE '%$trimmed%' ORDER BY value1 $max") or die(mysql_error());
echo "<td align='center'>";
// This shows the user what page they are on, and the total number of pages
echo "$pagenum of $last<br />";
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we put in our "faded" buttons, (no links). If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
echo "<img src='../resources/fadefirst.jpg' width='50' alt='First' /><img src='../resources/fadeprevious.jpg' width='50' alt='Previous' />";
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1&dvalue=$dvalue&q=$trimmed'><img src='../resources/first.jpg' width='50' alt='First' title='First' /></a> ";
echo " ";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous&dvalue=$dvalue&q=$trimmed'><img src='../resources/previous.jpg' width='50' alt='Previous' title='Previous' /></a> ";
}
//just a spacer
echo "&nbsp;&nbsp;&nbsp;";
//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last)
{
echo "<img src='../resources/fadenext.jpg' width='50' alt='Next' /><img src='../resources/fadelast.jpg' width='50' alt='Last' />";
}
else {
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next&dvalue=$dvalue&q=$trimmed'><img src='../resources/next.jpg' width='50' alt='Next' title='Next' /></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last&dvalue=$dvalue&q=$trimmed'><img src='../resources/last.jpg' width='50' alt='Last' title='Last' /></a> ";
}
//Set up the headers of the table to display your query results
echo "</td></tr></table></div>
<div><table border='1' width='100%'>
<tr align='center'>
<th width='20%'>Image</th>
<th width='20%'>Item1</th>
<th width='20%'>Item2</th>
<th width='20%'>Item3</th>
<th width='20%'>Item4</th>
</tr>";
//This is where you display your query results
while($info = mysql_fetch_array( $data_p ))
{
$image=$info['image'];
$v1=$info['value1'];
$v2=$info['value2'];
$v3=$info['value3'];
$v4=$info['value4'];
echo "<tr align='center'>";
echo "<td width='20%'> <img src ='$image'> </td>";
echo "<td width='20%'> $v1 </td>";
echo "<td width='20%'> $v2 </td>";
echo "<td width='20%'> $v3 </td>";
echo "<td width='20%'> $v4 </td>";
echo "</tr>";
}
echo "</table>";
// Same Paigation display as earlier - so the user has next/previous/first/last page navigation above and below the table of search results on each page
echo "<div align='center'>";
if ($pagenum == 1)
{
echo "<img src='../resources/fadefirst.jpg' width='50' alt='First' /><img src='../resources/fadeprevious.jpg' width='50' alt='Previous' />";
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1&q=$trimmed'><img src='../resources/first.jpg' width='50' alt='First' title='First' /></a> ";
echo " ";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous&q=$trimmed'><img src='../resources/previous.jpg' width='50' alt='Previous' title='Previous' /></a> ";
}
echo "&nbsp;&nbsp;&nbsp;";
if ($pagenum == $last)
{
echo "<img src='../resources/fadenext.jpg' width='50' alt='Next' /><img src='../resources/fadelast.jpg' width='50' alt='Last' />";
}
else {
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next&q=$trimmed'><img src='../resources/next.jpg' width='50' alt='Next' title='Next' /></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last&q=$trimmed'><img src='../resources/last.jpg' width='50' alt='Last' title='Last' /></a> ";
}
echo "<br />$pagenum of $last</div>";
?>

 

Tags: ,
14/11/2010

PDO/SQLite connection

I have been working for a while on a project involving running a PHP web application on on an ARM linux mini PC. There was an existing application on the PC whose SQLite database I needed to manipulate, to feed new values into the program from a web interface. The hardest thing by far was cross-compiling PHP to run in the ARM environment to include --enable-pdo --with-pdo-sqlite, but that would take too long to go into here.

I was able to collect and display data from the SQLite database using the following PHP code:

$connect = new PDO("sqlite:/path/to/sqlite.db");

$sql = "SELECT * FROM sqlite_table";

foreach ($connect->query($sql) as $info)
{
$val1=$info['val1'];

$val2=$info['val2'];
}

echo "$val1";

Tags: , , ,