Archive for 03/03/14

Tutorial Change Month Number to Month Name

by in , 0

$monthNum = 5;
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));

Reference URL

Beautifull HTML5 Love Heart for Valentine, 8 March, Women Gifts

by in , 0

I had to prepare this a few days ago, but I hope that it’s not too late. I want to introduce you the pleasant html5 examples for women, especially on Valentine’s Day, Or 8 March. This is a collection of interactive hearts and flowers. Trust me – your girlfriend will love it!


1. Love Is In The Air

Love Is In The Air

2. Heart Browser

Heart Browser

3. Bliss

Bliss

4. Plasma of love

Plasma of love

5. Love trails

Love trails

6. A Rose is a Rose

A Rose is a Rose

7. Catchy Hearts

Catchy Hearts

8. WebGL Rose

WebGL Rose

9. Love message

Love message

10. Hearts everywhere


Hearts everywhere

Tutorial Change Graphics Based on Season

by in , 0

Function

<?php

function current_season() {
       // Locate the icons
       $icons = array(
               "spring" => "images/spring.png",
               "summer" => "images/summer.png",
               "autumn" => "images/autumn.png",
               "winter" => "images/winter.png"
       );

       // What is today's date - number
       $day = date("z");

       //  Days of spring
       $spring_starts = date("z", strtotime("March 21"));
       $spring_ends   = date("z", strtotime("June 20"));

       //  Days of summer
       $summer_starts = date("z", strtotime("June 21"));
       $summer_ends   = date("z", strtotime("September 22"));

       //  Days of autumn
       $autumn_starts = date("z", strtotime("September 23"));
       $autumn_ends   = date("z", strtotime("December 20"));

       //  If $day is between the days of spring, summer, autumn, and winter
       if( $day >= $spring_starts && $day <= $spring_ends ) :
               $season = "spring";
       elseif( $day >= $summer_starts && $day <= $summer_ends ) :
               $season = "summer";
       elseif( $day >= $autumn_starts && $day <= $autumn_ends ) :
               $season = "autumn";
       else :
               $season = "winter";
       endif;

       $image_path = $icons[$season];

       echo $image_path;
}

?>

Usage

<img src="<?php current_season() ?>" alt="" />

How to strip white space when grabbing text with jQuery

by 0

I'm wanting to use jQuery to wrap a mailto: anchor around an email address, but it's also grabbing the whitepace that the CMS is generating.
Here's the HTML I have to work with, the script as I have it and a copy of the output.
html
<div >
  <div >
    name@example.com    </div>
</div>
jQuery JavaScript
$(document).ready(function(){
  $('div.field-field-email .field-item').each(function(){
    var emailAdd = $(this).text();
      $(this).wrapInner('<a href="mailto:' + emailAdd + '"></a>');
   });
 });
Generated HTML
<div >
  <div ><a href="mailto:%0A%20%20%20%20name@example.com%20%20%20%20">
    name@example.com    </a></div>
</div>
Though I suspect that others reading this question might want to just strip the leading and tailing whitespace, I'm quite happy to lose all the whitespace considering it's an email address I'm wrapping.
Cheers,
Steve

Read more »

jQuery unfocus method?

by in 0

How can I unfocus a textarea or input? I couldn't find a


$('#my-textarea').unfocus(); method?
yes this is the solution:
$('#textarea').blur()

Source

PHP convert Date from dd/mm/yyyy to yyyy-dd-mm

by in , 0

Conversion

$date_array = explode("/",$date); // split the array
$var_day = $date_array[0]; //day seqment
$var_month = $date_array[1]; //month segment
$var_year = $date_array[2]; //year segment
$new_date_format = "$var_year-$var_day-$var_month"; // join them together
Possibly a more MySQL friendly format in some circumstances.

Change period-separated to slash-separated or vice versa (and reverse order)

Convert date from YYYY/MM/DD to DD.MM.YYYY (and from DD.MM.YYYY to YYYY/MM/DD)
/**
 * @param string $date (d.m.y, y-m-d, y/m/d)
 * @return string|bol
 */

function convertDate($date) {
       // EN-Date to GE-Date
       if (strstr($date, "-") || strstr($date, "/"))   {
               $date = preg_split("/[\/]|[-]+/", $date);
               $date = $date[2].".".$date[1].".".$date[0];
               return $date;
       }
       // GE-Date to EN-Date
       else if (strstr($date, ".")) {
               $date = preg_split("[.]", $date);
               $date = $date[2]."-".$date[1]."-".$date[0];
               return $date;
       }
       return false;
}

Tutorial Calendar Function

by in , 0

<?php

function build_calendar($month,$year,$dateArray) {

    // Create array containing abbreviations of days of week.
    $daysOfWeek = array('S','M','T','W','T','F','S');

    // What is the first day of the month in question?
    $firstDayOfMonth = mktime(0,0,0,$month,1,$year);

    // How many days does this month contain?
    $numberDays = date('t',$firstDayOfMonth);

    // Retrieve some information about the first day of the
    // month in question.
    $dateComponents = getdate($firstDayOfMonth);

    // What is the name of the month in question?
    $monthName = $dateComponents['month'];

    // What is the index value (0-6) of the first day of the
    // month in question.
    $dayOfWeek = $dateComponents['wday'];

    // Create the table tag opener and day headers

    $calendar = "<table class='calendar'>";
    $calendar .= "<caption>$monthName $year</caption>";
    $calendar .= "<tr>";

    // Create the calendar headers

    foreach($daysOfWeek as $day) {
         $calendar .= "<th class='header'>$day</th>";
    }

    // Create the rest of the calendar

    // Initiate the day counter, starting with the 1st.

    $currentDay = 1;

    $calendar .= "</tr><tr>";

    // The variable $dayOfWeek is used to
    // ensure that the calendar
    // display consists of exactly 7 columns.

    if ($dayOfWeek > 0) {
         $calendar .= "<td colspan='$dayOfWeek'>&nbsp;</td>";
    }

    $month = str_pad($month, 2, "0", STR_PAD_LEFT);

    while ($currentDay <= $numberDays) {

         // Seventh column (Saturday) reached. Start a new row.

         if ($dayOfWeek == 7) {

              $dayOfWeek = 0;
              $calendar .= "</tr><tr>";

         }

         $currentDayRel = str_pad($currentDay, 2, "0", STR_PAD_LEFT);

         $date = "$year-$month-$currentDayRel";

         $calendar .= "<td class='day' rel='$date'>$currentDay</td>";

         // Increment counters

         $currentDay++;
         $dayOfWeek++;

    }

    // Complete the row of the last week in month, if necessary

    if ($dayOfWeek != 7) {

         $remainingDays = 7 - $dayOfWeek;
         $calendar .= "<td colspan='$remainingDays'>&nbsp;</td>";

    }

    $calendar .= "</tr>";

    $calendar .= "</table>";

    return $calendar;

}

?>

Usage

To print a table of May 2005, just do:

<?php echo build_calendar(05,2005); ?>

And you'll get a table like this:

May 2005 S M T W T F S
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31  

Tutorial Build a Calendar Table

by in , 0

<?php

function build_calendar($month,$year,$dateArray) {

     // Create array containing abbreviations of days of week.
     $daysOfWeek = array('S','M','T','W','T','F','S');

     // What is the first day of the month in question?
     $firstDayOfMonth = mktime(0,0,0,$month,1,$year);

     // How many days does this month contain?
     $numberDays = date('t',$firstDayOfMonth);

     // Retrieve some information about the first day of the
     // month in question.
     $dateComponents = getdate($firstDayOfMonth);

     // What is the name of the month in question?
     $monthName = $dateComponents['month'];

     // What is the index value (0-6) of the first day of the
     // month in question.
     $dayOfWeek = $dateComponents['wday'];

     // Create the table tag opener and day headers

     $calendar = "<table class='calendar'>";
     $calendar .= "<caption>$monthName $year</caption>";
     $calendar .= "<tr>";

     // Create the calendar headers

     foreach($daysOfWeek as $day) {
          $calendar .= "<th class='header'>$day</th>";
     } 

     // Create the rest of the calendar

     // Initiate the day counter, starting with the 1st.

     $currentDay = 1;

     $calendar .= "</tr><tr>";

     // The variable $dayOfWeek is used to
     // ensure that the calendar
     // display consists of exactly 7 columns.

     if ($dayOfWeek > 0) { 
          $calendar .= "<td colspan='$dayOfWeek'>&nbsp;</td>"; 
     }
     
     $month = str_pad($month, 2, "0", STR_PAD_LEFT);
  
     while ($currentDay <= $numberDays) {

          // Seventh column (Saturday) reached. Start a new row.

          if ($dayOfWeek == 7) {

               $dayOfWeek = 0;
               $calendar .= "</tr><tr>";

          }
          
          $currentDayRel = str_pad($currentDay, 2, "0", STR_PAD_LEFT);
          
          $date = "$year-$month-$currentDayRel";

          $calendar .= "<td class='day' rel='$date'>$currentDay</td>";

          // Increment counters
 
          $currentDay++;
          $dayOfWeek++;

     }
     
     

     // Complete the row of the last week in month, if necessary

     if ($dayOfWeek != 7) { 
     
          $remainingDays = 7 - $dayOfWeek;
          $calendar .= "<td colspan='$remainingDays'>&nbsp;</td>"; 

     }
     
     $calendar .= "</tr>";

     $calendar .= "</table>";

     return $calendar;

}

?> 

Usage

Build a calendar of the current month:

<?php

     $dateComponents = getdate();

     $month = $dateComponents['mon']; 			     
     $year = $dateComponents['year'];

     echo build_calendar($month,$year,$dateArray);

?>

Tutorial Basic SimplePie Usage

by in , 0

You'll need a of copy SimplePie for the include right at the top here.

<?php
    require_once('inc/simplepie.inc');
    
    $feed = new SimplePie();
    
    $feed->set_feed_url(array(
    	'http://search.twitter.com/search.atom?q=movie'
    ));
    
    $feed->enable_cache(true);
    $feed->set_cache_location('cache');
    $feed->set_cache_duration(15);
    
    $feed->init();
    
    $feed->handle_content_type();

    if ($feed->error): ?>
    
        <p><?php echo $feed->error; ?></p>
        
    <?php endif; ?>

    <?php foreach ($feed->get_items() as $item): ?>
    
    	<div class="chunk">
    
    		<h4 style="background:url(<?php $feed = $item->get_feed(); echo $feed->get_favicon(); ?>) no-repeat; text-indent: 25px; margin: 0 0 10px;"><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h4>
    
    		<p class="footnote">Source: <a href="<?php $feed = $item->get_feed(); echo $feed->get_permalink(); ?>"><?php $feed = $item->get_feed(); echo $feed->get_title(); ?></a> | <?php echo $item->get_date('j M Y | g:i a T'); ?></p>
    		     
    	</div>
    
    <?php endforeach; 
    
?>

Reference URL

Tutorial Basic Database Connection, Random Query, Display Result

by in , 0

<?php

define ('HOSTNAME', 'localhost');
define ('USERNAME', 'username');
define ('PASSWORD', 'password');
define ('DATABASE_NAME', 'recommendations');

$db = mysql_connect(HOSTNAME, USERNAME, PASSWORD) or die ('I cannot connect to MySQL.');

mysql_select_db(DATABASE_NAME);

$query = "SELECT testimonial,author FROM recommendations WHERE 1 ORDER by rand() LIMIT 1";

$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {
echo "<p id="quote">" , ($row['testimonial']) , "</p> \n <p id="author">&ndash;" , nl2br($row['author']) , "</p>";
}

mysql_free_result($result);
mysql_close();
?>

Tutorial Backup Database

by in , 0

Class to back up entire databases and email them out, or individual tables.

<?php
   class Backup
       {
               /**
                * @var stores the options
                */
               var $config;

               /**
                * @var stores the final sql dump
                */
               var $dump;

               /**
                * @var stores the table structure + inserts for every table
                */
               var $struktur = array();

               /**
                * @var zip file name
                */
               var $datei;


               /**
                * this function is the constructor and phrase the options
                * and connect to the database
                * @return
                */
               public function Backup($options)
               {
                       // write options
                       foreach($options AS $name => $value)
                       {
                               $this->config[$name] = $value;
                       }

                       // check mysql connection
                       mysql_connect($this->config['mysql'][0], $this->config['mysql'][1], $this->config['mysql'][2]) or die(mysql_error());
                       mysql_select_db($this->config['mysql'][3]) or die(mysql_error());
               }

               /**
                * this function start the backup progress its the core function
                * @return
                */
               public function backupDB()
               {
                       // start backup
                       if(isset($_POST['backup']))
                       {
                               // check if tables are selected
                               if(empty($_POST['table']))
                               {
                                       die("Please select a table.");
                               }

                               /** start backup **/
                               $tables = array();
                               $insert = array();
                               $sql_statement = '';

                               // lock tables
                               foreach($_POST['table'] AS $table)
                               {
                                        mysql_query("LOCK TABLE $table WRITE");

                                       // Read table structure
                                       $res = mysql_query('SHOW CREATE TABLE '.$table.'');
                                       $createtable = mysql_result($res, 0, 1);
                                       $str = "\n\n".$createtable."\n\n";

                                       array_push($tables, $str);

                                       // Read table "inserts"
                           $sql = 'SELECT * FROM '.$table;
                           $query = mysql_query($sql) or die(mysql_error());
                           $feld_anzahl = mysql_num_fields($query);

                                       $sql_statement = '--
-- Data Table `$table`
--

                                               ';

                                       // start reading progress
                           while($ds = mysql_fetch_object($query)){
                               $sql_statement .= 'INSERT INTO `'.$table.'` (';

                               for ($i = 0;$i <$feld_anzahl;$i++){
                                   if ($i ==$feld_anzahl-1){
                                       $sql_statement .= mysql_field_name($query,$i);
                                   } else {
                                       $sql_statement .= mysql_field_name($query,$i).', ';
                                   }
                               }

                               $sql_statement .= ') VALUES (';

                               for ($i = 0;$i <$feld_anzahl;$i++){
                                   $name = mysql_field_name($query,$i);
                                   if (empty($ds->$name)){
                                       $ds->$name = 'NULL';
                                   }
                                   if ($i ==$feld_anzahl-1){
                                       $sql_statement .= '"'.$ds->$name.'"';
                                   } else {
                                       $sql_statement .= '"'.$ds->$name.'", ';
                                   }
                               }
                               $sql_statement .= ");\n";
                           }

                                       // insert "Inserts" into an array if not exists
                                       if(!in_array($sql_statement, $insert))
                                       {
                                               array_push($insert, $sql_statement);
                                               unset($sql_statement);
                                       }

                                       unset($sql_statement);

                               }

                               // put table structure and inserts together in one var
                               $this->struktur = array_combine($tables, $insert);

                               // create full dump
                               $this->createDUMP($this->struktur);

                               // create zip file
                               $this->createZIP();

                               /** end backup **/

                               // send an email with the sql dump
                               if(isset($this->config['email']) && !empty($this->config['email']))
                               {
                                       $this->sendEmail();
                               }

                               // output
                               echo '<h3 style="color:green;">Backup war erfolgreich</h3><a href="'.$this->datei.'">Download Backup</a>
                               <br />
                               <br />';
                       }
               }

               /**
                * this function generate an email with attachment
                * @return
                */
               protected function sendEmail()
               {
                               // start sending emails
                               foreach($this->config['email'] AS $email)
                               {
                                       $to = $email;

                                       $from = $this->config['email'][0];

                                       $message_body = "This email contains the database backup as a zip file.";

                                       $msep = strtoupper (md5 (uniqid (time ())));

                                       // set email header (only text)
                                       $header =
                                                 "From: $from\r\n" .
                                                 "MIME-Version: 1.0\r\n" .
                                                 "Content-Type: multipart/mixed; boundary="$msep"\r\n\r\n" .
                                                 "--$msep\r\n" .
                                                 "Content-Type: text/plain\r\n" .
                                                 "Content-Transfer-Encoding: 8bit\r\n\r\n" .
                                                 $message_body . "\r\n";

                                       // file name
                                       $dateiname = $this->datei;

                                       // get filesize of zip file
                                       $dateigroesse = filesize ($dateiname);

                                       // open file to read
                                       $f = fopen ($dateiname, "r");
                                       // save content
                                       $attached_file = fread ($f, $dateigroesse);
                                       // close file
                                       fclose ($f);

                                       // create attachment
                                       $attachment = chunk_split (base64_encode ($attached_file));

                                       // set attachment header
                                       $header .=
                                                  "--" . $msep . "\r\n" .
                                                  "Content-Type: application/zip; name='Backup'\r\n" .
                                                  "Content-Transfer-Encoding: base64\r\n" .
                                                  "Content-Disposition: attachment; filename='Backup.zip'\r\n" .
                                                  "Content-Description: Mysql Datenbank Backup im Anhang\r\n\r\n" .
                                                  $attachment . "\r\n";

                                       // mark end of attachment
                                       $header .= "--$msep--";

                                       // eMail Subject
                                       $subject = "Database Backup";

                                       // send email to emails^^
                                       if(mail($to, $subject, '', $header) == FALSE)
                                       {
                                               die("The email could not be sent. Please check the email address.");
                                       }

                                       echo "<p><small>Email was successfully sent.</small></p>";
                               }
               }

               /**
                * this function create the zip file with the database dump and save it on the ftp server
                * @return
                */
               protected function createZIP()
               {

                       // Set permissions to 777
                       chmod($this->config['folder'], 0777);

                       // create zip file
                       $zip = new ZipArchive();
                       // Create file name
                       $this->datei = $this->config['folder'].$this->config['mysql'][3]."_".date("j_F_Y_g:i_a").".zip";

                       // Checking if file could be created
                       if ($zip->open($this->datei, ZIPARCHIVE::CREATE)!==TRUE) {
                               exit("cannot open <".$this->datei.">\n");
                       }

                       // add mysql dump to zip file
                       $zip->addFromString("dump.sql", $this->dump);
                       // close file
                       $zip->close();

                       // Check whether file has been created
                       if(!file_exists($this->datei))
                       {
                               die("The ZIP file could not be created.");
                       }

                       echo "<p><small>The zip was created.</small></p>";
               }

               /**
                * this function create the full sql dump
                * @param object $dump
                * @return
                */
               protected function createDUMP($dump)
               {
                       $date = date("F j, Y, g:i a");

                       $header = <<<HEADER
-- SQL Dump
--
-- Host: {$_SERVER['HTTP_HOST']}
-- Erstellungszeit: {$date}

--
-- Datenbank: `{$this->config['mysql'][3]}`
--

-- --------------------------------------------------------

HEADER;
                       foreach($dump AS $name => $value)
                       {
                               $sql .= $name.$value;
                       }
                       $this->dump = $header.$sql;
               }


               /**
                * this function displays the output form to select tables
                * @return
                */
               public function outputForm()
               {
                       // select all tables from database
                       $result = mysql_list_tables($this->config['mysql'][3]);

                       $buffer = '
                       <fieldset>
                               <legend>Select some tables</legend>
                               <form method="post" action="">
                       <select name="table[]" multiple="multiple" size="30">';
                       while($row = mysql_fetch_row($result))
                       {
                               $buffer .= '<option value="'.$row[0].'">'.$row[0].'</option>';
                       }
                       $buffer .= '</select>
                       <br /><br />
                       <input type="submit" name="backup" value="Backup Tables" />
                       </form>
                       </fieldset>';

                       echo $buffer;
               }
       }
?>

Usage:

<?php

       //You can add as many email addresses as you like
       $options = array('email' => array('email1', 'email2'),
                                  'folder' => './backup/',
                                  'mysql' => array('localhost', 'root', '****', 'database'));

       $b = new Backup($options);

       // if submit form start backup
       if(isset($_POST['backup']))
       {
               // start backup
               $b->backupDB();
       }

       // display tables
       $b->outputForm();

?>

Tutorial Automatic Mailto Links

by in , 0

$string = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})','<a href="mailto:\\1">\\1</a>', $text);
echo $string;

Tutorial Automatic Copyright Year

by in , 0

Current year only

&copy; <?php echo date("Y") ?>

With start year

&copy; 2008-<?php echo date("Y") ?>

Start date with error protection

<?php function auto_copyright($year = 'auto'){ ?>
   <?php if(intval($year) == 'auto'){ $year = date('Y'); } ?>
   <?php if(intval($year) == date('Y')){ echo intval($year); } ?>
   <?php if(intval($year) < date('Y')){ echo intval($year) . ' - ' . date('Y'); } ?>
   <?php if(intval($year) > date('Y')){ echo date('Y'); } ?>
<?php } ?>

Usage:

<?php auto_copyright(); // 2011?>

<?php auto_copyright('2010');  // 2010 - 2011 ?>

Reference URL

Tutorial Associative Array Syntax

by in , 0

Simple

$carParts = array( 
   'Tires'=>100, 
   'Window'=>1042, 
   'DoorHandle'=>917 
);

Array of Associative Arrays

public $notifyPartners = array(
			array(
				'name' => 'Twitter', 
				'tag'  => 'Social Network', 
				'url'  => ''),
			array(
				'name' => 'Campaign Monitor', 
				'tag'  => 'Email Marketing', 
				'url'  => ''),
			array(
				'name' => 'Sendloop', 
				'tag'  => 'Email Marketing', 
				'url'  => ''),
			array(
				'name' => 'Highrise', 
				'tag'  => 'CRM', 
				'url'  => '')
);

Looping

foreach ($carParts as $key => $value) {
 echo $key.'=>'.$value.'<br />';
}
while ($element = each($carParts)) {
 echo $element['key'];
 echo ' - ';
 echo $element['value'];
 echo '<br />';
}

Tutorial Applying Even/Odd Classes

by in , 0

<div class="example-class<?php echo ($xyz++%2); ?>">

Used inside a loop, class names would be named .example-class0 and .example-class1 alternating. Increasing the "2" number allows you to increment in thirds or fourths or whatever you need:

class="class<?php echo ($xyz++%3); ?>"

Classes: class0 class1 class2 class0 class1 class2

Change number to 4, this is the result: class0 class1 class2 class3 class0 class1 class2 class3

Tutorial Append Non-Breaking Space Between Last Two Words

by in , 0

<?php

function word_wrapper($text,$minWords = 3) {
       $return = $text;
       $arr = explode(' ',$text);
       if(count($arr) >= $minWords) {
               $arr[count($arr) - 2].= '&nbsp;'.$arr[count($arr) - 1];
               array_pop($arr);
               $return = implode(' ',$arr);
       }
       return $return;
}


?>

Reference URL

Tutorial Append Login Credentials to URL

by in , 0

The example here is if you had a form on a website that when submitted, needed to use that information to go to a special URL where the login information was all appeneded to the URL. You could have the form post with method GET, but that is limited to the typical ?variable=foo&variable2=bar format.

HTML Form

Typical form with three bits of information that submits to a file called ftp.php

<form action="../processing/ftp.php" method="post">
<p><label for="ftp-company-name">Company</label><input type="text" name="ftp-company-name" id="ftp-company-name" /></p>
<p><label for="ftp-user-name">User Name</label><input type="text" name="ftp-user-name" id="ftp-user-name" /></p>
<p><label for="ftp-password">Password</label><input type="password" name="ftp-password" id="ftp-password" /></p>
<p><input type="submit" id="ftp-submit" class="button" value="submit" /></p>
</form>

PHP file

This file reads in the POST variables (if they are set), builds the URL from them, and redirects to it. You'd probably want to clean up the POST variables for security purposes.

<?php

    if (isset($_POST["ftp-company-name"])) {
    
        $company = $_POST["ftp-company-name"];
        $username = $_POST["ftp-user-name"];
        $password = $_POST["ftp-password"];
        
        $url = "ftp://$username:$password@ftp2.edgeconsult.com/$company";
        
        header( "Location: $url" ) ;
        
    } else {
    
        // do nothing
        
    }

?>

Tutorial Adjust Server Time

by in , 0

Sometimes the time set on your server isn't accurate to what your local time is. If you can't change it, you can adjust it yourself.

$today = date('Y-m-d-G');
$today = strftime("%Y-%m-%d-%H", strtotime("$today -5 hour"));

If your server thought it was 12 midnight, but it was really 7 pm, this will roll the $today variable back five hours to be correct.

Redirect WWW / No-WWW htaccess

by in , 0

You should really be doing one or the other. For consistency, as well as SEO's, sake.

Force the www.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^your-site.com [NC]
RewriteRule ^(.*)$ http://www.your-site.com/$1 [L,R=301]

Remove the www.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^your-site.com$ [NC]
RewriteRule ^(.*)$ http://your-site.com/$1 [L,R=301]

Tutorial Use PHP inside JavaScript

by in , 0

This has only really been tested on Media Temple (gs) servers.

In the folder with the JavaScript, the .htaccess file should include:

<FilesMatch "^.*?api.*?$">
SetHandler php5-script
</FilesMatch>

In that above example, any file that includes the string "api" will be processed as PHP. Feel free to alter that RegEx.

Then in the JavaScript file itself, set the ContentType back to JavaScript:

<?php
	// Sets the proper content type for javascript
	header("Content-type: application/javascript");
?>

That will ensure browsers reading the file will interpret it as JavaScript. Now you can use <php ... ?> tags in the JavaScript file to do whatever PHP stuff you need to do.

Tutorial Temporary Maintenance using Mod_Rewrite

by in , 0

# Don't forget to turn on the rewrite engine
RewriteEngine on

# Maintenance Redirection
# Replace 555\.555\.555\.555 with your own IP address
# Uncomment first conditional to turn off the redirection
# RewriteCond %{REQUEST_URI} ^$a
RewriteCond %{REQUEST_URI} !maintenance.html
RewriteCond %{REQUEST_FILENAME} !(styles|images).+$
RewriteCond %{REMOTE_ADDR} !^555\.555\.555\.555$
RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1$
RewriteRule (.*) /maintenance.html [R,L]

This code makes it easy to temporarily take down a website for updates. Replace the "555" line with your own IP address so that you'll still be able to view the website as normal while everyone else gets redirected. Images and styles are allowed to pass through the filter as well.

The first commented condition is designed to fail every time, so turning this redirection off is as simple as uncommenting that line.

Tutorial Subdirectories URL Internally Redirect to Query String

by in , 0

The URL in the browser would be:

http://css-tricks.com/index.php/teachers/a/

The actual page rendered by the server would be:

http://css-tricks.com/index.php?search=teachers&sort=a

RewriteEngine on
RewriteRule ^index/([^/]+)/([^/]+).php /page.php?search=$1&sort=$2 [NC]

Reference URL

Tutorial Shock Teenage Gangsters with wp-config Redirect

by in , 0

Funny email from a reader, that I figured would make a good post:

This is a funny redirect. I get one or two visits a day from teenage gangsters trying to enter my server by checking if a wp-config-file exists that is no longer the newest version. I got best panic results by linking to the Russian IT-Counter-intelligence Agency.

NOTE: You should NOT use this if you are ACTUALLY using WordPress. Also, I updated it to the FBI since that Russian site went down.

Redirect 301 /wp-config.php http://www.fbi.gov/

Tutorial Set Expires

by in , 0

Setting "expires" tells browsers downloading these files that they don't need to request it again for this specific length of time. In otherwords, use the cache instead if you have it. This can reduce stress on the server for you, and speed up page load time for visitors.

# BEGIN EXPIRES
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 10 days"
    ExpiresByType text/css "access plus 1 week"
    ExpiresByType text/plain "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType application/x-javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 week"
    ExpiresByType application/x-icon "access plus 1 year"
</IfModule>
# END EXPIRES

Tutorial Serve SVG with the Correct Content Type

by in , 0

If you are trying to use SVG like <img src="image.svg"> or as a CSS background-image, and the file is linked to correctly and everything seems right, but the browser isn't displaying it, it might be because your server is serving it with an incorrect content-type.

Add this to your .htaccess file at the root to fix it:

AddType image/svg+xml .svg .svgz

Tutorial Remove File Extention from URLs

by in , 0

RewriteRule ^about$ about.php [L]

That little bit will make http://example.com/about.php be able to load at http://example.com/about

Tutorial Prevent Image Hotlinking

by in , 0

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?yourdomain\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpg|gif|bmp|png)$ /images/dontsteal.jpg [L]

Images linked to from anywhere else than your website are redirected to a custom graphic. Do note though, that this would affect people reading posts through RSS readers as well.

Also allow search engines

RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mydomain\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?google\.(.+)/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?(.*\.)?google\.(.+)/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?bing\.(.+)/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?(.*\.)?bing\.(.+)/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?yahoo\.(.+)/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?(.*\.)?yahoo\.(.+)/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpe?g|gif|png)$ /transparent.gif [L]

Tutorial PHP Error Logging

by in , 0

Log errors to a file, and prevent showing them to the user. Make sure that the file exists and youre able to write to it.

# display no errs to user
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
# log to file
php_flag log_errors on
php_value error_log /location/to/php_error.log

Tutorial Password Protect Folder(s)

by in , 0

Put in .htaccess file in the directory you are trying to protect:

AuthType Basic
AuthName "This Area is Password Protected"
AuthUserFile /full/path/to/.htpasswd
Require valid-user

Ideally, the .htpasswd file will be not in a public facing directory. Put this in there:

chriscoyier:$apr1$O/BJv...$vIHV9Q7ySPkw6Mv6Kd/ZE/

That is just a sample, you can create the code for your unique username and password here.

Note that all subdirectories of this directory will also be password protected by this same system.

Tutorial iPhone Catcher

by in , 0

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} .*iPhone.*
RewriteRule ^index\.html$ http://www.mobile.mydomain.com [L]
RewriteRule  ^/$ http://www.mydomain.com/index.html [L]
</IfModule>

Tutorial iPad Detection

by in , 0

Of course, the iPad is a pretty large screen and a fully capable browser, so most websites don't need to have iPad specific versions of them. But if you need to, you can detect for it with .htaccess

RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$
RewriteRule ^(.*)$ http://ipad.yourdomain.com [R=301]

This will redirect iPad users to a URL you specify. This is probably the best way to do it (assuming you are running an Apache server), but if you aren't, there are PHP and JavaScript methods here.

Tutorial Get The Dreamhost Stats Page Working on a WordPress Site

by in , 0

For websites hosted with Dreamhost, you have an analytics page by default at yoursite.tld/stats/. WordPress can interfere with this, thinking that you are trying to link to a page or category and give you a generated 404 page instead.

Simply add this to your .htaccess file ABOVE the typical # BEGIN WordPress stuff to get it working again.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/(stats|failed_auth\.html).*$ [NC]
RewriteRule . - [L]
</IfModule>

Tutorial Force Files to Download (Not Open in Browser)

by in , 0

AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf

Tutorial Force Favicon Requests to Correct Location

by in , 0

For whatever crazy reason, perhaps evil-doing site scanners, requets to a web server for a favicon in all known crevasses of the site are fairly common. Since that file probably only actually exists in the root directory of your site, these requests result in a 404. If you server up a fancy, user-friendly 404 page, this can add up to a ton of bandwidth for no good reason.

This code will make those requests serve up the real favicon instead, saving bandwidth:

# REDIRECT FAVICON.ICO
<ifmodule mod_rewrite.c>
RewriteCond %{REQUEST_URI} !^/favicon\.ico [NC]
RewriteCond %{REQUEST_URI} favicon\.ico    [NC]
RewriteRule (.*) http://css-tricks.com/favicon.ico [R=301,L]
</ifmodule>

Another common one is requests for a file called ajax-loader.gif, probably evil scanning looking for poorly made ajax applications in which to exploit. Make sure that file really does exist and force all requets for it to that real location.

# REDIRECT AJAX-LOADER
<ifmodule mod_rewrite.c>
RewriteCond %{REQUEST_URI} !^/images/ajax\-loader\.gif [NC]
RewriteCond %{REQUEST_URI} ajax\-loader\.gif           [NC]
RewriteRule (.*) http://css-tricks.com/images/ajax-loader.gif [R=301,L]
</ifmodule>

Tutorial Force Correct content-type for XHTML Documents

by in , 0

Most webservers serve XHTML content as text/html what is definitly the right way to handle XHTML documents. In case the server isn't doing that correctly, you can force it on Apache servers with .htaccess:

RewriteEngine On
RewriteCond %{HTTP_ACCEPT} application/xhtml\+xml
RewriteCond %{HTTP_ACCEPT} !application/xhtml\+xml\s*;\s*q=0
RewriteCond %{REQUEST_URI} \.html$
RewriteCond %{THE_REQUEST} HTTP/1\.1
RewriteRule .* - "[T=application/xhtml+xml; charset=ISO-8859-1]"

Reference URL

Tutorial Force charset utf-8

by in , 0

If you can not change the configuration of Apache server, use this code to force decoding of page to utf-8.

AddDefaultCharset utf-8

Reference URL

Tutorial Fancy Indexing

by in , 0

Adds fixed width fonts, file size and date, sort capability. Propagates to higher level directories. See example.

IndexOptions FancyIndexing
IndexOptions FoldersFirst
IndexOptions NameWidth=*

Reference URL

Tutorial Different Directory Index Page

by in , 0

Normally index.html or index.php is the default page a server serves up when visiting a directory without specifying a file name. You can change this with .htaccess:

DirectoryIndex index2.html

Tutorial Append / Prepend Files

by in , 0

Rather than having to call / include a file you need on every single page, you can have them automatically prepended (top of file) or appended (bottom of file) automatically through your .htaccess file.

php_value auto_prepend_file "/real/path/to/file/functions.php"
php_value auto_append_file "/real/path/to/file/footer.php"

Tutorial Allow Single URL Through .htaccess Password Protection

by in , 0

This code is useful for multi environment setups (staging, production, etc.) it allows you to keep your htaccess files in sync while maintaining an htpasswd on your development environment or anything but the live environment.

#allows a single uri through the .htaccess password protection
SetEnvIf Request_URI "/testing_uri$" test_uri

#allows everything if its on a certain host
SetEnvIf HOST "^testing.yoursite.com" testing_url
SetEnvIf HOST "^yoursite.com" live_url
Order Deny,Allow

AuthName "Restricted Area"
AuthType Basic
AuthUserFile /path/to/your/.htpasswd
AuthGroupFile /
Require valid-user

#Allow valid-user
Deny from all
Allow from env=test_uri
Allow from env=testing_url
Allow from env=live_url
Satisfy any

Tutorial Active Gzip Compression

by in , 0

Compression reduces response times by reducing the size of the HTTP response. Gzip is the most popular and effective compression method currently available and generally reduces the response size by about 70%. Approximately 90% of today's Internet traffic travels through browsers that claim to support gzip.

# BEGIN GZIP
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
</ifmodule>
# END GZIP

Tutorial 301 Redirects

by in , 0

This is the cleanest way to redirect a URL. Quick, easy, and search-engine friendly. Remember HTAccess stuff is for Apache servers only.

Redirect a single page

Redirect 301 /oldpage.html http://www.yoursite.com/newpage.html
Redirect 301 /oldpage2.html http://www.yoursite.com/folder/

Redirect an entire site

This way does it with links intact. That is www.oldsite.com/some/crazy/link.html will become www.newsite.com/some/crazy/link.html. This is extremely helpful when you are just "moving" a site to a new domain. Place this on the OLD site:

Redirect 301 / http://newsite.com/

Tutorial Using @font-face

by in , 0

This was updated February 10th, 2011 Updated again January 2012 to be the cleanest and most compatible way to embed custom fonts.
@font-face {
	font-family: 'MyWebFont';
	src: url('webfont.eot'); /* IE9 Compat Modes */
	src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
	     url('webfont.woff') format('woff'), /* Modern Browsers */
	     url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
	     url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
	}

Usage

body {
       font-family: 'MyFontFamily', Fallback, sans-serif;
}

Reference URL

Tutorial Useful CSS3 LESS Mixins

by in , 0

.text-shadow (@string: 0 1px 3px rgba(0, 0, 0, 0.25)) {
	text-shadow: @string;
}
.box-shadow (@string) {
	-webkit-box-shadow: @string;
	-moz-box-shadow:    @string;
	box-shadow:         @string;
}
.drop-shadow (@x: 0, @y: 1px, @blur: 2px, @spread: 0, @alpha: 0.25) {
	-webkit-box-shadow:	@x @y @blur @spread rgba(0, 0, 0, @alpha);
	-moz-box-shadow:	@x @y @blur @spread rgba(0, 0, 0, @alpha);
	box-shadow:		@x @y @blur @spread rgba(0, 0, 0, @alpha);
}
.inner-shadow (@x: 0, @y: 1px, @blur: 2px, @spread: 0, @alpha: 0.25) {
	-webkit-box-shadow: inset @x @y @blur @spread rgba(0, 0, 0, @alpha);
	-moz-box-shadow:    inset @x @y @blur @spread rgba(0, 0, 0, @alpha);
	box-shadow:         inset @x @y @blur @spread rgba(0, 0, 0, @alpha);
}

.box-sizing (@type: border-box) {
	-webkit-box-sizing: @type;
	-moz-box-sizing:    @type;
	box-sizing:         @type;
}

.border-radius (@radius: 5px) {
	-webkit-border-radius: @radius;
	-moz-border-radius:    @radius;
	border-radius:         @radius;

	-moz-background-clip:    padding;
	-webkit-background-clip: padding-box;
	background-clip:         padding-box;
}
.border-radiuses (@topright: 0, @bottomright: 0, @bottomleft: 0, @topleft: 0) {
	-webkit-border-top-right-radius:    @topright;
	-webkit-border-bottom-right-radius: @bottomright;
	-webkit-border-bottom-left-radius:  @bottomleft;
	-webkit-border-top-left-radius:     @topleft;

	-moz-border-radius-topright:        @topright;
	-moz-border-radius-bottomright:     @bottomright;
	-moz-border-radius-bottomleft:      @bottomleft;
	-moz-border-radius-topleft:         @topleft;

	border-top-right-radius:            @topright;
	border-bottom-right-radius:         @bottomright;
	border-bottom-left-radius:          @bottomleft;
	border-top-left-radius:             @topleft;

	-moz-background-clip:    padding; 
	-webkit-background-clip: padding-box; 
	background-clip:         padding-box; 
}

.opacity (@opacity: 0.5) {
	-webkit-opacity: 	@opacity;
	-moz-opacity: 		@opacity;
	opacity: 		@opacity;
}

.gradient (@startColor: #eee, @endColor: white) {
	background-color: @startColor;
	background: -webkit-gradient(linear, left top, left bottom, from(@startColor), to(@endColor));
	background: -webkit-linear-gradient(top, @startColor, @endColor);
	background: -moz-linear-gradient(top, @startColor, @endColor);
	background: -ms-linear-gradient(top, @startColor, @endColor);
	background: -o-linear-gradient(top, @startColor, @endColor);
}
.horizontal-gradient (@startColor: #eee, @endColor: white) {
 	background-color: @startColor;
	background-image: -webkit-gradient(linear, left top, right top, from(@startColor), to(@endColor));
	background-image: -webkit-linear-gradient(left, @startColor, @endColor);
	background-image: -moz-linear-gradient(left, @startColor, @endColor);
	background-image: -ms-linear-gradient(left, @startColor, @endColor);
	background-image: -o-linear-gradient(left, @startColor, @endColor);
}

.animation (@name, @duration: 300ms, @delay: 0, @ease: ease) {
	-webkit-animation: @name @duration @delay @ease;
	-moz-animation:    @name @duration @delay @ease;
	-ms-animation:     @name @duration @delay @ease;
}

.transition (@transition) {
	-webkit-transition: @transition;  
	-moz-transition:    @transition;
	-ms-transition:     @transition; 
	-o-transition:      @transition;  
}
.transform(@string){
	-webkit-transform: @string;
	-moz-transform: 	 @string;
	-ms-transform: 		 @string;
	-o-transform: 		 @string;
}
.scale (@factor) {
	-webkit-transform: scale(@factor);
	-moz-transform: 	 scale(@factor);
	-ms-transform: 		 scale(@factor);
	-o-transform: 		 scale(@factor);
}
.rotate (@deg) {
	-webkit-transform: rotate(@deg);
	-moz-transform: 	 rotate(@deg);
	-ms-transform: 		 rotate(@deg);
	-o-transform: 		 rotate(@deg);
}
.skew (@deg, @deg2) {
	-webkit-transform:       skew(@deg, @deg2);
	-moz-transform: 	 skew(@deg, @deg2);
	-ms-transform: 		 skew(@deg, @deg2);
	-o-transform: 		 skew(@deg, @deg2);
}
.translate (@x, @y:0) {
	-webkit-transform:       translate(@x, @y);
	-moz-transform: 	 translate(@x, @y);
	-ms-transform: 		 translate(@x, @y);
	-o-transform: 		 translate(@x, @y);
}
.translate3d (@x, @y: 0, @z: 0) {
	-webkit-transform:       translate3d(@x, @y, @z);
	-moz-transform: 	 translate3d(@x, @y, @z);
	-ms-transform: 		 translate3d(@x, @y, @z);
	-o-transform: 		 translate3d(@x, @y, @z);
}
.perspective (@value: 1000) {
	-webkit-perspective: 	@value;
	-moz-perspective: 	@value;
	-ms-perspective: 	@value;
	perspective: 		@value;
}
.transform-origin (@x:center, @y:center) {
	-webkit-transform-origin: @x @y;
	-moz-transform-origin:    @x @y;
	-ms-transform-origin:     @x @y;
	-o-transform-origin:      @x @y;
}

Tutorial Two-Color Three-Dimensional Blocks and Text

by in , 0

We can use multiple text-shadow and box-shadow values to create a three-dimensional look to blocks or text, like this screenshot of David DeSandro's footer. However in that example, the "three dimesional" part is a solid color.

By alternating colors back and forth in the "stacking order" of our box or text shadow declaration, we can simulate a more three dimensional / lighted effect.

text-shadow:   1px 0px #eee, 0px 1px #ccc,
               2px 1px #eee, 1px 2px #ccc,
               3px 2px #eee, 2px 3px #ccc,
               4px 3px #eee, 3px 4px #ccc,
               5px 4px #eee, 4px 5px #ccc,
               6px 5px #eee, 5px 6px #ccc,
               7px 6px #eee, 6px 7px #ccc,
               8px 7px #eee, 7px 8px #ccc,
               8px 8px #eee;

Example

Reference URL

Tutorial Turn Off Number Input Spinners

by in , 0

WebKit desktop browsers add little up down arrows to number inputs called spinners. You can turn them off visually like this:

input[type=number]::-webkit-inner-spin-button, 
input[type=number]::-webkit-outer-spin-button { 
  -webkit-appearance: none; 
  margin: 0; 
}

Note that some other functionality still exists, like being able to increment the number via the scroll wheel on a mouse.

Top, on, Bottom, off.

Tutorial Tucked Corners

by in , 0

<div class="corners">
   Content
</div>
body {
    background: #e6e6e6;
}
.corners { 
    background: #f6f6f6;
    height: 700px;
    margin: 50px auto;
    max-width: 600px;
    position: relative;
    width: 80%;
    -webkit-box-shadow: 0 1px 7px hsla(0,0%,0%,.2);
       -moz-box-shadow: 0 1px 7px hsla(0,0%,0%,.2);
            box-shadow: 0 1px 7px hsla(0,0%,0%,.2);
}
/* Corner Effect */
.corners:after,
.corners:before {
    background: #e6e6e6;
    content: '';
    height: 50px;
    position: absolute;
    top: -25px;
    width: 100px;
    -webkit-box-shadow: 0 5px 10px -7px hsla(0,0%,0%,.5);
       -moz-box-shadow: 0 5px 10px -7px hsla(0,0%,0%,.5);
            box-shadow: 0 5px 10px -7px hsla(0,0%,0%,.5);
}
.corners:after {
    left: -50px;
    -webkit-transform: rotate(-45deg);
       -moz-transform: rotate(-45deg);
        -ms-transform: rotate(-45deg);
         -o-transform: rotate(-45deg);
            transform: rotate(-45deg);
}
.corners:before {
    right: -50px;
    -webkit-transform: rotate(45deg);
       -moz-transform: rotate(45deg);
        -ms-transform: rotate(45deg);
         -o-transform: rotate(45deg);
            transform: rotate(45deg);
}

More robust example including bottom corners at the Reference URL.

Reference URL

Tutorial Truncate String with Ellipsis

by in , 0

All the following are required, so the text must be in a single straight line that overflows a box where that overflow is hidden.

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

A bunch of more techniques here, including multi-line ellipsis.

Tutorial Triangular List Bullets

by in , 0

ul {
    margin: 0.75em 0;
    padding: 0 1em;
    list-style: none;
}
li:before { 
    content: "";
    border-color: transparent #111;
    border-style: solid;
    border-width: 0.35em 0 0.35em 0.45em;
    display: block;
    height: 0;
    width: 0;
    left: -1em;
    top: 0.9em;
    position: relative;
}

Reference URL

Tutorial Transparent Inside Border

by in , 0

<div class="inner-border">
    Transparent Inside Border
</div>
.inner-border {
    background: #000;
    color: #fff;
    margin: 50px;
    padding: 15px;
    position: relative;
}
.inner-border:before {
    border: 5px solid #000;
    content: "";
    position: absolute;
    top: -10px;
    bottom: -10px;
    left: -10px;
    right: -10px;
}

Reference URL