• Skip to main content

Uly.me

cloud engineer

  • Home
  • About
  • Archives

Archives for February 2014

SimplePie RSS Reader

February 27, 2014

If you’re thinking about adding syndication to your website, consider using SimplePie, a super fast and easy-to-use feed parser written in PHP. With SimplePie, adding a RSS feed to your site couldn’t be more easier. In this article, I will show you how to create a RSS page that will display a feed. It will display my blog’s RSS feed as default when nothing is clicked. I’ve included a couple of links that are clickable. When the links are clicked, the RSS feed for that link will be displayed.

First, download SimplePie.

Next, we need to create a file and copy the code below. The code is pretty much self-explanatory.

<?php 
// include SimplePie
require_once('php/autoloader.php');
 
// Create a new object called $feed
$feed = new SimplePie();
 
// Set the default to my blog's RSS at first run
if ($_GET[feed] == "") { $_GET[feed]="http://uly.me/feed/"; }
$feed->set_feed_url($_GET[feed]);
 
// Run SimplePie.
$feed->init();
 
// Send the result to show up on the browser
$feed->handle_content_type();
?>
 
<!-- Display the links -->
<a href="rssfeed.php?feed=http://news.yahoo.com/rss">Yahoo News</a> | 
<a href="rssfeed.php?feed=http://feeds.reuters.com/reuters/topNews">Reuter News</a>
 
<!-- Display the header -->
<div class="header">
  <h1><a href="<?php echo $feed->get_permalink(); ?>"><?php echo $feed->get_title(); ?></a></h1>
  <p><?php echo $feed->get_description(); ?></p>
</div>
 
<?php
// Display the feed inside a loop
foreach ($feed->get_items() as $item): ?>
<div class="item">
<li><a href="<?php echo $item->get_permalink(); ?>" target="_blank"><?php echo $item->get_title(); ?></a></li>
  <p><?php echo $item->get_description(); ?></p>
  <p><small>Posted on <?php echo $item->get_date('j F Y | g:i a'); ?></small></p>
</div>
<?php 
endforeach;
 
/* end of file */

<?php // include SimplePie require_once('php/autoloader.php'); // Create a new object called $feed $feed = new SimplePie(); // Set the default to my blog's RSS at first run if ($_GET[feed] == "") { $_GET[feed]="http://uly.me/feed/"; } $feed->set_feed_url($_GET[feed]); // Run SimplePie. $feed->init(); // Send the result to show up on the browser $feed->handle_content_type(); ?> <!-- Display the links --> <a href="rssfeed.php?feed=http://news.yahoo.com/rss">Yahoo News</a> | <a href="rssfeed.php?feed=http://feeds.reuters.com/reuters/topNews">Reuter News</a> <!-- Display the header --> <div class="header"> <h1><a href="<?php echo $feed->get_permalink(); ?>"><?php echo $feed->get_title(); ?></a></h1> <p><?php echo $feed->get_description(); ?></p> </div> <?php // Display the feed inside a loop foreach ($feed->get_items() as $item): ?> <div class="item"> <li><a href="<?php echo $item->get_permalink(); ?>" target="_blank"><?php echo $item->get_title(); ?></a></li> <p><?php echo $item->get_description(); ?></p> <p><small>Posted on <?php echo $item->get_date('j F Y | g:i a'); ?></small></p> </div> <?php endforeach; /* end of file */

See the demo. Just add your own CSS stylesheet and you’re ready to go.

Filed Under: PHP Tagged With: feed, rss, simplepie

Calculating Dates in PHP

February 26, 2014

Calculating and formatting dates is an important function when writing software applications. You might be needing to perform a database search of all transactions a month ago, six months ago, etc. To make this all possible, you need to be able to figure out how to calculate dates based from today’s date. PHP has a couple of date functions called date() and mktime(). I use the date() function primarily for formatting dates, and mktime() function for calculating dates since mktime() is the actual Unix timestamp. With these two functions, you can do some pretty amazing date calculations.

Let’s get started.

// Today's date
$day   = date("d");
$month = date("m");
$year  = date("Y");
 
// Using mktime calculate past dates
$start_of_three_months_ago = mktime(0, 0, 0, date("m")-2, 1, date("Y"));
$end_of_three_months_ago   = mktime(23, 59, 59, date("m")-1, 0, date("Y"));
 
// Using mktime to calculate future dates
$start_of_three_months_from_now = mktime(0, 0, 0, date("m")+3, 1, date("Y"));
$end_of_three_months_from_now   = mktime(23, 59, 59, date("m")+4, 0, date("Y"));
 
// Formatting dates to 'month day, year' format.
$a = date("M j, Y", $start_of_three_months_ago);
$b = date("M j, Y", $end_of_three_months_ago);
$c = date("M j, Y", $start_of_three_months_from_now);
$d = date("M j, Y", $end_of_three_months_from_now);
 
// results are based on today's date 
echo $day;
// results in 26
echo $month;
// results in 02
echo $year;
// results in 2014
echo $a;
// results in Dec 1, 2013
echo $b;
// results in Dec 31, 2014
echo $c;
// results in May 1, 2014
echo $d;
// results in May 31, 2014

// Today's date $day = date("d"); $month = date("m"); $year = date("Y"); // Using mktime calculate past dates $start_of_three_months_ago = mktime(0, 0, 0, date("m")-2, 1, date("Y")); $end_of_three_months_ago = mktime(23, 59, 59, date("m")-1, 0, date("Y")); // Using mktime to calculate future dates $start_of_three_months_from_now = mktime(0, 0, 0, date("m")+3, 1, date("Y")); $end_of_three_months_from_now = mktime(23, 59, 59, date("m")+4, 0, date("Y")); // Formatting dates to 'month day, year' format. $a = date("M j, Y", $start_of_three_months_ago); $b = date("M j, Y", $end_of_three_months_ago); $c = date("M j, Y", $start_of_three_months_from_now); $d = date("M j, Y", $end_of_three_months_from_now); // results are based on today's date echo $day; // results in 26 echo $month; // results in 02 echo $year; // results in 2014 echo $a; // results in Dec 1, 2013 echo $b; // results in Dec 31, 2014 echo $c; // results in May 1, 2014 echo $d; // results in May 31, 2014

You can then use any set of dates to calculate transactions on the database. For example.

SELECT price FROM product WHERE purchase_date BETWEEN $a AND $b;

SELECT price FROM product WHERE purchase_date BETWEEN $a AND $b;

Read more about PHP’s date and mktime functions. See demo. Results are based on today’s date.

Filed Under: PHP Tagged With: date, mktime

The Latest Speed Test

February 25, 2014

I recently switched to Comcast for my Internet services. It has been several years since I have left and abandoned Comcast. I was curious more than anything as to what kind of download speeds I’ll be getting now that I’m back to using broadband cable. The result is pretty impressive. It has been a while since I’ve seen this kind of speeds at home. It’s about 4-5 times faster than what I previously had. I ran 3 different speed tests from 3 different sources. I’m a little surprised the results were similar. All fell within the same range of one another. So, without much further ado, here are the results of the speed tests.

Comcast Speed Test

speedtest

Speakeasy

speakeasy

Speedtest

speedtest-net

Filed Under: Misc Tagged With: comcast, speedtest

URL Spaces in CodeIgniter

February 19, 2014

I ran into some issues with a piece of code I wrote several years ago in CodeIgniter. I’m using names of people as part of the URL. When someone enters a name with spaces on the database, the spaces are converted to %20 in the resulting URL. The URL doesn’t look pretty and definitely not SEO friendly. It needs to be cleaned up by replacing spaces with either a dash or an underscore.

The other issue is when performing a search, the database doesn’t really know that ‘John Doe’ is essentially the same as ‘John%20Doe.’ So, I ended up using a CodeIgniter function called url_title. The function strips the spaces and replaces it with a dash or a hyphen. In the case of ‘John%20Doe’, it now displays as ‘John-Doe.’ You can also use an underscore. See example below.

Replace %20 with dash or hypen

$name = 'John Doe';
$url = url_title($name);
// produces 'John-Doe'
 
$name = 'John Doe';
$url = url_title($name, '_');
// produces 'John_Doe'

$name = 'John Doe'; $url = url_title($name); // produces 'John-Doe' $name = 'John Doe'; $url = url_title($name, '_'); // produces 'John_Doe'

Put the space before the search

Before performing a search, I use str_replace to remove the dash and put back the space so it matches the database entry. It’s essentially the reverse of what I did to display a friendly URL.

$url = 'John-Doe';
$name = str_replace('-', ' ', $url);
// perform your search function here

$url = 'John-Doe'; $name = str_replace('-', ' ', $url); // perform your search function here

If you’re not familiar with CodeIgniter, check how URI routing and url_title are handled.

Filed Under: PHP Tagged With: codeigniter, str_replace, url, url_title

Importing SQL in phpMyAdmin

February 18, 2014

If you have a problem importing SQL files into phpMyAdmin, the issue could be that the upload limit in PHP is set too low. By default, PHP sets the upload file limit to 2MB, which is too low for most people. You can increase the limit to something more realistic such as 16MB, if you’re working mostly with medium-sized SQL databases.

If you have access to the Terminal and have root access, you can edit your PHP.ini settings. First, you need to find out where your default PHP.ini is located. There might be several PHP.ini files in your system, but there’s only one bound to Apache. To determine to which one is being used, I suggest you create a file that contains the PHP function called phpinfo(). Place this file your web server and run it.

Create a file called phpinfo.php. Enter the code below. Save. Upload to server.

<?php phpinfo(); ?>

<?php phpinfo(); ?>

Now, open your browser and point the URL where your phpinfo.php is stored on your web server. The phpinfo.php file will run the phpinfo() function and will display the environment variables being used by Apache. Near the top of the page, you’ll see the path of the php.ini. Now that you know where your php.ini file is exactly located, you’ll need to edit that file and look for the Upload Limits.

In Ubuntu, my php.ini is located in /etc/php5/apache2/php.ini.

sudo nano /etc/php5/apache2/php.ini

sudo nano /etc/php5/apache2/php.ini

Look for the File Uploads text as displayed below. Change from 2M to 16M. Save file.

;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;
 
upload_max_filesize = 16M

;;;;;;;;;;;;;;;; ; File Uploads ; ;;;;;;;;;;;;;;;; upload_max_filesize = 16M

Finally, you need to reboot Apache for your changes take effect.

sudo /etc/init.d/apache restart

sudo /etc/init.d/apache restart

Filed Under: PHP Tagged With: phpmyadmin, sql, upload

List Directories Using Glob

February 15, 2014

If there’s a need for you to list directories on the server, there’s a PHP function called Glob which will find pathnames to match a certain pattern. To make glob read only directories on the server, we can specify in the glob function with the GLOB_ONLYDIR option which will return only directories and ignore files. The asterisk means it will accept any pattern.

glob('*', GLOB_ONLYDIR);

glob('*', GLOB_ONLYDIR);

In the example below, we will specify any directory by assigning an empty or a blank to the $dir variable. We will then use the foreach loop to display all directories found. If we have WordPress installed, we can ignore the WordPress directories by searching for them in the if statement. We will finally echo and print to the screen each individual directory found by our glob function.

Here’s the entire script with HTML included.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Glob - list directories</title>
  <style>
    li { list-style-type:none; margin-left:-15px; }
  </style>
</head>
<body>
<h1>List directories using Glob</h1>
<ul>
<?php
// set to current directory 
$dir = '';
// directories only. ignore files, etc.
foreach(glob($dir.'*', GLOB_ONLYDIR) as $folder){ 
  // do not include wordpress directories
  if (($folder != 'wp-admin') && ($folder != 'wp-content') && ($folder != 'wp-includes')) { 
    // list directories and their links
    ?> 
    <li><a href="<?php echo $dir."/".$folder;?>"><?php echo $folder;?></li> 
    <?php 
  }
} 
?>
</ul>
</body>
</html>

<!DOCTYPE html> <html lang="en"> <head> <title>Glob - list directories</title> <style> li { list-style-type:none; margin-left:-15px; } </style> </head> <body> <h1>List directories using Glob</h1> <ul> <?php // set to current directory $dir = ''; // directories only. ignore files, etc. foreach(glob($dir.'*', GLOB_ONLYDIR) as $folder){ // do not include wordpress directories if (($folder != 'wp-admin') && ($folder != 'wp-content') && ($folder != 'wp-includes')) { // list directories and their links ?> <li><a href="<?php echo $dir."/".$folder;?>"><?php echo $folder;?></li> <?php } } ?> </ul> </body> </html>

Filed Under: PHP Tagged With: directories, folders, glob

Fighting Spam With Akismet

February 6, 2014

Akismet is a web service that detects spam. Akismet was originally created by Automattic, the company behind WordPress, to filter out spam comments on its own blogs. The use of Akismet has spread to other blogs and CMS engines. Akismet can also be implemented on other websites. There are a number of plugins and libraries available. Akismit also has an API.

Akismet is open-source and free for personal use. Akismet offers professional and enterprise plans for a modest fee. To start using Akismet on your website, you first need an Akismet key which you can get from WordPress.com. Just register. A key will be automatically generated for you. In addition, you also need to download the Akismet class library which you’ll need to include in your web projects.

How to use Akismet

In this example, we will use Akismet’s PHP class library. Download. So, let’s assume you have a comment form or a contact page on your website. When your form is submitted, Akismet will check if the comment is spam or not. The API accesses the Akismet servers and it will return either a yes or a no. Simple enough. How Akismet filters out the spam is not known. They say it’s in the “secret sauce.”

Our HTML Form

We will keep our form simple. We will use the post method. Our form will call itself after submission. We are taking the proper precautions to avoid cross-site scripting attacks, etc. by using the htmlspecialchars function and the $_SERVER[“PHP_SELF”] variable itself.

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" />
Email: <input type="text" name="email" />
URL: <input type="text" name="url" />
Comment: <textarea name="comment" rows="5" cols="80"></textarea>
<input type="submit" name="submit" value="Submit">
</form>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text" name="name" /> Email: <input type="text" name="email" /> URL: <input type="text" name="url" /> Comment: <textarea name="comment" rows="5" cols="80"></textarea> <input type="submit" name="submit" value="Submit"> </form>

Our PHP Code

This is the PHP code that we can place at top of our page. The code will start a new session. It will check if the form is submitted. We will then create a new Akismet object and check if our comment data is spam or not. The Akismet class will contact the Akismet servers. It will determine if our comment is spam or not. If it is, it will mark it as spam. We can either ignore it or save it to the database. If it’s a good comment, we definitely need to keep it and mark it as good comment.

<?php
// start a new session
session_start();
 
// our submitted values are sanitized
$author = addslashes(htmlspecialchars(strip_tags(trim($_POST['name']))));
$email = addslashes(htmlspecialchars(strip_tags(trim($_POST['email']))));
$url = addslashes(htmlspecialchars(strip_tags(trim($_POST['url']))));
$comment = addslashes(htmlspecialchars(strip_tags(trim($_POST['comment']))));
 
// Load array with comment data.
$data = array(
  'author' => $author,
  'email' => $email,
  'website' => 'http://www.yourdomain.com/',
  'body' => $comment,
  'permalink' => 'http://www.yourdomain.com/path-to-your-comment-page',
);
 
// include Akismet class
include "akismet.class.php";
 
// check if the form was submitted
if(isset($_POST['submit'])) {
  // submitted
  // create a new object
  $akismet = new Akismet('http://www.yourdomain.com/', 'YOUR_WORDPRESS_API_KEY', $data);  
 
  if($akismet->errorsExist()) {
    echo "Oops! Problem connecting to the Akismet server!";
  } else {
    if($akismet->isSpam()) {
      echo "This is spam!";
      // mark comment as spam
      // option to either save to database or ignore
    } else {
      echo "This is good ham! Let's keep it!";
      // mark comment as good ham
      // definitely save the good comment to the database
    }
  }
}
?>

<?php // start a new session session_start(); // our submitted values are sanitized $author = addslashes(htmlspecialchars(strip_tags(trim($_POST['name'])))); $email = addslashes(htmlspecialchars(strip_tags(trim($_POST['email'])))); $url = addslashes(htmlspecialchars(strip_tags(trim($_POST['url'])))); $comment = addslashes(htmlspecialchars(strip_tags(trim($_POST['comment'])))); // Load array with comment data. $data = array( 'author' => $author, 'email' => $email, 'website' => 'http://www.yourdomain.com/', 'body' => $comment, 'permalink' => 'http://www.yourdomain.com/path-to-your-comment-page', ); // include Akismet class include "akismet.class.php"; // check if the form was submitted if(isset($_POST['submit'])) { // submitted // create a new object $akismet = new Akismet('http://www.yourdomain.com/', 'YOUR_WORDPRESS_API_KEY', $data); if($akismet->errorsExist()) { echo "Oops! Problem connecting to the Akismet server!"; } else { if($akismet->isSpam()) { echo "This is spam!"; // mark comment as spam // option to either save to database or ignore } else { echo "This is good ham! Let's keep it!"; // mark comment as good ham // definitely save the good comment to the database } } } ?>

Making a Correction

Occasionally, not very often, Akismet screws up, and marks a good comment as spam, and vice versa. We can tell Akismet, “Hey, what’s the matter! Please correct these comments!” We can correct Akismet by running these two methods.

// Submit as Ham
$akismet->submitHam();
 
// Submit as Spam
$akismet->submitSpam();

// Submit as Ham $akismet->submitHam(); // Submit as Spam $akismet->submitSpam();

That’s how how Akismet is implemented in a nutshell.

Filed Under: PHP Tagged With: akismet, protection, spam

Responsive Web Trends Conference

February 5, 2014

I just signed up for an all-day conference called Responsive Web Trends Conference in San Francisco. It’s a day-long event and it’s free as in beer. The event is on Wednesday, February 12, 2014 starting at 9am. Register.

Responsive Web Trends is a completely free, day-long conference for those who are passionate about creating websites that look great and work well on any device—even those that haven’t been invented yet.

The conference brings together forward-thinking industry influencers, designers and developers for a day of deep discussions and workshops. Presented by Moboom, the conference explores trends in responsive web design and adaptive technologies with the goal of creating an open dialogue about how designers and developers can work more efficiently and think beyond just mobile.

The speakers include Jason Grigsby, Greg Nudelman, and Ben Callahan.

The topics planned are:

  • A Developer’s Next Big Challenge
  • Dissecting Responsive Design
  • Lean Mobile-First UX
  • Scale Big with Docker
  • Multi-Lingual Coding
  • And more…

The event is sponsored by Moboom.

Filed Under: HTML Tagged With: design, responsive

  • Go to page 1
  • Go to page 2
  • Go to Next Page »
  • Home
  • About
  • Archives

Copyright © 2023