Showing posts with label .htaccess. Show all posts
Showing posts with label .htaccess. Show all posts

Thursday 24 May 2018

Prevent caching using .htaccess

Sometimes your pages and scripts etc get cached forcing you to examine whether you really did save the file you're working on, or pressing ctrl-f5 to make sure you have the up to date version in your browser. To cut down on this confusion follow the instructions below.
cd myApp
touch .htaccess
Now add the following to the .htaccess file, which will prevent caching
<filesMatch "\.(html|js|css)$">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>
Remember to remove this when you've finished developing.

Wednesday 10 June 2015

Bootstrap formhandler calling class methods with JSON returned and processed

This entry offers a number of techniques through 4 files.

  • index.php contains a message alert which will only be displayed when there is a message to put in it. The forms use an action which contains the name of a class and method which will be used to process the results. There is also a call to custom.js
  • custom.js handles the form submissions and delivers the data returned to the page. It passes the form action and field content to formhandler.php. It receives JSON which then is either passed to a message alert or a data table.
  • formhandler.php receives the call from custom.js. This contains the form action and field content. It takes the form action and uses them to create calls to classes and methods named in the form action. For example and action of myclass/mymethod would be used to create calls similar to those below. The inclusion of the $_POST array allows the form field content to be passed to the class. The data returned is then passed back to custom.js for processing.
$myclass = new myclass($_POST);
$myclass->mymethod;

  • myclassname.class.php contains the example class and methods. The class receives the $_POST array and processes its content. There are 3 methods which demonstrate how to return a string, an array and an object.

This approach is a quick way of utilising many classes. It does not require a .htaccess file to simplify form actions and is flexible in its handling of returned data through JSON.
Have fun.

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Form handler for many PHP classes using jQuery</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
    body
    {
      margin-top:2em;
    }
    #message, #data-table
    {
      display:none;
    }
    </style>
  </head>
  <body>
    <div class="row">
      <div class="container">
        <div class="col-md-12">
          <div id="message" class="alert alert-success" role="alert"></div>
          <!-- <form action="myclassname/myclassmethod_string" method="POST"> -->
          <!-- <form action="myclassname/myclassmethod_array" method="POST"> -->
          <form action="myclassname/myclassmethod_object" method="POST">
            <div class="form-group">
              <label for="name"></label>
              <input type="text" name="name" class="form-control" />
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
          </form>
          <table id="data-table" class="table table-striped">
            <thead>
              <tr>
                <th>Name</th>
                <th>Age</th>
              </tr>
            </thead>
            <tbody>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="custom.js"></script>
  </body>
</html>

custom.js

(function()
{
  $('form').on('submit', function(event)
  {
    $.post('formhandler.php?action='+$(this).attr('action'), $(this).serialize(), function(data)
    {
      var json_obj = JSON.parse(data);
      if(json_obj.hasOwnProperty('message'))
      {
        $('#message').text(json_obj.message);
        $('#message').show();
        $('#message').fadeOut(3000);
      }
      else
      {
        $.each(json_obj, function(name,age)
        {
          $('#data-table > tbody').appendRow(name,age);            
        });
        $('#data-table').show();
      }
    });
    event.preventDefault();
  });
})();

$.fn.appendRow = function()
{
  var s = '<tr>';
  for (var i = 0; i < arguments.length; i++)
  {
    s += '<td>'+arguments[i]+'</td>';
  }
  s += '</tr>';
  return $(this).append(s);
}

formhandler.php

<?php
if(isset($_GET['action']))
{
$arr = split('/', $_GET['action']);
$class = $arr[0];
$method = $arr[1];
require_once $class.'.class.php';
if(class_exists($class))
{
$evalStr = '$'.$class.' = new '.$class.'($_POST);';
eval($evalStr);
if(method_exists($class, $method))
{
$evalStr = '$returnValue = $'.$class.'->'.$method.'();';
eval($evalStr);
}
else
{
$returnValue = 'Method does not exist';
}
}
else
{
$returnValue = 'Class does not exist';
}
}
else
{
$returnValue = 'No action given';
}

if(is_object($returnValue) || is_array($returnValue))
{
echo json_encode($returnValue);
}
else
{
$returnArr = array('message'=>$returnValue);
echo json_encode($returnArr);
}
?>

myclassname.class.php

<?php
class myclassname
{
private $pa;
function __construct($postArray = array())
{
$this->pa = $postArray;
}

function myclassmethod_string()
{
return 'Your name is '.$this->pa['name'];
}

function myclassmethod_array()
{
$myArr = array('Peter'=>'35', 'Ben'=>'37', 'Joe'=>'43');
return $myArr;
}

function myclassmethod_object()
{
$myObj = (object) array('Peter'=>'35', 'Ben'=>'37', 'Joe'=>'43');
return $myObj;
}

function __destruct()
{

}
}
?>

Friday 25 April 2014

Get .htaccess files working on Ubuntu after LAMP installation

Step 1. Configure Apache mod_rewrite
sudo a2enmod rewrite

Step 2. Within the file /etc/apache2/apache2.conf
Under the section labelled <Directory /var/www/>
Change the line
AllowOverride None
to
AllowOverride All

Step 3. Restart apache
sudo /etc/init.d/apache2 restart

Tuesday 24 September 2013

htaccess and HTML5 lines to force downloads

Here are a couple of tips to make life a little easier for your users with download links.
If you are running a Apache as your web server you can add the following line to your htaccess file:

AddType application/octet-stream .pdf

and/or ad a line like this within your HTML page:

<a href="document.pdf" download="document.pdf">Download the document</a>

In this case the pdf will automatically be downloaded when the user clicks on the link, rather than presenting them with a dialogue box asking them what to do.

Tuesday 7 August 2012

Hiding website directories from Johnnie Hacker using a .htaccess file

OK, here's the situation.
You're creating a website.
You want a directory called say 'classes'.
You need to access stuff contained in 'classes', but you don't want a user of your site to access the 'classes' directory through something like this http://www.yoursite.com/classes/
I'm assuming you've shown the good sense to use the apache web server here and that you haven't fallen foul of the Microsoft marketing machine or foolishly believed that you get what you pay for. That said, there are some good web servers other than apache.
I digress. Anyway, here is how to do it.


Go into the directory you wish to deny access to.
Create a file called .htaccess
Add a single line to the file namely:
deny from all
Save the file and restart apache.


If for some reason this doesn't work, it may be the way your apache server is set up.
Look for a file such as:
/etc/apache2/sites-available/default
That's if you're using a proper operating system. Goodness knows what it would be if you were using Windows.
In here you will see a few lines which look like this:

<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Change the line which says 'AllowOverride None' to 'AllowOverride All'.
Now restart apache again.

You can now add similar .htaccess files to any directories you want to control.