Archive for the ‘Web Development’ Category

Scale div / element and maintain aspect ratio with and without box-sizing and padding-top

Kind of ran across this by accident today. I have looked for solutions for this from time to time and always ended up using some sort of hack, but this works, no hacks.

I need this when I want a rectangle to keep it’s ratio without having an image nested inside, but instead using the image as the background.

Use case for this today was a responsive Flexslider implementation with a different set of images with different ratios shown with a media query for smaller devices.

This works with and without box-sizing but if you look at the element in your inspector, box-sizing makes more sense.

There may already be a solution or the same post somewhere else, if so, let me know.

.scales { 
box-sizing: border-box; 
max-width: 100%; 
padding-top: 25%; 
border: 1px solid red; 
}
<div class="scales"></div>

Squeeze your browser and check it out. I didn’t test in every browser.

GoDaddy HTML 5 Boilerplate htaccess file 500 error

I recently had to deal with a client’s site on shared hosting that was returning a 500 error.

After a little diggining I found the offender was the .htacess that comes with HTML5BP.

If you are experiencing the same issue due to some changes GD made,  try commenting out these parts of the .htaccess file:

# AddType text/x-vcard vcf

# HTML, TXT, CSS, JavaScript, JSON, XML, HTC:

# <IfModule filter_module>
# FilterDeclare COMPRESS
# FilterProvider COMPRESS DEFLATE resp=Content-Type $text/html
# FilterProvider COMPRESS DEFLATE resp=Content-Type $text/css
# FilterProvider COMPRESS DEFLATE resp=Content-Type $text/plain
# FilterProvider COMPRESS DEFLATE resp=Content-Type $text/xml
# FilterProvider COMPRESS DEFLATE resp=Content-Type $text/x-component
# FilterProvider COMPRESS DEFLATE resp=Content-Type $application/javascript
# FilterProvider COMPRESS DEFLATE resp=Content-Type $application/json
# FilterProvider COMPRESS DEFLATE resp=Content-Type $application/xml
# FilterProvider COMPRESS DEFLATE resp=Content-Type $application/xhtml+xml
# FilterProvider COMPRESS DEFLATE resp=Content-Type $application/rss+xml
# FilterProvider COMPRESS DEFLATE resp=Content-Type $application/atom+xml
# FilterProvider COMPRESS DEFLATE resp=Content-Type $application/vnd.ms-fontobject
# FilterProvider COMPRESS DEFLATE resp=Content-Type $image/svg+xml
# FilterProvider COMPRESS DEFLATE resp=Content-Type $image/x-icon
# FilterProvider COMPRESS DEFLATE resp=Content-Type $application/x-font-ttf
# FilterProvider COMPRESS DEFLATE resp=Content-Type $font/opentype
# FilterChain COMPRESS
# FilterProtocol COMPRESS DEFLATE change=yes;byteranges=no
</IfModule>

Quick and dirty way to migrate from old Coldfusion / SQL Server to PHP / MySQL using jSON

There may be another way to do this out there, but when I needed it, I couldn’t find an easy free way to do it, so I made one.

You first need to create your new tables in your new MySQL DB and make sure you have allow_url_fopen on in htaccess or in your PHP config. I use PDO so you may have to modify the code if you don’t.

Step 1: The CF file

I made one of these for each table I wanted to move. Map the jSON key to the new column names in your new DB.

<cfquery datasource="yourDSN" name="qName">
 select * from table order by id
 </cfquery>
 [
 <cfoutput query="qName">
 {
 "id":"#URLEncodedFormat(id)#",
 "col1":"#URLEncodedFormat(col1)#",
 "col2":"#URLEncodedFormat(col2)#"
 }
 <cfif currentrow neq recordcount>,</cfif>
 </cfoutput>
 ]

 Step 2: The PHP file

You can run this in your browser using https://yourserver/import.php?records=yourCFfilenameonyourremoteserver

function get_web_page($url)
{
	$options = array( 'http' => array(
			'user_agent' => 'spider', // who am i
			'max_redirects' => 30, // stop after 10 redirects
			'timeout' => 220, // timeout on response
		) );
	$context = stream_context_create( $options );
	$page = @file_get_contents( $url, false, $context );

	$result = array( );
	if ( $page != false )
		$result['content'] = $page;
	else if ( !isset( $http_response_header ) )
			return null; // Bad url, timeout

		// Save the header
		$result['header'] = $http_response_header;

	// Get the *last* HTTP status code
	$nLines = count( $http_response_header );
	for ( $i = $nLines-1; $i >= 0; $i-- )
	{
		$line = $http_response_header[$i];
		if ( strncasecmp( "HTTP", $line, 4 ) == 0 )
		{
			$response = explode( ' ', $line );
			$result['http_code'] = $response[1];
			break;
		}
	}

	return $result;
}

error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set('memory_limit', '128M');

require_once('db.php');

$records = $_GET['records'];

$inserts = get_web_page("https://pathtoyourserverwithcfandsql/".$records.".cfm");

print_r($inserts);

if ($inserts['http_code'] == 200)
{
	$inserts = $inserts['content'];
}

if (json_decode($inserts,true) == true)
{

	$insertsR = json_decode($inserts,true);

	foreach ($insertsR as $items)
	{
		$cols = array();
		$vals = array();

		foreach ($items as $key => $value)
		{
			$cols[] = $key;
			$vals[] = urldecode($value);
		}

		$colsI = implode(',',$cols);

		$questions = '';

		$valsC = count($vals);

		for ($i=1; $i <= $valsC; $i++)
		{
			$questions .= ($i < $valsC) ? '?,' : '?'; 		} 		print_r($cols); 		print_r($vals); 		echo "insert ignore into $records (".implode(',',$cols).") values ($questions)"; 		print_r($vals); 		$statement = $db->prepare("insert ignore into $records (".implode(',',$cols).") values ($questions)");
		$statement->execute($vals);

	}

}

else
{
	echo 'no bueno';
}

Canadian provinces in PHP multi-dimensional array

This was useful when using the shipping address PayPal returns for CA addresses to get rates from the UPS API. The UPS API seems to only accept CA provinces as the two-digit code, PayPal sends it back is full words.

$caProv = array("Alberta" => "AB",
"British Columbia" => "BC",
"Manitoba" => "MB",
"New Brunswick" => "NB",
"Newfoundland and Labrador" => "NL",
"Northwest Territories" => "NT",
"Nova Scotia" => "NS",
"Nunavut" => "NU",
"Ontario" => "ON",
"Prince Edward Island" => "PE",
"Quebec" => "QC",
"Saskatchewan" => "SK",
"Yukon" => "YT");
$state = ($httpParsedResponseAr['SHIPTOCOUNTRYCODE'] == "CA") ? $caProv[$httpParsedResponseAr['SHIPTOSTATE']] : $httpParsedResponseAr['SHIPTOSTATE'];

Sorting muilti-dimensional arrays in PHP

I ALWAYS forget this so I am posting it for myself and anyone else who stumbles upon it.

function subval_sort($a,$subkey) {
 foreach($a as $k=>$v) {
 $b[$k] = strtolower($v[$subkey]);
 }
 asort($b);
 foreach($b as $key=>$val) {
 $c[] = $a[$key];
 }
 return $c;
}
$songs = subval_sort($songs,'artist'); 
print_r($songs);
Array
(
 [0] => Array
 (
 [artist] => Fleetwood Mac
 [song] => Second-hand News
 )

 [1] => Array
 (
 [artist] => The Decemberists
 [song] => The Island
 )

 [2] => Array
 (
 [artist] => The Smashing Pumpkins
 [song] => Cherub Rock
 )

)

Taken from this site:
http://www.firsttube.com/read/sorting-a-multi-dimensional-array-with-php/

Thanks!

Skate Ipsum lorem ipsum generator

Made this awhile back, but didn’t have a place to list it.

Here it is!

I tried to keep it as close to real language as possible by categorizing all of the words with a part of speech and only allowing one proper noun per sentence. It just feels a little bit better than random.

http://skateipsum.com

Skate ipsum dolor sit amet, rip grip Jim Phillips handplant front foot impossible stalefish spine locals ledge. Gnar bucket street shinner hang up front foot impossible goofy footed face plant. Locals crail grab steps nosebone impossible boardslide skater. Pushead rip grip rock and roll nosebone Primo slide bruised heel front foot impossible poseur. Masonite camel back durometer 180 body varial hanger Japan air. Coffin wax shoveit Steve Olson coping front foot impossible flypaper shinner. Method air handplant fakie out manual front foot impossible Saran Wrap pivot. Crail grab 360 varial concave blunt ho-ho lien air. Concave hardware bank salad grind pop shove-it poseur axle.

L-Square Browser Extension / Add-On

Update: I guess I missed this, but something very similar to this made it into Chrome

The other day I read an article mentioning the Boston Globe embracing responsive design. The site was great, but I was having trouble determining screen widths and couldn’t find a tool to easily do this, so I made this for myself. It was easy enough to make so I thought I’d share it with you.

There may be something else that accomplishes the same thing, if there is, sorry, I didn’t see it.

Once the bmklt or extension is clicked, it toggles the rulers over the current page content. The z-index is like 600000 or something, so if someone has a super-high z-index, it may not work. Also, it seems to not work on some Google stuff, but this didn’t really matter too much to me.

It looks like this in use (links below):

Bookmarklet: L-Square
Just drag this up to your tool bar and voila. I did not test this on IE. Please let me know if it has issues and/or what the fix is.

Safari extension: L-Square
This has been approved by Apple and is available in the Extensions Gallery under Developer.

Firefox extension: L-Square
This link will take you to the Mozilla Add-Ons site.

Chrome extension: L-Square
This link will take you to the Chrome web store.

Note: You may need to reload your current page after you install the extension.

Disclaimer: This is my first attempt at extensions. Please forgive me if they suck.

Accessing the Discogs API v2 with PHP

To save someone a little time, here are two ways I was able to successfully send requests and get a 200 response. I was getting 406 because I was relying on my server sending HTTP_ACCEPT_ENCODING, which is apparently not enough.

Using cUrl:

// create curl resource
$ch = curl_init();

// set url
curl_setopt($ch, CURLOPT_URL, "http://api.discogs.com/release/1111");

//send headers
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Accept-Encoding: gzip', 'User-Agent: ExampleBot/1.0'));

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources
curl_close($ch);

echo $output;

Using PHP get_file_contents (Thanks vreon at Discogs):

$ctx_options = array('http' => array('method' => 'GET', 'header' => 'Accept-Encoding: gzip, deflate\r\nUser-Agent: ExampleBot/1.0\r\n'));
$ctx = stream_context_create($ctx_options);
echo file_get_contents('http://api.discogs.com/', false, $ctx);

Of course, make a up a unique user agent.