Lil Josh

A tech blog about web development with PHP, MySQL, jQuery, CSS3 and various other programming languages.

Resizing High Resolution (Hi-res) JPEG Images with PHP

October 13, 2014

I kept running into a problem when I uploaded high resolution (14MP) images and tried creating thumbnails with them. The issue turned out being the PHP script ran out of memory. So it was a simple increase to about a half gig (512MB) and the script ran perfectly. Here’s the code:

thumbnail.php?src=myImage.jpg&w=300

<?php
ini_set ( "memory_limit", "512M");
header('Content-Type:image/jpeg');
echo createThumb($_GET["src"],$_GET["w"]);


function createThumb( $path, $thumbWidth ) 
{
 
    $info = pathinfo($path);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'jpg' ) 
    {

      // load image and get image size
      $img = imagecreatefromjpeg( "{$path}" );
      $width = imagesx( $img );
      $height = imagesy( $img );

	 

      // calculate thumbnail size
      $new_width = $thumbWidth;
      $new_height = floor( $height * ( $thumbWidth / $width ) );

      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );

      // copy and resize old image into new image 
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
	  $exif = exif_read_data($_GET["src"]);
	  $orientation = $exif["Orientation"]; //6 for portrait and 1 for landscape
	  if($orientation == 6 && $width > $height) {
	  	$tmp_img = imagerotate($tmp_img, 270, 0);
	  }
      return imagejpeg($tmp_img);
  
  }
}
?>
hi-res high resolution images jpeg jpg PHP resize

New Twitter API (v1.1) Quick Start

October 10, 2014

This tutorial will help you get started with the new Twitter API which will be much different than the deprecated 1.0 version. In this example we’ll look at how to get a user’s timeline via the API.

  1. Setup your developer account if you haven’t done so yet at https://dev.twitter.com
  2. Go to https://apps.twitter.com/ and create your app
  3. Once created click on the Keys and Access Tokens tab and Create Access Tokens (for this example we only need Read access but for other applications you may want read and write)
  4. Copy and paste contents of TwitterAPIExchange.php
  5. Create a new PHP file that includes the TwitterAPI Exchange and uses your access tokens to GET requests from Twitter API:
    <?php
    require_once('TwitterAPIExchange.php');
    
    /** Set access tokens here - see: https://dev.twitter.com/apps/ **/
    $settings = array(
        'oauth_access_token' => "",
        'oauth_access_token_secret' => "",
        'consumer_key' => "",
        'consumer_secret' => "",
        'username' => 'jolamar',
        'count' => 2
    );
    
    $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
    $getfield = '?screen_name='.$settings["username"].'&count='.$settings["count"];
    $requestMethod = 'GET';
    $twitter = new TwitterAPIExchange($settings);
    $feed = json_decode($twitter->setGetfield($getfield)
                 ->buildOauth($url, $requestMethod)
                 ->performRequest(), true);
                 
    foreach($feed as $tweet) {
        
        // twitter variables
        $created = date("j M Y", strtotime($tweet["created_at"]));
        $id = $tweet["id"];
        $text = $tweet["text"];
        $username = $tweet["user"]["screen_name"];
        $name = $tweet["user"]["name"];
        $retweet_count = $tweet["retweet_count"];
        $favorite_count = $tweet["favorite_count"];
        $hashtags = $tweet["entities"]["hashtags"]; //array
        $mediaItems = $tweet["entities"]["media"]; //array
        
        echo "<div class='liljoshTweet'>
        <div class='liljoshName'><a href='https://twitter.com/$username'>$name</a></div><!-- /.liljoshName -->
        <div class='liljoshUsername'><a href='https://twitter.com/$username'>@$username</a></div><!-- /.liljoshUsername -->
        <div class='liljoshDivide'><a href='https://twitter.com/$username/status/$id'> · </a></div><!-- /.liljoshDivide -->
        <div class='liljoshDate'><a href='https://twitter.com/$username/status/$id'>$created</a></div><!-- /.liljoshDate -->
        <div class='liljoshText'>".makeHashtagLinks(makeClickableLinks($text))."</div><!-- /.liljoshText -->";
        
        if(is_array($mediaItems)) {
            foreach($mediaItems as $media) {
                $media_url = $media["media_url_https"];
                $media_link = $media["expanded_url"];
                $width = $media["sizes"]["small"]["w"];
                $height = $media["sizes"]["small"]["h"];
                
                echo "<div class='liljoshImage'><a href='$media_link' target='_blank'><img src='$media_url' /></a></div><!-- /.liljoshImage -->";
            }
        }
        
        echo "</div><!-- /.liljoshTweet -->";
    
    }
                 
    function makeClickableLinks($s) {
      return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $s);
    }
    
    function makeHashtagLinks($s) {
        return preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1<span class="liljoshHashtag">#</span><a href="https://twitter.com/hashtag/\2?src=hash" target="_blank">\2</a>', $s);
    }
    ?>
    
    <style>
    
    .liljoshTweet {
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    border: 1px solid #e1e8ed;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    line-height: 1.375em;
    padding: 13px 15px 15px;
    position: relative;
    display:block;
    }
    
    .liljoshText {
    font-size: 26px;
    font-weight: 300;
    line-height: 32px;
    letter-spacing: .01em;
    clear:both;
    }
    
    .liljoshText a {
    color: #0084B4;
    text-decoration: none;
    }
    
    .liljoshName {
    font-size:14px;
    font-weight: bold;
    color: #292f33;
    }
    
    .liljoshUsername, .liljoshDate, .liljoshDivide {
    color: #8899a6;
    font-size: 13px;
    }
    
    .liljoshUsername, .liljoshName, .liljoshDate, .liljoshDivide {
    float:left;
    padding-right: 5px;
    }
    
    .liljoshUsername a, .liljoshName a, .liljoshDate a, .liljoshDivide a,
    .liljoshUsername a:hover, .liljoshName a:hover, .liljoshDate a:hover, .liljoshDivide a:hover,
    .liljoshUsername a:focus, .liljoshName a:focus, .liljoshDate a:focus, .liljoshDivide a:focus,
    .liljoshUsername a:active, .liljoshName a:active, .liljoshDate a:active, .liljoshDivide a:active {
    text-decoration: none;
    color: inherit;
    }
    
    .liljoshImage {
    max-height: 262px;
    clear: both;
    border-radius: 5px;
    overflow: hidden;
    display: inline-block;
    }
    
    .liljoshImage img {
    max-width: 570px;
    }
    
    .liljoshHashtag {
    color: #66B5D2;
    }
    
    </style>
1.1 api quickstart twitter

Github quick start

October 9, 2014

This requires that you generate SSH keys on GitHub and use Terminal to clone and contribute to a repository.

git clone git@github.com:myProject/myRepo.git

cd myRepo

vi someFile.txt

git add someFile.txt

git commit -m "initial add of some file"

git push

clone commit github push quickstart

Remove .php extensions with .htaccess

September 29, 2014

You can clean up your URL a little by automatically removing the .php extensions and index files using mod_rewrite. This requires your web server has Apache running the mod_rewrite module. Create an .htaccess file in your web root directory with this content:

# Author: Lil Josh (liljosh.com)
# Date: Sept 2014
# Description: Clean up the URL by removing the .php extension and index file

RewriteEngine On
RewriteBase /

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ $1 [R=301,L]

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^\.]+)$ $1.php

# Remove index file
RewriteRule ^(.*)index\.(html|htm|shtml|php)$ http://%{HTTP_HOST}/$1 [R=301,L]
.htaccess extension mod_rewrite PHP