Bootstrap Profile Card

HTML

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
<div class="container">
	<div class="row">
		<div class="col-lg-3 col-sm-6">

            <div class="card hovercard">
                <div class="cardheader">

                </div>
                <div class="avatar">
                    <img alt="" src="http://lorempixel.com/100/100/people/9/">
                </div>
                <div class="info">
                    <div class="title">
                        <a target="_blank" href="http://scripteden.com/">Script Eden</a>
                    </div>
                    <div class="desc">Passionate designer</div>
                    <div class="desc">Curious developer</div>
                    <div class="desc">Tech geek</div>
                </div>
                <div class="bottom">
                    <a class="btn btn-primary btn-twitter btn-sm" href="https://twitter.com/webmaniac">
                        <i class="fa fa-twitter"></i>
                    </a>
                    <a class="btn btn-danger btn-sm" rel="publisher"
                       href="https://plus.google.com/+ahmshahnuralam">
                        <i class="fa fa-google-plus"></i>
                    </a>
                    <a class="btn btn-primary btn-sm" rel="publisher"
                       href="https://plus.google.com/shahnuralam">
                        <i class="fa fa-facebook"></i>
                    </a>
                    <a class="btn btn-warning btn-sm" rel="publisher" href="https://plus.google.com/shahnuralam">
                        <i class="fa fa-behance"></i>
                    </a>
                </div>
            </div>

        </div>

	</div>
</div>

CSS



.card {
    padding-top: 20px;
    margin: 10px 0 20px 0;
    background-color: rgba(214, 224, 226, 0.2);
    border-top-width: 0;
    border-bottom-width: 2px;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

.card .card-heading {
    padding: 0 20px;
    margin: 0;
}

.card .card-heading.simple {
    font-size: 20px;
    font-weight: 300;
    color: #777;
    border-bottom: 1px solid #e5e5e5;
}

.card .card-heading.image img {
    display: inline-block;
    width: 46px;
    height: 46px;
    margin-right: 15px;
    vertical-align: top;
    border: 0;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
}

.card .card-heading.image .card-heading-header {
    display: inline-block;
    vertical-align: top;
}

.card .card-heading.image .card-heading-header h3 {
    margin: 0;
    font-size: 14px;
    line-height: 16px;
    color: #262626;
}

.card .card-heading.image .card-heading-header span {
    font-size: 12px;
    color: #999999;
}

.card .card-body {
    padding: 0 20px;
    margin-top: 20px;
}

.card .card-media {
    padding: 0 20px;
    margin: 0 -14px;
}

.card .card-media img {
    max-width: 100%;
    max-height: 100%;
}

.card .card-actions {
    min-height: 30px;
    padding: 0 20px 20px 20px;
    margin: 20px 0 0 0;
}

.card .card-comments {
    padding: 20px;
    margin: 0;
    background-color: #f8f8f8;
}

.card .card-comments .comments-collapse-toggle {
    padding: 0;
    margin: 0 20px 12px 20px;
}

.card .card-comments .comments-collapse-toggle a,
.card .card-comments .comments-collapse-toggle span {
    padding-right: 5px;
    overflow: hidden;
    font-size: 12px;
    color: #999;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.card-comments .media-heading {
    font-size: 13px;
    font-weight: bold;
}

.card.people {
    position: relative;
    display: inline-block;
    width: 170px;
    height: 300px;
    padding-top: 0;
    margin-left: 20px;
    overflow: hidden;
    vertical-align: top;
}

.card.people:first-child {
    margin-left: 0;
}

.card.people .card-top {
    position: absolute;
    top: 0;
    left: 0;
    display: inline-block;
    width: 170px;
    height: 150px;
    background-color: #ffffff;
}

.card.people .card-top.green {
    background-color: #53a93f;
}

.card.people .card-top.blue {
    background-color: #427fed;
}

.card.people .card-info {
    position: absolute;
    top: 150px;
    display: inline-block;
    width: 100%;
    height: 101px;
    overflow: hidden;
    background: #ffffff;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

.card.people .card-info .title {
    display: block;
    margin: 8px 14px 0 14px;
    overflow: hidden;
    font-size: 16px;
    font-weight: bold;
    line-height: 18px;
    color: #404040;
}

.card.people .card-info .desc {
    display: block;
    margin: 8px 14px 0 14px;
    overflow: hidden;
    font-size: 12px;
    line-height: 16px;
    color: #737373;
    text-overflow: ellipsis;
}

.card.people .card-bottom {
    position: absolute;
    bottom: 0;
    left: 0;
    display: inline-block;
    width: 100%;
    padding: 10px 20px;
    line-height: 29px;
    text-align: center;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

.card.hovercard {
    position: relative;
    padding-top: 0;
    overflow: hidden;
    text-align: center;
    background-color: rgba(214, 224, 226, 0.2);
}

.card.hovercard .cardheader {
    background: url("http://lorempixel.com/850/280/nature/4/");
    background-size: cover;
    height: 135px;
}

.card.hovercard .avatar {
    position: relative;
    top: -50px;
    margin-bottom: -50px;
}

.card.hovercard .avatar img {
    width: 100px;
    height: 100px;
    max-width: 100px;
    max-height: 100px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    border: 5px solid rgba(255,255,255,0.5);
}

.card.hovercard .info {
    padding: 4px 8px 10px;
}

.card.hovercard .info .title {
    margin-bottom: 4px;
    font-size: 24px;
    line-height: 1;
    color: #262626;
    vertical-align: middle;
}

.card.hovercard .info .desc {
    overflow: hidden;
    font-size: 12px;
    line-height: 20px;
    color: #737373;
    text-overflow: ellipsis;
}

.card.hovercard .bottom {
    padding: 0 20px;
    margin-bottom: 17px;
}

.btn{ border-radius: 50%; width:32px; height:32px; line-height:18px;  }

Bootstrap Loading button effect (no JS)

HTML

<div class="container">
	<div class="row">
        <h1 class="col-xs-12">Loading button effect</h1>
        
		<div class="col-xs-12 text-center">
            <h2>Preview</h2>
            <table class="table">
                <tr>
                    <th>No effect</th>
                    <th>With effect</th>
                </tr>
                <tr>
                    <td colspan="2">Base effect</td>
                </tr>
                <tr>
                    <td>
                        <button class="btn btn-lg btn-primary">Button</button>
                		<button class="btn btn-lg btn-default">Button</button>
            			<button class="btn btn-lg btn-info">Button</button>
            			<button class="btn btn-lg btn-warning">Button</button>
            			<button class="btn btn-lg btn-danger">Button</button>
                    </td>
                    <td>
                        <button class="btn btn-lg btn-primary m-progress">Button</button>
                		<button class="btn btn-lg btn-default m-progress">Button</button>
            			<button class="btn btn-lg btn-info m-progress">Button</button>
            			<button class="btn btn-lg btn-warning m-progress">Button</button>
            			<button class="btn btn-lg btn-danger m-progress">Button</button>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">For any size</td>
                </tr>
                <tr>
                    <td>
                        <button class="btn btn-lg btn-primary">Button</button>
                    	<button class="btn btn-primary">Button</button>
                        <button class="btn btn-sm btn-primary">Button</button>
                        <button class="btn btn-xs btn-primary">Button</button>
                    </td>
                    <td>
                        <button class="btn m-progress btn-lg btn-primary">Button</button>
                        <button class="btn m-progress btn-primary">Button</button>
                        <button class="btn m-progress btn-sm btn-primary">Button</button>
                        <button class="btn m-progress btn-xs btn-primary">Button</button>
                    </td>
                </tr>
            </table>
		</div>
	</div>
</div>

CSS

@-webkit-keyframes ld {
  0%   { transform: rotate(0deg) scale(1); }
  50%  { transform: rotate(180deg) scale(1.1); }
  100% { transform: rotate(360deg) scale(1); }
}
@-moz-keyframes ld {
  0%   { transform: rotate(0deg) scale(1); }
  50%  { transform: rotate(180deg) scale(1.1); }
  100% { transform: rotate(360deg) scale(1); }
}
@-o-keyframes ld {
  0%   { transform: rotate(0deg) scale(1); }
  50%  { transform: rotate(180deg) scale(1.1); }
  100% { transform: rotate(360deg) scale(1); }
}
@keyframes ld {
  0%   { transform: rotate(0deg) scale(1); }
  50%  { transform: rotate(180deg) scale(1.1); }
  100% { transform: rotate(360deg) scale(1); }
}

.m-progress {
    position: relative;
    opacity: .8;
    color: transparent !important;
    text-shadow: none !important;
}

.m-progress:hover,
.m-progress:active,
.m-progress:focus {
    cursor: default;
    color: transparent;
    outline: none !important;
    box-shadow: none;
}

.m-progress:before {
    content: '';
    
    display: inline-block;
    
    position: absolute;
    background: transparent;
    border: 1px solid #fff;
    border-top-color: transparent;
    border-bottom-color: transparent;
    border-radius: 50%;
    
    box-sizing: border-box;
    
    top: 50%;
    left: 50%;
    margin-top: -12px;
    margin-left: -12px;
    
    width: 24px;
    height: 24px;
    
    -webkit-animation: ld 1s ease-in-out infinite;
    -moz-animation:    ld 1s ease-in-out infinite;
    -o-animation:      ld 1s ease-in-out infinite;
    animation:         ld 1s ease-in-out infinite;
}

.btn-default.m-progress:before {
    border-left-color: #333333;
    border-right-color: #333333;
}

.btn-lg.m-progress:before {
    margin-top: -16px;
    margin-left: -16px;
    
    width: 32px;
    height: 32px;
}

.btn-sm.m-progress:before {
    margin-top: -9px;
    margin-left: -9px;
    
    width: 18px;
    height: 18px;
}

.btn-xs.m-progress:before {
    margin-top: -7px;
    margin-left: -7px;
    
    width: 14px;
    height: 14px;
}

Bootstrap Pricing Slider [Mobile Touch UI]

HTML

  <div class="container">
    
    
    <center>
    <strong>ORIGINAL</strong>         
    <br><br>
    http://bootsnipp.com/snippets/featured/bootstrap-pricing-slider-donations<br><br>
    <strong>REVISIONS</strong>
    <h4>- Added jquery.ui.touch-punch.min.js from http://touchpunch.furf.com <br><br>
        - Due to glitchy dragging, changed css to have normal sized .label on slider, but large transparent tab hidden.
    </h4>
    </center>
      <br><br>
      
      <!-- START -->
      <div class="price-box">

        <form class="form-horizontal form-pricing" role="form">

          <div class="price-slider">
            <h4 class="great">Amount</h4>
            <span>Minimum $10 is required</span>
            <div class="col-sm-12">
             <div id="slider"></div>
            </div>
          </div>
          <div class="price-slider">
            <h4 class="great">Duration</h4>
            <span>Minimum 1 day is required</span>
            <div class="col-sm-12">
              <div id="slider2"></div>
            </div>
          </div>

          <div class="price-form">

            <div class="form-group">
              <label for="amount" class="col-sm-6 control-label">Amount ($): </label>
              <span class="help-text">Please choose your amount</span>
              <div class="col-sm-6">
                <input type="hidden" id="amount" class="form-control">
                <p class="price lead" id="amount-label"></p>
                <span class="price">.00</span>
              </div>
            </div>
            <div class="form-group">
              <label for="duration" class="col-sm-6 control-label">Duration: </label>
              <span class="help-text">Choose your commitment</span>
              <div class="col-sm-6">
                <input type="hidden" id="duration" class="form-control">
                <p class="price lead" id="duration-label"></p>
                <span class="price">days</span>
              </div>
            </div>
            <hr class="style">
            <div class="form-group total">
              <label for="total" class="col-sm-6 control-label"><strong>Total: </strong></label>
              <span class="help-text">(Amount * Days)</span>
              <div class="col-sm-6">
                <input type="hidden" id="total" class="form-control">
                <p class="price lead" id="total-label"></p>
                <span class="price">.00</span>
              </div>
            </div>

          </div>

          <div class="form-group">
            <div class="col-sm-12">
              <button type="submit" class="btn btn-primary btn-lg btn-block">Proceed <span class="glyphicon glyphicon-chevron-right pull-right" style="padding-right: 10px;"></span></button>
            </div>
          </div>
          <div class="form-group">
            <div class="col-sm-12">
              <img src="http://amirolahmad.github.io/bootstrap-pricing-slider/images/payment.png" class="img-responsive payment" />
            </div>
          </div>

        </form>

        <p class="text-center" style="padding-top:10px;font-size:12px;color:#2c3e50;font-style:italic;">Created by <a href="https://twitter.com/AmirolAhmad" target="_blank">AmirolAhmad</a></p>

      </div>

    </div>
        <script src="http://code.jquery.com/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
    <script>
        /*!
 * jQuery UI Touch Punch 0.2.3
 *
 * Copyright 2011โ€“2014, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 *  jquery.ui.widget.js
 *  jquery.ui.mouse.js
 */
(function ($) {

  // Detect touch support
  $.support.touch = 'ontouchend' in document;

  // Ignore browsers without touch support
  if (!$.support.touch) {
    return;
  }

  var mouseProto = $.ui.mouse.prototype,
      _mouseInit = mouseProto._mouseInit,
      _mouseDestroy = mouseProto._mouseDestroy,
      touchHandled;

  /**
   * Simulate a mouse event based on a corresponding touch event
   * @param {Object} event A touch event
   * @param {String} simulatedType The corresponding mouse event
   */
  function simulateMouseEvent (event, simulatedType) {

    // Ignore multi-touch events
    if (event.originalEvent.touches.length > 1) {
      return;
    }

    event.preventDefault();

    var touch = event.originalEvent.changedTouches[0],
        simulatedEvent = document.createEvent('MouseEvents');
    
    // Initialize the simulated mouse event using the touch event's coordinates
    simulatedEvent.initMouseEvent(
      simulatedType,    // type
      true,             // bubbles                    
      true,             // cancelable                 
      window,           // view                       
      1,                // detail                     
      touch.screenX,    // screenX                    
      touch.screenY,    // screenY                    
      touch.clientX,    // clientX                    
      touch.clientY,    // clientY                    
      false,            // ctrlKey                    
      false,            // altKey                     
      false,            // shiftKey                   
      false,            // metaKey                    
      0,                // button                     
      null              // relatedTarget              
    );

    // Dispatch the simulated event to the target element
    event.target.dispatchEvent(simulatedEvent);
  }

  /**
   * Handle the jQuery UI widget's touchstart events
   * @param {Object} event The widget element's touchstart event
   */
  mouseProto._touchStart = function (event) {

    var self = this;

    // Ignore the event if another widget is already being handled
    if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
      return;
    }

    // Set the flag to prevent other widgets from inheriting the touch event
    touchHandled = true;

    // Track movement to determine if interaction was a click
    self._touchMoved = false;

    // Simulate the mouseover event
    simulateMouseEvent(event, 'mouseover');

    // Simulate the mousemove event
    simulateMouseEvent(event, 'mousemove');

    // Simulate the mousedown event
    simulateMouseEvent(event, 'mousedown');
  };

  /**
   * Handle the jQuery UI widget's touchmove events
   * @param {Object} event The document's touchmove event
   */
  mouseProto._touchMove = function (event) {

    // Ignore event if not handled
    if (!touchHandled) {
      return;
    }

    // Interaction was not a click
    this._touchMoved = true;

    // Simulate the mousemove event
    simulateMouseEvent(event, 'mousemove');
  };

  /**
   * Handle the jQuery UI widget's touchend events
   * @param {Object} event The document's touchend event
   */
  mouseProto._touchEnd = function (event) {

    // Ignore event if not handled
    if (!touchHandled) {
      return;
    }

    // Simulate the mouseup event
    simulateMouseEvent(event, 'mouseup');

    // Simulate the mouseout event
    simulateMouseEvent(event, 'mouseout');

    // If the touch interaction did not move, it should trigger a click
    if (!this._touchMoved) {

      // Simulate the click event
      simulateMouseEvent(event, 'click');
    }

    // Unset the flag to allow other widgets to inherit the touch event
    touchHandled = false;
  };

  /**
   * A duck punch of the $.ui.mouse _mouseInit method to support touch events.
   * This method extends the widget with bound touch event handlers that
   * translate touch events to mouse events and pass them to the widget's
   * original mouse event handling methods.
   */
  mouseProto._mouseInit = function () {
    
    var self = this;

    // Delegate the touch handlers to the widget's element
    self.element.bind({
      touchstart: $.proxy(self, '_touchStart'),
      touchmove: $.proxy(self, '_touchMove'),
      touchend: $.proxy(self, '_touchEnd')
    });

    // Call the original $.ui.mouse init method
    _mouseInit.call(self);
  };

  /**
   * Remove the touch event handlers
   */
  mouseProto._mouseDestroy = function () {
    
    var self = this;

    // Delegate the touch handlers to the widget's element
    self.element.unbind({
      touchstart: $.proxy(self, '_touchStart'),
      touchmove: $.proxy(self, '_touchMove'),
      touchend: $.proxy(self, '_touchEnd')
    });

    // Call the original $.ui.mouse destroy method
    _mouseDestroy.call(self);
  };

})(jQuery);
        
    </script>

CSS

body {
    padding-top: 50px;
    padding-bottom: 50px;
}

.price-box {
    margin: 0 auto;
    background: #E9E9E9;
	border-radius: 10px;
	padding: 40px 15px;
	width: 500px;
}

.ui-widget-content {
	border: 1px solid #bdc3c7;
	background: #e1e1e1;
	color: #222222;
	margin-top: 4px;
}

.ui-state-default, .ui-widget-content .ui-state-default{
background:transparent !important;
border:none !important;
}
.ui-slider .ui-slider-handle label{
    background: #428bca;
    border-radius: 20px;
    width:5.2em;
}

.ui-slider .ui-slider-handle {
	position: absolute;
	z-index: 2;
	width: 5.2em;
	height: 100px;
	cursor: default;
	margin: 0 -40px auto !important;
	text-align: center;	
	line-height: 35px;
	color: #FFFFFF;
	font-size: 15px;
    
}

.ui-slider .ui-slider-handle .glyphicon {
	color: #FFFFFF;
	margin: 0 3px; 
	font-size: 11px;
	opacity: 0.5;
}

.ui-corner-all {
	border-radius: 20px;
}

.ui-slider-horizontal .ui-slider-handle {
	top: -.9em;
}

.ui-state-default,
.ui-widget-content .ui-state-default {
	border: 1px solid #f9f9f9;
	background: #3498db;
}

.ui-slider-horizontal .ui-slider-handle {
	margin-left: -0.5em;
}

.ui-slider .ui-slider-handle {
	cursor: pointer;
}

.ui-slider a,
.ui-slider a:focus {
	cursor: pointer;
	outline: none;
}

.price, .lead p {
	font-weight: 600;
	font-size: 32px;
	display: inline-block;
	line-height: 60px;
}

h4.great {
	background: #00ac98;
	margin: 0 0 25px -60px;
	padding: 7px 15px;
	color: #ffffff;
	font-size: 18px;
	font-weight: 600;
	border-radius: 5px;
	display: inline-block;
	-moz-box-shadow:    2px 4px 5px 0 #ccc;
  	-webkit-box-shadow: 2px 4px 5px 0 #ccc;
  	box-shadow:         2px 4px 5px 0 #ccc;
}

.total {
	border-bottom: 1px solid #7f8c8d;
	/*display: inline;
	padding: 10px 5px;*/
	position: relative;
	padding-bottom: 20px;
}

.total:before {
	content: "";
	display: inline;
	position: absolute;
	left: 0;
	bottom: 5px;
	width: 100%;
	height: 3px;
	background: #7f8c8d;
	opacity: 0.5;
}

.price-slider {
	margin-bottom: 70px;
}

.price-slider span {
	font-weight: 200;
	display: inline-block;
	color: #7f8c8d;
	font-size: 13px;
}

.form-pricing {
	background: #ffffff;
	padding: 20px;
	border-radius: 4px;
}

.price-form {
	background: #ffffff;
	margin-bottom: 10px;
	padding: 20px;
	border: 1px solid #eeeeee;
	border-radius: 4px;
	/*-moz-box-shadow:    0 5px 5px 0 #ccc;
  	-webkit-box-shadow: 0 5px 5px 0 #ccc;
  	box-shadow:         0 5px 5px 0 #ccc;*/
}

.form-group {
	margin-bottom: 0;
}

.form-group span.price {
	font-weight: 200;
	display: inline-block;
	color: #7f8c8d;
	font-size: 14px;
}

.help-text {
	display: block;
	margin-top: 32px;
	margin-bottom: 10px;
	color: #737373;
	position: absolute;
	/*margin-left: 20px;*/
	font-weight: 200;
	text-align: right;
	width: 188px;
}

.price-form label {
	font-weight: 200;
	font-size: 21px;
}

img.payment {
	display: block;
    margin-left: auto;
    margin-right: auto
}

.ui-slider-range-min {
	background: #2980b9;
}

/* HR */

hr.style {
	margin-top: 0;
    border: 0;
    border-bottom: 1px dashed #ccc;
    background: #999;
}
}

Javascript

$(document).ready(function() {
          $("#slider").slider({
              animate: true,
              value:1,
              min: 0,
              max: 1000,
              step: 10,
              slide: function(event, ui) {
                  update(1,ui.value); //changed
              }
          });

          $("#slider2").slider({
              animate: true,
              value:0,
              min: 0,
              max: 500,
              step: 1,
              slide: function(event, ui) {
                  update(2,ui.value); //changed
              }
          });

          //Added, set initial value.
          $("#amount").val(0);
          $("#duration").val(0);
          $("#amount-label").text(0);
          $("#duration-label").text(0);
          
          update();
      });

      //changed. now with parameter
      function update(slider,val) {
        //changed. Now, directly take value from ui.value. if not set (initial, will use current value.)
        var $amount = slider == 1?val:$("#amount").val();
        var $duration = slider == 2?val:$("#duration").val();

        /* commented
        $amount = $( "#slider" ).slider( "value" );
        $duration = $( "#slider2" ).slider( "value" );
         */

         $total = "$" + ($amount * $duration);
         $( "#amount" ).val($amount);
         $( "#amount-label" ).text($amount);
         $( "#duration" ).val($duration);
         $( "#duration-label" ).text($duration);
         $( "#total" ).val($total);
         $( "#total-label" ).text($total);

         $('#slider a').html('');
         $('#slider2 a').html('');
      }

PHP 5 File Upload

With PHP, it is easy to upload files to the server.
However, with ease comes danger, so always be careful when allowing file uploads!

Configure The “php.ini” File
First, ensure that PHP is configured to allow file uploads.
In your “php.ini” file, search for the file_uploads directive, and set it to On:

file_uploads = On

Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:

<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

Some rules to follow for the HTML form above:

Make sure that the form uses method=”post”
The form also needs the following attribute: enctype=”multipart/form-data”. It specifies which content-type to use when submitting the form
Without the requirements above, the file upload will not work.

Other things to notice:

The type=”file” attribute of the tag shows the input field as a file-select control, with a “Browse” button next to the input control
The form above sends data to a file called “upload.php”, which we will create next.

Create The Upload File PHP Script
The “upload.php” file contains the code for uploading a file:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
?>

PHP script explained:

$target_dir = “uploads/” – specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is not used yet (will be used later)
$imageFileType holds the file extension of the file
Next, check if the image file is an actual image or a fake image

Check if File Already Exists

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

Limit File Size
The file input field in our HTML form above is named “fileToUpload”.

Now, we want to check the size of the file. If the file is larger than 500kb, an error message is displayed, and $uploadOk is set to 0:

 // Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

Limit File Type
The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0:

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

Complete Upload File PHP Script
The complete “upload.php” file now looks like this:

 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

How to Create an Image in PHP

PHP makes it very easy to do many things needed on a website, among which is to create an image. The ability to generate an image in PHP can be useful if you want to do things like create CAPTCHA images, or even design a banner or logo on the fly the way some free blogging software do.

By the end of this tutorial, you will be able to create or modify an existing image using PHP, set the colours (“colors” in US English) of its background, the text and the lines you draw, write text to that image, draw a line and set its thickness. You will also be able to either send that image to a web browser or to save it as a file. Armed with this basic foundation, you will also be able to knowledgeably explore further and perform more complex operations on images using PHP if you wish.

Prerequisites
Note: If you are here looking for an article on how to create banners or logos for your website, and not strictly for an article on how to write PHP scripts to generate such images, you may find my article on How to Create a Logo for Your Site the Quick and Easy Way more relevant.

Basic PHP Knowledge
I will assume that you already have some basic knowledge of how to write PHP programs. If not, you may wish to check out my basic PHP tutorial, How to Program in PHP.

Your PHP Must Have Been Compiled with the GD Library
For any of the functions listed here to be available, your PHP interpreter must have been compiled with the GD library. If you are using the PHP provided by a commercial web host, this is probably already provided as a standard feature.

FreeType Must Be Compiled for TrueType Font Support
If you want TrueType font support, your PHP must have FreeType support compiled into it as well.

An Introduction to Creating an Image from Scratch Using PHP
The easiest way to understand how to create an image is by looking at some sample code.

<?php
$my_img = imagecreate( 200, 80 );
$background = imagecolorallocate( $my_img, 0, 0, 255 );
$text_colour = imagecolorallocate( $my_img, 255, 255, 0 );
$line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
imagestring( $my_img, 4, 30, 25, "thesitewizard.com", $text_colour );
imagesetthickness ( $my_img, 5 );
imageline( $my_img, 30, 45, 165, 45, $line_colour );

header( "Content-type: image/png" );
imagepng( $my_img );
imagecolordeallocate( $line_color );
imagecolordeallocate( $text_color );
imagecolordeallocate( $background );
imagedestroy( $my_img );
?>

The above code creates a 200×80 PNG image with a blue background and yellow text. It can be called from within your web page simply by referencing the php file. For example, if the PHP file that contains the above code is called myimage.php, then the HTML code to invoke it can simply be:

<img src="myimpage.php" alt="Image created by a PHP script" width="200" height="80">

Explanation of the Code
Creating the Image
The first thing the code does is to call the imagecreate() function with the dimensions of the image, namely its width and height in that order. This function returns a resource identifier for the image which we save in $my_img. The identifier is needed for all our operations on the image.

If the function fails for some reason, it will return FALSE. If you want your code to be robust, you should test for this. The demo code above doesn’t do any error checking, since it will clutter the example, making it harder to understand.

Using Colours in PHP
Before you can use any sort of colours in your image at all, you will need to allocate them. Colours are represented by three digits, known as the RGB value. The first digit denotes the red component, the second the green and the third blue, hence RGB, for Red-Green-Blue. These are the same colour values that you use for your web page as well as numerous other computer applications.

Colours are allocated using the imagecolorallocate() function. This function will automatically fill the background of the image with the colour the first time you call it, as well as return an identifier for that particular colour. Subsequent calls to imagecolorallocate() will simply create a colour identifier for your colour, without affecting your image background.

As you can see from the above code, my script allocates a blue identifier for the image, and in so doing, causes imagecolorallocate() to set the background to blue automatically. It also allocates a colour identifier for yellow and one for a shade of green. The latter two identifiers will be used later to write text and draw a line.

imagecolorallocate() returns FALSE if the function fails for any reason.

Writing Text to the Image
To write text to your image, you will need to use the imagestring() function. This function uses a set of built-in fonts to do the writing. The fonts have various sizes, ranging from 1 to 5, where 1 is the smallest font size and 5 the largest. The size of the font is specified in the second parameter to the function. In my example, I used font size 4.

The third and fourth parameters to imagestring() specify the x,y coordinate for the top left hand corner of the text. In the case of the example above, my text will begin 25 pixels from the top edge of the image, and 30 pixels from the left.

The fifth parameter is for the text to print, and the final parameter the colour of the text. This is the same colour that was allocated earlier using imagecolorallocate().

Drawing a Line and Setting the Thickness of the Brush
The imageline() function can be used to draw a line to the image. To set the thickness of the brush used to draw the line, you may want to call the imagesetthickness() function as I did in my example. The numeric parameter to imagesetthickness() is the thickness of the brush in pixels. In my code, I set it to 5 pixels. If you don’t call imagesetthickness(), the line will be 1 pixel thick.

The imageline() function is called with the start and end coordinates of the line, in x,y format. In my code, the line starts from 30,45 and ends on 165,45. That is, it will be a horizontal line 45 pixels from the top, starting 30 pixels from the left edge and ending 165 pixels from that same edge. Since $line_colour was set to a shade of green earlier, the line will be green.

How to Output the Image
Since the output of my example script is the image itself, I send an “image/png” content type header to the browser telling it that what follows are the bytes of a PNG image. The function imagepng() is then called to generate the necessary image from my $my_img image identifer. Since I called imagepng() without a second parameter, the function automatically sends its output to the browser. If you prefer to save your image, don’t call the header() function to output the header, and call imagepng() with the filename of the image for its second parameter, like the following:

imagepng( $my_img, "my_new_image.png" );

Your image does not have to be a PNG image. You can use imagegif() or imagejpeg() to create GIF and JPG images respectively. You should of course send the correct content type header for the type of image you are creating. For example, a jpeg image should have a content type of “image/jpeg” while a gif image “image/gif”. Note though that GIF support may or may not necessarily be compiled into the version of the GD library your web host is using, so if you’re not sure, use one of the other file formats.

Freeing Resources
On completion, the program releases the resources associated with the image by calling imagecolordeallocate() and imagedestroy(). I’m not sure if any of these calls are really necessary if your script is going to terminate immediately, since I don’t know if PHP automatically cleans up all these resources on the termination of the script. I like to put those calls there for completeness.

Modifying an Existing Image
In most cases, creating an image from scratch is overkill. For most web purposes, you can usually design the basic background of your image using a normal image editor and only add any additional text or graphical elements that need to be dynamically drawn using PHP. This allows you to speed up your scripts and reduce the resource consumption on your web server. It also lets you create your picture using professional picture designing tools.

To use an existing GIF, JPEG or PNG image as a canvas on which you add additional elements, use one of the following functions instead of imagecreate().

imagecreatefromgif ( string $filename )
imagecreatefromjpeg ( string $filename )
imagecreatefrompng ( string $filename )

For example, if you created a GIF file called “mytemplate.gif”, the function can be called as follows:

$myimage = imagecreatefromgif ( "mytemplate.gif" );

Like the basic imagecreate() function, these functions return FALSE if they fail to load the image for any reason.

Using TrueType Fonts
If you want to use a True Type font, you will need to use imagettftext() instead. For details on how to use this function, please consult the function’s manual page on php.net.

You should note a few things, though, before using this function:

Check that your web host has compiled FreeType support into PHP before you rely on this function.

Find out whether your web host’s PHP is using GD version 1 or 2. This affects a number of things, including the meaning of the font size parameter to the function (whether it means pixel size or point size).

Note that the coordinates for the text has a different starting point from imagestring(). That is, a coordinate like (say) 10,20 has a different meaning in the two functions.

Make sure the font you want exists on your web server. Remember that your web server is not the same as your computer. Just because a font like Arial exists on your computer does not mean that it exists on your server. If you have fonts that you created yourself, you may want to upload those to your web directory and use those instead. At least, that way, you have a guarantee that the font needed by your script exists.

The path setting to the font file is tricky, and depends on the version of the GD library your web server is using. One way around it is to specify the full path to the file on your server.

Drawing to Your Image
Besides the line drawing function used above, PHP has other functions that you can use. A complete list of functions, along with their descriptions, can be found on http://www.php.net/gd. To whet your appetite, functions include those that allow you to draw ellipses, arcs and polygons, change the style of your lines (to say dashed lines), and so on.

However, unless you have special reasons why you might want to dynamically draw complex pictures onto an image, you should consider creating your base image using a normal picture editor, load that image using a function like imagecreatefrompng(), and then only modifying small details with your script. Generating everything from scratch is unnecessary for most purposes, and can drain your web server resources.

How to Set a Cookie using PHP

Setting a cookie with PHP could not be easier, since PHP provides a function for you to do precisely that. The following code sets a cookie called “userlogin” with a value of “anonymous”:

$date_of_expiry = time() + 60 ;
setcookie( "userlogin", "anonymous", $date_of_expiry );

How to Create and Use Cookies in PHP
Cookies are bits of data that a web browser stores on your visitor’s computer. They can be very useful if you need to store things like your visitor’s preferences or login data (if your site has a membership facility) or other things that are specific to a particular visitor. This tutorial teaches you how you can set cookies, retrieve them and delete them using PHP.

Prerequisites
This tutorial assumes that you already know how to write scripts in PHP. You don’t have to be an expert, but some working knowledge is necessary or you will not be able to follow the discussion.

If you have do not know PHP, you may want to read a beginner’s tutorial first, like PHP Tutorial: How to Write Your First PHP Script and follow through with my other PHP tutorials.

How to Set a Cookie using PHP
Setting a cookie with PHP could not be easier, since PHP provides a function for you to do precisely that. The following code sets a cookie called “userlogin” with a value of “anonymous”:

$date_of_expiry = time() + 60 ;
setcookie( "userlogin", "anonymous", $date_of_expiry );

The code starts by calculating the expiry date of the cookie. Cookies have a limited lifespan. If you do not set an expiry date, the cookie will expire automatically when the user closes his/her web browser. The expiry date has to be in a special format, so it’s actually simplest to just use the time() function and work from there. This function returns the current date and time in the required format. My code adds 60 seconds to the existing time, effectively making the cookie last for only 1 minute.

The second line calls the setcookie() function, which does the actual work of setting the cookie in PHP. This is a built-in function in PHP. The first parameter (or argument) to setcookie() is the name that you want to give the cookie. It can be any name you like. In the example above, I gave the cookie the name “userlogin”.

The second parameter to the setcookie() function contains the actual data that you want saved. Again, this can be any data you like, although the maximum size of any cookie is 4 KB. This 4 KB includes things like the date of expiry, the name, and other cookie overheads, so you don’t really have all 4,096 bytes to work with. Note that cookies are not encrypted by default, so unless you encrypt your data yourself, you should not store any sensitive information in them.

The third argument is the date of expiry that was calculated earlier. As noted earlier, my code gives the cookie a very short lifespan. If you want your cookie to last longer, and you surely will, you will have to add the lifespan you want, converted to seconds, to the value returned by time().

Here’s an example of how to do that using a new variable, $number_of_days. Set the $number_of_days variable to the number of days you want your cookie to last, and the code below will calculate the actual date of expiry for you in a format suitable for passing to the setcookie() function.

$number_of_days = 30 ;
$date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ;

You will of course have to pass $date_of_expiry to setcookie() as its third parameter.

Making the Cookie Valid for Other Folders / Subdirectories
Although the above parameters to setcookie() are probably the most useful, there are additional parameters that you can use when calling the function. These parameters are optional, and can be omitted if you don’t need to use them.

As it stands, the cookie set in the above example will only be valid for the directory (or folder) where the current web document is kept as well as its descendant directories. For example, if your script was executed from the page http://www.example.com/members-only/login.php, then the cookie will be valid for any file in http://www.example.com/members-only/ and the subdirectories below it. If you want your cookie to be valid for every folder on your website, you will have to specify a fourth argument to setcookie().

setcookie( "userlogin", "anonymous", $date_of_expiry, "/" ) ;

The fourth parameter should be the top directory where you want to cookie to be available in. If it is set to “/” (the root folder of your website) as in the above example, it will be valid throughout your site. If you want the cookie to be available only in the “/secret” directory, pass “/secret” instead of “/” to the function.

Making the Cookie Valid in Other Sub-domains
If your cookie was set for a user accessing your site using (say) http://www.example.com, the cookie will not be valid if he/she goes to example.com even if both URLs resolve to the same site. To make it valid no matter which subdomain name of example.com is used, you will need to add a fifth parameter to setcookie().

setcookie( "userlogin", "anonymous", $date_of_expiry, "/", "example.com" );

Note that if you add a fifth parameter to the function, you must include the fourth parameter โ€” that is, the path or folder argument will no longer be optional. However, if you don’t really want to set the fourth parameter but only the fifth, you can pass an empty string (that is, “”) for the that parameter.

setcookie( "userlogin", "anonymous", $date_of_expiry, "", "example.com" );

Cookies Must Be Set Before Page Output
Since cookies are sent by the script to the browser in the HTTP headers, before your page is sent, they must be set before you even send a single line of HTML or any other page output. The moment you send any sort of output, you are signalling the end of the HTTP headers. When that happens, you can no longer set any cookie. If you try, the setcookie() function will return FALSE, and the cookie will not be sent. You will probably also get a PHP error message.

When setcookie() returns TRUE, the cookie was successfully sent to the web browser. This does not mean that the cookie has been successfully set, though, since it’s possible that the user has disabled cookie support. However, where the PHP interpreter is concerned, the cookie has been sent.

How to Get the Contents of a Cookie
Cookies set for a page can be retrieved from the variable $_COOKIE[‘cookie_name’] where ‘cookie_name’ is the name of the cookie you set earlier.

For example, if you wanted to display the value of the “userlogin” cookie, the following code should do the trick.

echo "Welcome back to the site" . $_COOKIE['userlogin'] ;

Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. Take the following non-working PHP code as an example:

/* WARNING: THIS WILL NOT WORK */
setcookie ( "userlogin", "anonymous", time()+60 );
echo "Value of userlogin: " . $_COOKIE['userlogin'] ;

Remember that cookies are sent in the HTTP headers, both to and by the web browser. At the time the above script runs, the web browser will have sent a request to your server for your script without including any “userlogin” cookie, since none has been set yet (unless one was already set in an earlier session). As such, when the PHP interpreter loads your script, it will create the $_COOKIE array without your “userlogin” cookie.

Testing for the existence of the cookie immediately after you set it in the same script is thus pointless. For example, the above code will print “Value of userlogin: ” and nothing else. This doesn’t mean that the cookie has not been sent โ€” it just means you can’t test it in the same script run. If you really need to test whether the cookie has been set, one way is to use JavaScript to check the cookie.

(Sites that want to check whether a cookie is successfully set are typically those that depend heavily on cookies to deliver content, such as those that only show certain pages to members paying a subscription fee. Since they require that a login cookie be present, they may want to check to see if cookie support has been disabled in the browser and warn the user if so. The most reliable way to perform such a check, at this time, is to set a cookie and then try to retrieve it.)

How to Delete a Cookie
Cookies can also be deleted. This is useful for situations such as when a user logs out of your site. To delete a cookie, call the setcookie() function again with the same name, folder and domain that you used earlier to set the cookie. However, instead of an expiry date set in the future, this time give an expiry date some time in the past.

$date_of_expiry = time() - 60 ;
setcookie( "userlogin", "anonymous", $date_of_expiry, "/", "example.com" );

The above code simply sets the expiry date 60 seconds in the past, effectively making the cookie no longer valid.

PHP Format bytes to KB,MB,GB

function formatBytes($bytes, $precision = 2) { 
    if ($bytes > pow(1024,3)) return round($bytes / pow(1024,3), $precision)."GB";
    else if ($bytes > pow(1024,2)) return round($bytes / pow(1024,2), $precision)."MB";
    else if ($bytes > 1024) return round($bytes / 1024, $precision)."KB";
    else return ($bytes)."B";
} 

Usage:

<?php
$filepath = 'uploads/somefile.txt';
$filesize = formatBytes($filepath);
echo $filepath.' ('.$filesize.')';
?>