Archive for the ‘Code Library’ Category
Posted: May 5th, 2010 | Author: Henrie Media Inc. | Filed under: PHP | No Comments »
This is a useful script for anybody who wishes to get the beginning of a string up to the word break before $num of characters. Usually the use of substr will break half way through a word and leave things looking a little untidy on your site. This little function allows you to set the maximum length of the string, then it returns all the whole words before it. If the supplied string is shorter than the maximum length, the whole string is returned.
<?php
/**
*
* @break a string at the end of the last word
* before $maxlength chars
*
* @param string $string
*
* @param int $maxlength
*
* @return string
*
*/
function wordbreak($string, $maxlength)
{
$string = substr($string, 0, $maxlength);
return substr($string, 0, strrpos($string, ” ”));
}
/*** example usage ***/
$string = ’Kyle was hoping to be finished before he left on his vacation to Hawaii! He also wanted to make sure the dog was fed, the house was clean and the lawn was mowed’;
echo wordbreak($string, 50).’ …’;
?>
Print, Email, Share, Enjoy!
Posted: April 14th, 2010 | Author: Henrie Media Inc. | Filed under: Code Library, PHP | No Comments »
Many times it is neat to display the current temperature on your website, and there are a lot of different ways to go about this. I’d like to show you the easiest way to display the temperature on your site using XML from the National Weather Service (NOAA) and simple XML commands in PHP.
Get Started
To get started, you will need to find weather data. The National Weather Service offers this data in free XML feeds, which you can find at http://www.weather.gov/xml/current_obs/. To get started, select an XML feed you’d like to use. I’m using a Salt Lake City, Utah, ID feed, which looks like:
http://www.weather.gov/xml/current_obs/KSLC.xml
You will is this URL in the PHP code to get your location’s current temperature.
The Code
To get the data we want from the XML feed, we will be using the simplexml_load_file() function. This will, essentially, parse the XML for us, making it ready to use as text online. Here is the code you will need:
<?php
// Load the XML
$xml_slc = simplexml_load_file(‘http://www.weather.gov/xml/current_obs/KSLC.xml’);
// Get the current temperature
$slc_temp = $xml_slc->temp_f;
//echo $slc_temp.”° F”;
?>
The output you get should be something similar to 64°. It’s that easy and and it’s FREE! Enjoy!
Print, Email, Share, Enjoy!
Posted: March 30th, 2010 | Author: Henrie Media Inc. | Filed under: JavaScript | No Comments »
I often get the question if it’s possible to use document.write() in JavaScript to output multiple likes instread of having to put – document.write(‘ – at the beginning of every line and – ‘); – at the end. The answer is Yes. Here is how -
document.write(
‘line1′
+’line2′
+’line3′
)
OR -
document.write(
‘line1′ + ‘\n’
+’line2′ + ‘\n’
+’line3′ + ‘\n’
)
..or use a single string -
document.write(
‘line1\
line2\
line3′
)
JavaScript is a little funny, so make sure you test! Hope this helps!
Print, Email, Share, Enjoy!
Posted: June 4th, 2009 | Author: Henrie Media Inc. | Filed under: Configuration | 1 Comment »
If you notice an unreasonable consumption of your bandwidth, there is a good chance that some of your interesting images are being virtually stolen by other websites. They issue links to your content and leave you with the bill. Here is a sure way to prevent this from happening once and for all!
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$ [NC]
RewriteCond %{HTTP_REFERER} !^http://yourdomainname.com [NC]
RewriteCond %{HTTP_REFERER} !^http://www.yourdomainname.com [NC]
RewriteRule [^/]+.(gif|jpg)$ http://eboundhost.com/images/leeching.jpg [R,L]
Of course, you will need to change “yourdomainname.com” to match your actual domain name.
Print, Email, Share, Enjoy!
Posted: March 25th, 2009 | Author: Henrie Media Inc. | Filed under: JavaScript | No Comments »
I am often asked the question of how to generate random numbers in JavaScript. It’s a little tricky and the results may be unpredictable, but the technique to getting them certainly is not. To generate a random number in JavaScript, simply use the following code:
var randomnumber=Math.floor(Math.random()*11)
where 11 dictates that the random number will fall between 0-10. To increase the range to, say, 100, simply change 11 to 101 instead.
Some of you may be curious as to why Math.floor(), instead of Math.round(), is used in the above code. While both successfully round off its containing parameter to an integer within the designated range, Math.floor does so more “evenly”, so the resulting integer isn’t lopsided towards either end of the number spectrum. In other words, a more random number is returned using Math.floor().
Print, Email, Share, Enjoy!
Posted: March 3rd, 2009 | Author: Henrie Media Inc. | Filed under: Code Library, JavaScript | No Comments »
Sometimes you need to perform a function after a set time has passed. This script is a simple to use JavaScript timer.
Here’s the script:
<SCRIPT LANGUAGE = "JavaScript">
<!--
var secs
var timerID = null
var timerRunning = false
var delay = 1000
function InitializeTimer()
{
// Set the length of the timer, in seconds
secs = 10
StopTheClock()
StartTheTimer()
}
function StopTheClock()
{
if(timerRunning)
clearTimeout(timerID)
timerRunning = false
}
function StartTheTimer()
{
if (secs==0)
{
StopTheClock()
// Here's where you put something useful that's
// supposed to happen after the allotted time.
// For example, you could display a message:
alert("You have just wasted 10 seconds of your life.")
}
else
{
self.status = secs
secs = secs - 1
timerRunning = true
timerID = self.setTimeout("StartTheTimer()", delay)
}
}
//-->
</SCRIPT>
To use this script, copy everything between and including the <SCRIPT> and </SCRIPT> tags and insert it on your page between the </HEAD> and <BODY> tags.
The following line sets the length, in seconds, of the timer:
secs = 10
The code decreases the “secs” variable by 1 each second. When “secs” gets to 0, the clock is stopped and that’s when you do whatever it is you want to do once the timer is done (such as display a message or send the user to another page).
In the example above, I use a simple form button to start the timer (it also displays the countdown in the status bar). You could also start the timer (that is, run the InitializeTimer() function) automatically by adding the following to the <BODY> tag:
onLoad="InitializeTimer()"
Print, Email, Share, Enjoy!
Posted: February 26th, 2009 | Author: Henrie Media Inc. | Filed under: Code Library, Configuration | No Comments »
You can use .htaccess to redirect users to a different URL. The .htaccess looks for any request for a specific page and if it finds that request, it forwards it to a new page you have specified.
The syntax is:
redirect accessed-file URL-to-go-to
There are 3 parts;
(1) the Redirect command,
(2) the location of the file/directory you want redirected, and
(3) the full URL of the location you want that request sent to.
These parts are separated by a single space and should be on one line.
For example, if you want to redirect users from oldfile.html in the www directory of your account, myaccount, to newpage.html, the syntax should be
redirect /oldfile.html http://www.carefreetrip.com/newpage.html
Anyone going to http://www.carefreetrip.com/oldfile.html will end up on http://www.carefreetrip.com/newpage.html.
You must use a full URL even if you’re going to send the users to another page on your own site.
You can also redirect an entire directory:
redirect /old_dir/ http://www.carefreetrip.com/new_dir/
Anyone going to http://www.carefreetrip.com/old_dir/filename.html will end up on http://www.carefreetrip.com/new_dir/filename.html.
After you set up the redirect, you should test it by going to the old URL.
Print, Email, Share, Enjoy!
Posted: February 24th, 2009 | Author: Henrie Media Inc. | Filed under: Code Library, Flash | No Comments »
I had a need to pause the timeline in a Flash project I was working on and found this script. I thought I would post it for others if they need to accomplish the same thing. Enjoy!
stop();
var nInterval = setInterval(Play, 5000);
function Play() {
clearInterval(nInterval);
gotoAndPlay(_currentframe+1);
}
so what does Every line mean …
stop();
//stop at your desired frame .
//Build the interval
// 1 second = 1000 milliseconds 1 x 1000
// setinterval(the-function , time[in milliseconds])
var nInterval = setInterval(Play, 5000);
/*function which will excute and clear the interval & Will play the next
Frame after 5 sec.*/
function Play() {
clearInterval(nInterval);
gotoAndPlay(_currentframe+1);
Print, Email, Share, Enjoy!
Posted: February 23rd, 2009 | Author: Henrie Media Inc. | Filed under: Code Library, PHP | No Comments »
When developing PHP-driven websites its often very useful to know how long your pages took to process. This not only gives you some idea of the efficiency of your websites and of the server running them, but may help you diagnose problems, benchmark code corrections/additions, etc. The best way to do this is program PHP to read the system time at the beginning of the page, scan it again near the end, and then work out the difference between the values. To get us started, just add the following basic code near the top of your page, before all the main content:
<?php
$starttime = microtime();
$startarray = explode(” “, $starttime);
$starttime = $startarray[1] + $startarray[0];
?>
It may look complex, but the above code is actually dead simple. Microtime is a function that returns a value giving the current time in seconds and milliseconds from the UNIX Epoch (internationally set as 0:00:00 January 1, 1970 GMT). Explode then splits this value into its two component parts (seconds and milliseconds), and then inserts both values separately into an array. With those values determined, of course, we can go on to insert the following code near the end of the webpage, after all the main code:
<?php
$endtime = microtime();
$endarray = explode(” “, $endtime);
$endtime = $endarray[1] + $endarray[0];
$totaltime = $endtime – $starttime;
$totaltime = round($totaltime,5);
echo “This page loaded in $totaltime seconds.”;
?>
The microtime is determined again and inserted into the endtime array. We then delete the starttime array from it and come up with a brand new value, totaltime (which is the value we’ve wanted all along). The number is then rounded to 5 significant figures, and output by the ECHO command. If you’ve entered everything correctly, you should end up with a line of text saying something like this:
Page generated in 0.27283 seconds
That is all there is to it. Make sure you keep in mind that this measure depends heavily on server load levels, mySQL commands, etc. Make sure you take into account all of these factors when determine load time.
Print, Email, Share, Enjoy!
Posted: December 18th, 2008 | Author: Henrie Media Inc. | Filed under: Code Library, Configuration | No Comments »
A 301 redirect is the best method to preserve your current search engine rankings when redirecting web pages or a website. The code “301″ is interpreted as “moved permanently”. After the code, the URL of the missing or renamed page is noted, followed by a space, then followed by the new location or file name. You implement the 301 redirect by
creating a .htaccess file.
What is a .htaccess file?
When a visitor/spider requests a web page, your web server checks for a .htaccess file. The .htaccess file contains specific instructions for certain requests, including security, redirection issues and how to handle certain errors.
How to implement the 301 Redirect
- To create a .htaccess file, open notepad, name and save the file as .htaccess (there is no extension).
- If you already have a .htaccess file on your server, download it to your desktop for editing.
- Place this code in your .htaccess file: redirect 301 /old/old.htm http://www.you.com/new.htm
- If the .htaccess file already has lines of code in it, skip a line, then add the above code.
- Save the .htaccess file
- Upload this file to the root folder of your server.
- Test it by typing in the old address to the page you’ve changed. You should be immediately taken to the new location.
CONSIDER THIS: Don’t add “http://www” to the first part of the statement – place the path from the top level of your site to the page. Also ensure that you leave a single space between these elements:
redirect 301 (the instruction that the page has moved)
/old/old.htm (the original folder path and file name)
http://www.you.com/new.htm (new path and file name)
When the search engines spider your site again they will follow the rule you have created in your .htaccess file. The search engine spider doesn’t actually read the .htaccess file, but recognizes the response from the server as valid.
During the next update, the old file name and path will be dropped and replaced with the new one. Sometimes you may see alternating old/new file names during the transition period, plus some fluctuations in rankings. According to
Google it will take 6-8 weeks to see the changes reflected on your pages.
Other ways to implement the 301 redirect:
- To redirect ALL files on your domain use this in your .htaccess file if you are on a unix web server:
redirectMatch 301 ^(.*)$ http://www.domain.com
redirectMatch permanent ^(.*)$ http://www.domain.com
You can also use one of these in your .htaccess file:
redirect 301 /index.html http://www.domain.com/index.html
redirect permanent /index.html http://www.domain.com/index.html
redirectpermanent /index.html http://www.domain.com/index.html
This will redirect “index.html” to another domain using a 301-Moved permanently redirect.
- If you need to redirect http://mysite.com to http://www.mysite.com and you’ve got mod_rewrite enabled on your server you can put this in your .htaccess file:
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule ^(.*)$ http://www.example.com/$1 [R=permanent,L]
or this:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]
Use your full URL (ie http://www.domain.com) when obtaining incoming links to your site. Also use your full URL for the internal linking of your site.
- If you want to redirect your .htm pages to .php pages and you’ve got mod_rewrite enabled on your server you can put this in your .htaccess file:
RewriteEngine on
RewriteBase /
RewriteRule (.*).htm$ /$1.php
- If you wish to redirect your .html or .htm pages to .shtml pages because you are using Server Side Includes (SSI) add this code to your .htaccess file:
AddType text/html .shtml
AddHandler server-parsed .shtml .html .htm
Options Indexes FollowSymLinks Includes
DirectoryIndex index.shtml index.html
What’s the difference in using a 301 redirect versus a meta redirect?
Meta Redirect
To send someone to a new page (or site) put this in the head of your document:
<meta http-equiv=”refresh” content=”10; url=http://mynewsite.com/”>
Content=”10; tells the browser to wait 10 seconds before transfer, choose however long you would like, you can even choose 0 to give a smoother transition, but some (really old) browsers aren’t capable of using this so I’d suggest putting a link on that page to your new site for them.
With a meta redirect the page with the redirect issues a 200 OK status and some other mechanism moves the browser over to the new URL. With a 200 OK on both pages, the search engine wants to index both the start page and the target page – and that is a known spam method (set up 10,000 domains full of keywords for the search engines to index then meta redirect the “real visitor” after 0 or 1 seconds to the “real site” ) so using it gets you penalized.
The 301 redirect simply issues a Permanently Moved message in the HTTP header which tells the search engine to only index the target URL.
Print, Email, Share, Enjoy!