Hey, Would you like to work at Home ?? Just click here No need to pay, just register free and activate your account and get data Entry Work at your Home.
Showing posts with label Example. Show all posts
Showing posts with label Example. Show all posts

Tuesday, November 1, 2011

How to use a CIDR netmask to block an IP address range using .htaccess

This article explains why you must sometimes use CIDR netmask notation to ban an IP address range using Apache .htaccess, and how to do it. It is intended to supplement the basic Apache information about mod_access in the documentation at http://httpd.apache.org/docs/1.3/mod/mod_access.html.


An IP address is a 32-bit binary number that uniquely identifies a computer on the internet


32-bit binary is hard to remember : 11000000010000000000000000000000

Decimal notation isn't much easier: 3225419776

So it is usually written like this     : 192.64.0.0


You get this "dotted-quad notation" by breaking the 32 bits into 4 groups of 8 and then converting each group to decimal:


11000000010000000000000000000000
1926400

192.64.0.0


That makes it easier to remember, but it creates problems if you try to use it for calculations.


An IP address contains two pieces of information:



  1. The leftmost binary digits are the unique ID of the network (usually your Internet Service Provider, ISP) through which you are connected to the internet.

  2. The remaining binary digits are your unique ID as an individual user on that network.



The number of leftmost digits used for network ID is not the same for every network. In CIDR notation, the /nn part says how many of the leftmost bits indicate the network.



If the network uses exactly the leftmost 8, 16, or 24 bits for its ID, then the dividing line between network and user falls on one of the period boundaries of the dotted-quad notation, and one of the partial IP notations will work:


.htaccess partial IP addressEquivalent CIDR
deny from 192deny from 192.0.0.0/8
deny from 192.64deny from 192.64.0.0/16
deny from 192.64.0deny from 192.64.0.0/24

Each quad that you don't specify is treated as a wildcard that can take any value from 0 to 255. So the first example bans any IP address that starts with 192., followed by anything.


When to use CIDR notation


If the network doesn't use exactly 8, 16, or 24 bits for the network part of the IP address, the dividing line between network and user does not fall on a period boundary of dotted-quad notation, and you need to use a CIDR netmask.


Example CIDR/netmask:


192.64.0.0/10


This says the base address of the network is 192.64.0.0 and the first 10 bits are the network:


192 64 0 0 = 11000000 01000000 00000000 00000000


192 is the first 8 bits, but two more bits are part of the network ID, too. The 9th bit is 0 and the 10th is 1, and that is where the 64 comes from.


The full range of this network in quad notation is 192.64.0.0 - 192.127.255.255. Note that the 64 in the second position doesn't remain constant. The first 2 bits are always the same, but the righthand 6 will be different for different users.


The simple notations for an .htaccess ban won't work. Why not?



  • deny from 192 would ban the range 192.0.0.0 - 192.255.255.255, which will ban some users that are not coming from this network.

  • deny from 192.64 would ban the range 192.64.0.0 - 192.64.255.255, which is insufficient to ban all the users that are coming from this network.


So the answer is CIDR notation and an .htaccess line that says:


deny from 192.64.0.0/10


This says the base address is 192.64.0.0, and the first 10 bits identify the network (those are always the same for all users who are on that network).


To ban a specific IP range in htaccess



  1. Figure out, from your website access logs or elsewhere, the IP addresses you want to ban. Look them up in a WhoIs database such as http://whois.domaintools.com/.


  2. Determine whether you need to use a CIDR netmask. If the IP address range in the report looks like one of these, with each quad after the leading one(s) showing a rull range of 0-255, then you can use one of the simpler methods:



    192.0.0.0 - 192.255.255.255   -- Use deny from 192

    192.64.0.0 - 192.64.255.255   -- Use deny from 192.64

    192.64.128.0 - 192.64.128.255 -- Use deny from 192.64.128


  3. For anything else, you need CIDR. At Domain Tools, the CIDR netmask is sometimes shown in the report for that IP address, several lines down in the report. If it is, that's all you need. You're ready to create the line in your .htaccess file. Go to Step 5.


  4. If the CIDR wasn't given, you can calculate it yourself with a netmask calculator such as http://jodies.de/ipcalc.



    a) Enter the base (lowest) address. 



    b) You can simply determine the netmask (the /nn part) by trial and error, or you can calculate the minimum size to start with: take the rightmost nonzero quad of the base address and convert it to binary in your head or in Windows Calculator. Find the rightmost "1". The netmask will have to be sufficient to include all of the previous quads (at 8 bits each), plus all the digits in this quad up to its rightmost "1". That's the minimum. But it might include some of the trailing zeroes, too.



    c) Keep using trial and error for the netmask until HostMin and HostMax match the IP address range you saw in the Domain Tools report.



Note that final quads of 0 and 255 are reserved, so:



The calculated HostMin will be nnn.nnn.nnn.1,  not nnn.nnn.nnn.0

The calculated HostMax will be nnn.nnn.nnn.254 not nnn.nnn.nnn.255



The Hosts/Net line tells you how many users this network might have, which can help decide whether you really want to ban the entire range.




  1. Edit your public_html/.htaccess file to add the "deny from" line:




  1. Go to cPanel > File Manager.

  2. Navigate to the file public_html/.htaccess.

  3. Click on its file name (not the icon next to it).

  4. In the upper right corner of the screen, click Edit File.

  5. Make a backup copy: Copy all the text in the file, and save it into a file on your local computer so you can put it back into .htaccess if something goes wrong.

  6. Backup made? Ok, now you can edit the file. On a blank line in a part of the file that is not between HTML-style tags like <tag></tag>, type the line:



    deny from nnn.nnn.nnn.nnn/nn



    Replace the nnn's with the IP/netmask you calculated for this range.



    Further explanation: some lines of your .htaccess file might be contained between tags that look like HTML tags where the opening tag looks like <tag> and the closing tag looks like </tag>. Insert this new line in a part of the file that is not between any of these pairs of tags.



    Depending on what is in your .htaccess, you might need to use your judgment whether to use the order and allow directives that are also provided by mod_access. See the link to Apache at the top of this article for more information. That is beyond the scope of this article, and it will require your judgment. I'd suggest adding only the "deny from" line at first and seeing if it works as expected. What is expected: you can access your website; most other people can, too; when the denied party tries, your logs will show a result code of 403 Forbidden.



Wednesday, October 7, 2009

Flash image upload with PHP

Flash Code
System.security.allowDomain("www.tshirtsetc.co.uk");  import flash.net.FileReference;    // The listener object listens for FileReference events.  var listener:Object = new Object();    listener.onSelect = function(selectedFile:FileReference):Void {      upWin._x = 200;    selectedFile.upload("./upload.php");  };    // the file is starting to upload.  listener.onOpen = function(selectedFile:FileReference):Void {    _root.upWin.results_txt.text = String("Uploading " + selectedFile.name + "\n");  };    listener.onHTTPError = function(file:FileReference, httpError:Number):Void {      _root.upWin.results_txt.text = String("HTTPError number: "+httpError +"\nFile: "+ file.name);  }    listener.onIOError = function(file:FileReference):Void {   _root.upWin.results_txt.text = String("IOError: "+ file.name);  }    listener.onSecurityError = function(file:FileReference, errorString:String):Void {      _root.upWin.results_txt.text = String("SecurityError: "+SecurityError+"\nFile: "+ file.name);      }    listener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void {   upWin.loadBar._width = Number(bytesLoaded)/Number(bytesTotal)*300;  }    // the file has uploaded  listener.onComplete = function(selectedFile:FileReference):Void {    upWin.results_txt.text = String("Upload finished.\nNow downloading " + selectedFile.name + " to player\n");        if(position_txt.text == String("Front")){    attachMovie("trans", "transHolder", -16161, {_x:150, _y:120});     downloadImage1(selectedFile.name);    }else{    if(position_txt.text == String("Back")){     attachMovie("trans2", "transHolder2", -16162, {_x:450, _y:120});       downloadImage2(selectedFile.name);    }else{    if(position_txt.text == String("LSleeve")){     attachMovie("trans3", "transHolder3", -16163, {_x:150, _y:120});       downloadImage3(selectedFile.name);    }else{    if(position_txt.text == String("RSleeve")){     attachMovie("trans4", "transHolder4", -16164, {_x:450, _y:120});       downloadImage4(selectedFile.name);    }    }    }    }    Itotal_txt.text = Number(3.00);    _root.upWin._x = 2000;  };    var imageFile:FileReference = new FileReference();  imageFile.addListener(listener);     imageMovie.uploadBtn.onPress = uploadImage;  imageMovie.uploadBtn2.onPress = uploadImage;  imageMovie2.uploadBtn3.onPress = uploadImage;  imageMovie2.uploadBtn4.onPress = uploadImage;    // Call the uploadImage() function, opens a file browser dialog.  function uploadImage(event:Object):Void {    imageFile.browse([{description: "Image Files", extension: "*.jpg;*.gif;*.png"}]);  }    // If the image does not download, the event object's total property  // will equal -1. In that case, display am error message  function imageDownloaded(event:Object):Void {    if(event.total == -1) {      _root.upWin.results_txt.text = String("error");        }  }    // show uploaded image in scrollPane  function downloadImage1(file:Object):Void {   transHolder.umbongo.loadMovie("./uploaded/" + file);  }    // show uploaded image in scrollPane  function downloadImage2(file:Object):Void {   transHolder2.umbongo2.loadMovie("./uploaded/" + file);  }    // show uploaded image in scrollPane  function downloadImage3(file:Object):Void {   transHolder3.umbongo3.loadMovie("./uploaded/" + file);  }    // show uploaded image in scrollPane  function downloadImage4(file:Object):Void {   var randomNum:Number = Math.round(Math.random()*(10000-0))+0;   transHolder4.umbongo4.loadMovie("./uploaded/" + file);  }


Server Side - PHP Code
<?php    move_uploaded_file($_FILES['Filedata']['tmp_name'], './uploaded/'.$_FILES['Filedata']['name']);  copy('./uploaded/'.$_FILES['Filedata']['name'], './timeStamped/'.time().$_FILES['Filedata']['name']);    ?>


For more information goto http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001054.html

Monday, October 5, 2009

Mod-Rewrite Tricks and Tips - .Htaccess rewrites rules



If you really want to take a look, check out the mod_rewrite.c and mod_rewrite.h files.


Be aware that mod_rewrite (RewriteRule, RewriteBase, and RewriteCond) code is executed for each and every HTTP request that accesses a file in or below the directory where the code resides, so it’s always good to limit the code to certain circumstances if readily identifiable.


For example, to limit the next 5 RewriteRules to only be applied to .html and .php files, you can use the following code, which tests if the url does not end in .html or .php and if it doesn’t, it will skip the next 5 RewriteRules.




RewriteRule !\.(html|php)$ - [S=5]  
RewriteRule ^.*-(vf12|vf13|vf5|vf35|vf1|vf10|vf33|vf8).+$ - [S=1]

.htaccess rewrite examples should begin with:


Options +FollowSymLinks     
RewriteEngine On RewriteBase /

Require the www


Options +FollowSymLinks 
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.yourdomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]

Loop Stopping Code


Sometimes your rewrites cause infinite loops, stop it with one of these rewrite code snippets.


RewriteCond %{REQUEST_URI} ^/(stats/|missing\.html|failed_auth\.html|error/).* [NC]  
RewriteRule .* - [L]  
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]

Cache-Friendly File Names


This is probably my favorite, and I use it on every site I work on. It allows me to update my javascript and css files in my visitors cache’s simply by naming them differently in the html, on the server they stay the same name. This rewrites all files for /zap/j/anything-anynumber.js to /zap/j/anything.js and /zap/c/anything-anynumber.css to /zap/c/anything.css


RewriteRule ^zap/(j|c)/([a-z]+)-([0-9]+)\.(js|css)$ /zap/$1/$2.$4 [L]  

SEO friendly link for non-flash browsers


When you use flash on your site and you properly supply a link to download flash that shows up for non-flash aware browsers, it is nice to use a shortcut to keep your code clean and your external links to a minimum. This code allows me to link to site.com/getflash/ for non-flash aware browsers.


RewriteRule ^getflash/?$ http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash [NC,L,R=307]  

Removing the Query_String


On many sites, the page will be displayed for both page.html and page.html?anything=anything, which hurts your SEO with duplicate content. An easy way to fix this issue is to redirect external requests containing a query string to the same uri without the query_string.


RewriteCond %{THE_REQUEST} ^GET\ /.*\;.*\ HTTP/  
RewriteCond %{QUERY_STRING} !^$
RewriteRule .* http://www.askapache.com%{REQUEST_URI}? [R=301,L]

Sending requests to a php script


This .htaccess rewrite example invisibly rewrites requests for all Adobe pdf files to be handled by /cgi-bin/pdf-script.php


RewriteRule ^(.+)\.pdf$  /cgi-bin/pdf-script.php?file=$1.pdf [L,NC,QSA]  

Setting the language variable based on Client


For sites using multiviews or with multiple language capabilities, it is nice to be able to send the correct language automatically based on the clients preferred language.


RewriteCond %{HTTP:Accept-Language} ^.*(de|es|fr|it|ja|ru|en).*$ [NC]  
RewriteRule ^(.*)$ - [env=prefer-language:%1]

Deny Access To Everyone Except PHP fopen


This allows access to all files by php fopen, but denies anyone else.


RewriteEngine On  
RewriteBase /
RewriteCond %{THE_REQUEST} ^.+$ [NC]
RewriteRule .* - [F,L]

If you are looking for ways to block or deny specific requests/visitors, then you should definately read Blacklist with mod_rewrite. I give it a 10/10


Deny access to anything in a subfolder except php fopen


This can be very handy if you want to serve media files or special downloads but only through a php proxy script.


RewriteEngine On  
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+)/.*\ HTTP [NC]
RewriteRule .* - [F,L]

Require no www


Options +FollowSymLinks  
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^yourdomain\.com$ [NC]
RewriteRule ^(.*)$ http://yourdomain.com/$1 [R=301,L]

Check for a key in QUERY_STRING


Uses a RewriteCond Directive to check QUERY_STRING for passkey, if it doesn’t find it it redirects all requests for anything in the /logged-in/ directory to the /login.php script.


RewriteEngine On  RewriteBase /  
RewriteCond %{QUERY_STRING} !passkey
RewriteRule ^/logged-in/(.*)$ /login.php [L]

Removes the QUERY_STRING from the URL


If the QUERY_STRING has any value at all besides blank than the?at the end of /login.php? tells mod_rewrite to remove the QUERY_STRING from login.php and redirect.


RewriteEngine On  RewriteBase /  
RewriteCond %{QUERY_STRING} .
RewriteRule ^login.php /login.php? [L]

Fix for infinite loops


An error message related to this isRequest exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.or you may seeRequest exceeded the limit,probable configuration error,Use 'LogLevel debug' to get a backtrace, orUse 'LimitInternalRecursion' to increase the limit if necessary


RewriteCond %{ENV:REDIRECT_STATUS} 200  
RewriteRule .* - [L]

External Redirect .php files to .html files (SEO friendly)


RewriteRule ^(.*)\.php$ /$1.html [R=301,L]  

Internal Redirect .php files to .html files (SEO friendly)


Redirects all files that end in .html to be served from filename.php so it looks like all your pages are .html but really they are .php


RewriteRule ^(.*)\.html$ $1.php [R=301,L]  

block access to files during certain hours of the day


Options +FollowSymLinks  
RewriteEngine On
RewriteBase /
# If the hour is 16 (4 PM) Then deny all access
RewriteCond %{TIME_HOUR} ^16$
RewriteRule ^.*$ - [F,L]

Rewrite underscores to hyphens for SEO URL


Options +FollowSymLinks  
RewriteEngine On
RewriteBase /  
RewriteRule !\.(html|php)$ - [S=4]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5 [E=uscor:Yes]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4 [E=uscor:Yes]
RewriteRule ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3 [E=uscor:Yes]
RewriteRule ^([^_]*)_(.*)$ $1-$2 [E=uscor:Yes]  
RewriteCond %{ENV:uscor} ^Yes$
RewriteRule (.*) http://d.com/$1 [R=301,L]

Require the www without hardcoding


Options +FollowSymLinks  
RewriteEngine On RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.[a-z-]+\.[a-z]{2,6} [NC]
RewriteCond %{HTTP_HOST} ([a-z-]+\.[a-z]{2,6})$ [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]

Require no subdomain


RewriteEngine On  
RewriteBase /
RewriteCond %{HTTP_HOST} \.([a-z-]+\.[a-z]{2,6})$ [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]

Require no subdomain


RewriteEngine On  
RewriteBase /
RewriteCond %{HTTP_HOST} \.([^\.]+\.[^\.0-9]+)$
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Redirecting Wordpress Feeds to Feedburner


RewriteEngine On  
RewriteBase /
RewriteCond %{REQUEST_URI} ^/feed\.gif$
RewriteRule .* - [L]  
RewriteCond %{HTTP_USER_AGENT} !^.*(FeedBurner|FeedValidator) [NC]
RewriteRule ^feed/?.*$ http://feeds.feedburner.com/apache/htaccess [L,R=302]  
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Only allow GET and PUT Request Methods


RewriteEngine On  
RewriteBase /
RewriteCond %{REQUEST_METHOD} !^(GET|PUT)
RewriteRule .* - [F]

Prevent Files image/file hotlinking and bandwidth stealing


RewriteEngine On  
RewriteBase /
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?askapache.com/.*$ [NC]
RewriteRule \.(gif|jpg|swf|flv|png)$ /feed/ [R=302,L]

Stop browser prefetching


RewriteEngine On  
SetEnvIfNoCase X-Forwarded-For .+ proxy=yes
SetEnvIfNoCase X-moz prefetch no_access=yes  
# block pre-fetch requests with X-moz headers
RewriteCond %{ENV:no_access} yes
RewriteRule .* - [F,L]

Wednesday, September 2, 2009

PHP Fatal error : Out of memory Problem

PHP Fatal error: Out of memoryProblem. Let see how to solve this problem using various techniques.


The first thing I could think of was to restart the Apache httpd service. This immediately solved the issue. but I knew this is not a permanent fix for the issue. When I researched further, I got to know that the
error comes when certain PHP scripts require more memory than PHP was allowed by default.


So the solution is to increase the memory allocated for

PHP. How to do that? There are 4 possible ways -


1. Try looking for the php.ini file. You might find some redundant php.ini files, so make sure you have got the one which is actually being read by PHP. o be sure, create a new php file in your root folder, say “check.php” and have phpInfo(); within the php open and close tags. Execute this file to get the information on where the php.ini is residing. Normally it will be in /usr/local/lib/php.ini


Open the php.ini file in a text editor like TextPad (not in Notepad) and change the values for memory_limit. By default you should see memory_limit = 8M. Try changing it to 12M. If it doesn’t work, increase it to 16M or even 24M and so on.


2. In case you can’t find the php.ini file or do not have access to it, then open up the file which was throwing the error (test.php in my case) and add a line below just after ini_set(’memory_limit’, lsquo;12M’);


3. You can even consider adding a line in .htaccess file which will resolve the issue.
php_value memory_limit 32M


4. Or else, Try adding this line to your wp-config.php file:

Increasing memory allocated to PHP
define('WP_MEMORY_LIMIT', '32M');


If none of the above things solve your issue, then talk to you host.


Note: I am now worrying on which PHP script required an increase in memory allocation. The analysis won’t be so easy though.

Sunday, August 16, 2009

Optimize MySQL response time Techniques

High loaded / Heavy Traffic website can get slow to respond when a lot of different visitors visit sites querying the same mysql database server, making it slow to respond.


There is many ways you can improve mysql server response time:


- by modifying the cache size
- stopping dns resolution ....


Let's see how to implement that.


Sometime it may happen when we got troubles with our databases system. The mysql servers were slow to respond, but when we were logging into those machines, the load was fine, there were quite a few queries going on, but mysql didn't report it was overwhelmed.


1. Disable DNS Hostname Lookup

After seeking out the reason why the traffic wasn't going flawlessly, we determine that the mysql server was doing loads of name resolution queries!!!! What for? Why would that machine to a hostname resolution when only local network machines connect to it.


Seeking out in mysqld manual page, we found that this could be disabled by adding the --skip-name-resolve switch.


Under debian based system, such as ubuntu, knoppix ... and on most linux distribution, mysql configuration files are located in /etc/mysql/my.cnf.


In order to apply the --skip-name-resolve switch when you start mysqld, simply add:



[mysqld]
.....
......
skip-name-resolve



NOTE: When this option is activated, you can only use IP numbers in the MySQL Grant table.


With DNS hostname resolution:


date; mysql -u root -h 192.168.1.4 ; date
Fri Jul 21 23:56:58 CEST 2006
ERROR 1130 (00000): Host '192.168.1.3' is not allowed to connect to this MySQL server

Fri Jul 21 23:57:00 CEST 2006

it take 2-3 seconds before the server reply that the client IP is not allowed to connect.


Once DNS hostname lookup is disabled:


date; mysql -u root -h 192.168.1.4 ; date

Fri Jul 21 23:56:37 CEST 2006

ERROR 1130 (00000): Host '192.168.1.3' is not allowed to connect to this MySQL server

Fri Jul 21 23:56:37 CEST 2006

The server is replying instantly.


2. Activate Query Cache


After we resolved that issue, we started seeing the database server load increasing, the response time was good after the previous change, but now, we had to lighten a bit the mysql database server's load.


By checking the Query cache memory:



mysql> SHOW STATUS LIKE 'Qcache%';

we could see that no query cache memory was left. It was neccessary to increase the query cache size.


To get an overview of your query_cache variables state, use the following syntax:



mysql> SHOW VARIABLES LIKE '%query_cache%';

You need to have the query cache enabled in the first place (have_query_cache | YES) and make sure that query_cache_type is set to ON. This is usually activated by default on most linux distribution.


Now, you can increase the query cache size (let say you want 50M) using:



mysql> SET GLOBAL query_cache_size = 52428800;

If you want this setting to be kept when restarting mysql, add:



[mysqld]
...
...
query_cache_size = 52428800;


query_cache_type = 1



3. Summary:


After doing those changes, there were much more queries resolved from the cache, the effect was that the server was responding quickly without calculating too much has most of the queries where cached.

Wednesday, June 10, 2009

Protecting Script using SQL injection For MySQL with PHP

If you are running a dynamic website coded in PHP, chances are you'll be using
MySQL for storing content or information.


MySQL is very well suited for running anything from small personal websites to large corporate
systems, as it is both simple to use and scalable.  However, it is easy to overlook potential
security problems, especially if you don't have much experience.


Example


For instance, you may have a login script for a secure page of your site:



<?php

    
# Database connection code here



    
$result=mysql_query('select * from users where

    user="'
.$_POST['username'].'" and pass="'.$_POST['password'].'"');



    if(
mysql_num_rows($result)==0):

        
# Username or password incorrect

        
exit;

    endif;



    
# Send user protected page

?>



So for instance, if somebody sent " or ""=" for the username and the password,
the SQL query sent to the database would read: select * from users where user="" or
""="" and pass="" or ""=""
, which would allow access to the protected page without a
valid username or password.  This method is called SQL Injection.


Escaping


To prevent this from happening, the data provided by the user need to be 'escaped' - this means
putting backslashes in front of quotes, backslashes and other special characters.


This means that the MySQL engine will recognise that the quotes are part of the string, which
prevents SQL injection.


PHP has a built in function that is intended for escaping strings, called addslashes().


For instance, passing the form data from our example through addslashes would result in select * from users where user="\" or \"\"=\""
and pass="\" or \"\"=\""
being passed to the database, which can
be correctly interpreted by MySQL.


Magic Quotes


PHP has a feature called 'Magic Quotes', which automatically escapes get, post and cookie data, as if
addslashes had been called on them.  The idea of this is to prevent scripts written by
inexperienced coders being vulnerable to SQL injection.


However, there are several problems with this feature:



  • Addslashes doesn't escape data exactly right for MySQL databases. (The MySQL function
    MySQL_real_escape_string() should really be used instead)

  • Magic quotes can give programmers a false sense of security, and makes scripts completely
    vulnerable if the option is turned off.

  • It has the irritating side effect that form inputs used in other parts of scripts have slashes added to
    them, which can be very puzzling for beginners, and adds extra coding to remove them again.


Because of these reasons, magic quotes are turned off by default in PHP 5, although they are on
by default in PHP 4.


Best Practice

To keep your code portable and protected against vulnerabilities whether Magic Quotes is enabled or not,
it is best to use a function similar to the one below:



<?php

    
function proper_escape($datastring) {

        
# Strip slashes if data has already been escaped by magic quotes

        
if(get_magic_quotes_gpc()):

            
$datastring=stripslashes($datastring);

        endif;



        
# Escape string properly & return

        
return mysql_real_escape_string($datastring);

    }

?>


Call this when sending input data to the MySQL database like: proper_escape($_POST['username']).


Tuesday, January 20, 2009

MySQL Regular Expressions - Part 2


Regular Expressions in MySQL


Introduction



A very interesting and useful capability of MySQL is to incorporate Regular Expressions (regex) in SQL queries. The regular expression support in MySQL is extensive. Let's take a look at using Regular Expressions in queries and the supported metacharacters.



Using Regular Expressions in queries



A simple example of using Regular Expressions in a SQL query would be to select all names from a table that start with 'A'.



Code: SQL

SELECT name FROM employees WHERE name REGEXP '^A'




Your Ad Here


A slight modification in the above example to look for names starting with 'A' or 'D' or 'F' will look like this.


Code: SQL

SELECT name FROM employees WHERE name REGEXP '^(A|D|F)'



If we want to select all names ending with 'P', then the SQL query goes like this


Code: SQL

SELECT name FROM employees WHERE name REGEXP 'P$'



We can use much complex patterns in our SQL queries, but first let's have a look at various MySQL Regular Expression metacharacters.



Regular Expression Metacharacters



*
Matches zero or more instances of the string preceding it

+
Matches one or more instances of the string preceding it

?
Matches zero or one instances of the string preceding it

.
Matches any single character, except a newline

[xyz]
Matches any of x, y, or z (match one of enclosed characters)

[^xyz]
Matches any character not enclosed

[A-Z]
Matches any uppercase letter

[a-z]
Matches any lowercase letter

[0-9]
Matches any digit

^
Anchors the match from the beginning

$
Anchors the match to the end

|
Separates alternatives

{n,m}
String must occur at least n times, but not more than m times

{n}
String must occur exactly n times

{n,}
String must occur at least n times

[[:<:]]
Matches beginning of words

[[:>:]]
Matches ending of words

[:class:]
match a character class i.e.,



[:alpha:] for letters

[:space:] for whitespace

[:punct:] for punctuation

[:upper:] for upper case letters


Extras



MySQL interprets a backslash (\) character as an escape character. To use a backslash in a regular expression, you must escape it with another backslash (\\).



Your Ad Here



Whether the Regular Expression match is case sensitive or otherwise is decided by the collation method of the table. If your collation method name ends with ci then the comparison/match is case-insensitive, else if it end in cs then the match is case sensitive.



Examples



Checking only for numbers


Code: SQL

SELECT age FROM employees WHERE age REGEXP '^[0-9]+$'

/* starts, ends and contains numbers */



Contains a specific word, for example the skill PHP in skill sets


Code: SQL

SELECT name FROM employees WHERE skill_sets REGEXP '[[:<:]]php[[:>:]]'



Fetching records where employees have entered their 10-digit mobile number as the contact number.


Code: SQL

SELECT name FROM employees WHERE contact_no REGEXP '^[0-9]{10}$'





For more information refer http://dev.mysql.com/doc/refman/5.1/en/regexp.html

MySQL Regular Expressions - Part 1


A regular expression (regex) is a powerful way of specifying a complex search.



MySQL uses Henry Spencer's implementation of regular
expressions, which is aimed at conformance with POSIX
1003.2. MySQL uses the extended version.



This is a simplistic reference that skips the details. To get more exact
information, see Henry Spencer's regex(7) manual page that is
included in the source distribution. See section C Credits.



A regular expression describes a set of strings. The simplest regexp is
one that has no special characters in it. For example, the regexp
hello matches hello and nothing else.



Non-trivial regular expressions use certain special constructs so that
they can match more than one string. For example, the regexp
hello|word matches either the string hello or the string
word.



As a more complex example, the regexp B[an]*s matches any of the
strings Bananas, Baaaaas, Bs, and any other string
starting with a B, ending with an s, and containing any
number of a or n characters in between.




Your Ad Here


A regular expression may use any of the following special
characters/constructs:



^

Match the beginning of a string.

 
mysql> SELECT "fo\nfo" REGEXP "^fo$"; -> 0
mysql> SELECT "fofo" REGEXP "^fo"; -> 1


$

Match the end of a string.

 
mysql> SELECT "fo\no" REGEXP "^fo\no$"; -> 1
mysql> SELECT "fo\no" REGEXP "^fo$"; -> 0


.

Match any character (including newline).

 
mysql> SELECT "fofo" REGEXP "^f.*"; -> 1
mysql> SELECT "fo\nfo" REGEXP "^f.*"; -> 1


a*

Match any sequence of zero or more a characters.

 
mysql> SELECT "Ban" REGEXP "^Ba*n"; -> 1
mysql> SELECT "Baaan" REGEXP "^Ba*n"; -> 1
mysql> SELECT "Bn" REGEXP "^Ba*n"; -> 1


a+

Match any sequence of one or more a characters.

 
mysql> SELECT "Ban" REGEXP "^Ba+n"; -> 1
mysql> SELECT "Bn" REGEXP "^Ba+n"; -> 0


a?

Match either zero or one a character.

 
mysql> SELECT "Bn" REGEXP "^Ba?n"; -> 1
mysql> SELECT "Ban" REGEXP "^Ba?n"; -> 1
mysql> SELECT "Baan" REGEXP "^Ba?n"; -> 0


de|abc

Match either of the sequences de or abc.

 
mysql> SELECT "pi" REGEXP "pi|apa"; -> 1
mysql> SELECT "axe" REGEXP "pi|apa"; -> 0
mysql> SELECT "apa" REGEXP "pi|apa"; -> 1
mysql> SELECT "apa" REGEXP "^(pi|apa)$"; -> 1
mysql> SELECT "pi" REGEXP "^(pi|apa)$"; -> 1
mysql> SELECT "pix" REGEXP "^(pi|apa)$"; -> 0



Your Ad Here

(abc)*

Match zero or more instances of the sequence abc.

 
mysql> SELECT "pi" REGEXP "^(pi)*$"; -> 1
mysql> SELECT "pip" REGEXP "^(pi)*$"; -> 0
mysql> SELECT "pipi" REGEXP "^(pi)*$"; -> 1


{1}

{2,3}

The is a more general way of writing regexps that match many
occurrences of the previous atom.


a*

Can be written as a{0,}.
a+

Can be written as a{1,}.
a?

Can be written as a{0,1}.

To be more precise, an atom followed by a bound containing one integer
i and no comma matches a sequence of exactly i matches of
the atom. An atom followed by a bound containing one integer i
and a comma matches a sequence of i or more matches of the atom.
An atom followed by a bound containing two integers i and
j matches a sequence of i through j (inclusive)
matches of the atom.

Both arguments must be in the range from 0 to RE_DUP_MAX
(default 255), inclusive. If there are two arguments, the second must be
greater than or equal to the first.
[a-dX]

[^a-dX]

Matches
any character which is (or is not, if ^ is used) either a, b,
c, d or X. To include a literal ] character,
it must immediately follow the opening bracket [. To include a
literal - character, it must be written first or last. So
[0-9] matches any decimal digit. Any character that does not have
a defined meaning inside a [] pair has no special meaning and
matches only itself.


Your Ad Here

 
mysql> SELECT "aXbc" REGEXP "[a-dXYZ]"; -> 1
mysql> SELECT "aXbc" REGEXP "^[a-dXYZ]$"; -> 0
mysql> SELECT "aXbc" REGEXP "^[a-dXYZ]+$"; -> 1
mysql> SELECT "aXbc" REGEXP "^[^a-dXYZ]+$"; -> 0
mysql> SELECT "gheis" REGEXP "^[^a-dXYZ]+$"; -> 1
mysql> SELECT "gheisa" REGEXP "^[^a-dXYZ]+$"; -> 0


[[.characters.]]

The sequence of characters of that collating element. The sequence is a
single element of the bracket expression's list. A bracket expression
containing a multi-character collating element can thus match more than
one character, for example, if the collating sequence includes a ch
collating element, then the regular expression [[.ch.]]*c matches the
first five characters of chchcc.

[=character_class=]

An equivalence class, standing for the sequences of characters of all
collating elements equivalent to that one, including itself.

For example, if o and (+) are the members of an
equivalence class, then [[=o=]], [[=(+)=]], and
[o(+)] are all synonymous. An equivalence class may not be an
endpoint of a range.

[:character_class:]

Within a bracket expression, the name of a character class enclosed in
[: and :] stands for the list of all characters belonging
to that class. Standard character class names are:







Name Name Name
alnum digit punct
alpha graph space
blank lower upper
cntrl print xdigit


These stand for the character classes defined in the ctype(3) manual
page. A locale may provide others. A character class may not be used as an
endpoint of a range.


Your Ad Here

 
mysql> SELECT "justalnums" REGEXP "[[:alnum:]]+"; -> 1
mysql> SELECT "!!" REGEXP "[[:alnum:]]+"; -> 0


[[:<:]]

[[:>:]]

These match the null string at the beginning and end of a word
respectively. A word is defined as a sequence of word characters which
is neither preceded nor followed by word characters. A word character is
an alnum character (as defined by ctype(3)) or an underscore
(_).

 
mysql> SELECT "a word a" REGEXP "[[:<:]]word[[:>:]]"; -> 1
mysql> SELECT "a xword a" REGEXP "[[:<:]]word[[:>:]]"; -> 0





 
mysql> SELECT "weeknights" REGEXP "^(wee|week)(knights|nights)$"; -> 1


Wednesday, November 26, 2008

Date Diffrence In Days

Introduction

This code will give you the diffrence between the two dates in days.Some time it is required in the program to get diff. between two dates.It is so small and very efficient code.

//


// Any source code blocks look like this

//


t1="10/10/2006" ;

t2="15/10/2006";


//Total time for one day

var one_day=1000*60*60*24;

//Here we need to split the inputed dates to convert them into standard format

for furter execution
var x=t1.split("/");
var y=t2.split("/");
//date format(Fullyear,month,date)


var date1=new Date(x[2],(x[1]-1),x[0]);

var date2=new Date(y[2],(y[1]-1),y[0])
var month1=x[1]-1;
var month2=y[1]-1;

//Calculate difference between the two dates, and convert to days



_Diff=Math.ceil((date2.getTime()-date1.getTime())/(one_day));
//_Diff gives the diffrence between the two dates.





Friday, August 22, 2008

Mod Rewrite Tips and Examples

For example, to limit the next 5 RewriteRules to only be applied to .html and .php files, you can use the following code, which tests if the url does not end in .html or .php and if it doesn’t, it will skip the next 5 RewriteRules.



RewriteRule !\.(html|php)$ - [S=5]

RewriteRule ^.*-(vf12|vf13|vf5|vf35|vf1|vf10|vf33|vf8).+$ - [S=1]



.htaccess rewrite examples should begin with:


Options +FollowSymLinks



RewriteEngine On

RewriteBase /


Require the www


Options +FollowSymLinks

RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} !^www\.askapache\.com$ [NC]

RewriteRule ^(.*)$ http://www.askapache.com/$1 [R=301,L]


Loop Stopping Code


Sometimes your rewrites cause infinite loops, stop it with one of these rewrite code snippets.


RewriteCond %{REQUEST_URI} ^/(stats/|missing\.html|failed_auth\.html|error/).* [NC]

RewriteRule .* - [L]



RewriteCond %{ENV:REDIRECT_STATUS} 200

RewriteRule .* - [L]


Cache-Friendly File Names


This is probably my favorite, and I use it on every site I work on. It allows me to update my javascript and css files in my visitors cache’s simply by naming them differently in the html, on the server they stay the same name. This rewrites all files for /zap/j/anything-anynumber.js to /zap/j/anything.js and /zap/c/anything-anynumber.css to /zap/c/anything.css


RewriteRule ^zap/(j|c)/([a-z]+)-([0-9]+)\.(js|css)$ /zap/$1/$2.$4 [L]



SEO friendly link for non-flash browsers


When you use flash on your site and you properly supply a link to download flash that shows up for non-flash aware browsers, it is nice to use a shortcut to keep your code clean and your external links to a minimum. This code allows me to link to site.com/getflash/ for non-flash aware browsers.


RewriteRule ^getflash/?$ http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash [NC,L,R=307]



Removing the Query_String


On many sites, the page will be displayed for both page.html and page.html?anything=anything, which hurts your SEO with duplicate content. An easy way to fix this issue is to redirect external requests containing a query string to the same uri without the query_string.


RewriteCond %{THE_REQUEST} ^GET\ /.*\;.*\ HTTP/

RewriteCond %{QUERY_STRING} !^$

RewriteRule .* http://www.askapache.com%{REQUEST_URI}? [R=301,L]


Sending requests to a php script


This .htaccess rewrite example invisibly rewrites requests for all Adobe pdf files to be handled by /cgi-bin/pdf-script.php


RewriteRule ^(.+)\.pdf$ /cgi-bin/pdf-script.php?file=$1.pdf [L,NC,QSA]


Setting the language variable based on Client


For sites using multiviews or with multiple language capabilities, it is nice to be able to send the correct language automatically based on the clients preferred language.


RewriteCond %{HTTP:Accept-Language} ^.*(de|es|fr|it|ja|ru|en).*$ [NC]

RewriteRule ^(.*)$ - [env=prefer-language:%1]



Deny Access To Everyone Except PHP fopen


This allows access to all files by php fopen, but denies anyone else.


RewriteEngine On

RewriteBase /

RewriteCond %{THE_REQUEST} ^.+$ [NC]

RewriteRule .* - [F,L]


Deny access to anything in a subfolder except php fopen


This can be very handy if you want to serve media files or special downloads but only through a php proxy script.


RewriteEngine On

RewriteBase /

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+)/.*\ HTTP [NC]

RewriteRule .* - [F,L]


Require no www


Options +FollowSymLinks

RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} !^askapache\.com$ [NC]

RewriteRule ^(.*)$ http://askapache.com/$1 [R=301,L]


Check for a key in QUERY_STRING


Uses a RewriteCond Directive to check QUERY_STRING for passkey, if it doesn’t find it it redirects all requests for anything in the /logged-in/ directory to the /login.php script.


RewriteEngine On

RewriteBase /

RewriteCond %{QUERY_STRING} !passkey

RewriteRule ^/logged-in/(.*)$ /login.php [L]


Removes the QUERY_STRING from the URL


If the QUERY_STRING has any value at all besides blank than the?at the end of /login.php? tells mod_rewrite to remove the QUERY_STRING from login.php and redirect.


RewriteEngine On

RewriteBase /

RewriteCond %{QUERY_STRING} .

RewriteRule ^login.php /login.php? [L]


Fix for infinite loops


An error message related to this isRequest exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.or you may seeRequest exceeded the limit,probable configuration error,Use 'LogLevel debug' to get a backtrace, orUse 'LimitInternalRecursion' to increase the limit if necessary


RewriteCond %{ENV:REDIRECT_STATUS} 200

RewriteRule .* - [L]


External Redirect .php files to .html files (SEO friendly)


RewriteRule ^(.*)\.php$ /$1.html [R=301,L]


Internal Redirect .php files to .html files (SEO friendly)


Redirects all files that end in .html to be served from filename.php so it looks like all your pages are .html but really they are .php


RewriteRule ^(.*)\.html$ $1.php [R=301,L]



block access to files during certain hours of the day


Options +FollowSymLinks

RewriteEngine On

RewriteBase /

# If the hour is 16 (4 PM) Then deny all access

RewriteCond %{TIME_HOUR} ^16$

RewriteRule ^.*$ - [F,L]



Rewrite underscores to hyphens for SEO URL


Converts all underscores “_” in urls to hyphens “-” for SEO benefits… See the full article for more info.


Options +FollowSymLinks

RewriteEngine On

RewriteBase /



RewriteRule !\.(html|php)$ - [S=4]

RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5 [E=uscor:Yes]

RewriteRule ^([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4 [E=uscor:Yes]

RewriteRule ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3 [E=uscor:Yes]

RewriteRule ^([^_]*)_(.*)$ $1-$2 [E=uscor:Yes]



RewriteCond %{ENV:uscor} ^Yes$

RewriteRule (.*) http://d.com/$1 [R=301,L]



Require the www without hardcoding


Options +FollowSymLinks

RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} !^www\.[a-z-]+\.[a-z]{2,6} [NC]

RewriteCond %{HTTP_HOST} ([a-z-]+\.[a-z]{2,6})$ [NC]

RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]



Require no subdomain


RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} \.([a-z-]+\.[a-z]{2,6})$ [NC]

RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]


Require no subdomain


RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} \.([^\.]+\.[^\.0-9]+)$

RewriteRule ^(.*)$ http://%1/$1 [R=301,L]



Redirecting Wordpress Feeds to Feedburner


Full article:Redirecting Wordpress Feeds to Feedburner


RewriteEngine On

RewriteBase /

RewriteCond %{REQUEST_URI} ^/feed\.gif$

RewriteRule .* - [L]



RewriteCond %{HTTP_USER_AGENT} !^.*(FeedBurner|FeedValidator) [NC]

RewriteRule ^feed/?.*$ http://feeds.feedburner.com/apache/htaccess [L,R=302]



RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . /index.php [L]



Only allow GET and PUT Request Methods


Article: Request Methods


RewriteEngine On

RewriteBase /

RewriteCond %{REQUEST_METHOD} !^(GET|PUT)

RewriteRule .* - [F]


Prevent Files image/file hotlinking and bandwidth stealing


RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_REFERER} !^$

RewriteCond %{HTTP_REFERER} !^http://(www\.)?askapache.com/.*$ [NC]

RewriteRule \.(gif|jpg|swf|flv|png)$ /feed/ [R=302,L]


Stop browser prefetching


RewriteEngine On

SetEnvIfNoCase X-Forwarded-For .+ proxy=yes

SetEnvIfNoCase X-moz prefetch no_access=yes



# block pre-fetch requests with X-moz headers

RewriteCond %{ENV:no_access} yes

RewriteRule .* - [F,L]


Make a prefetching hint for Firefox.


Header append Link "

</index.htm>

; rel=prefetch"


This module uses a rule-based rewriting engine (based on a regular-expression parser) to rewrite requested URLs on the fly. It supports an unlimited number of rules and an unlimited number of attached rule conditions for each rule, to provide a really flexible and powerful URL manipulation mechanism. The URL manipulations can depend on various tests, of server variables, environment variables, HTTP headers, or time stamps. Even external database lookups in various formats can be used to achieve highly granular URL matching.


This module operates on the full URLs (including the path-info part) both in per-server context (httpd.conf) and per-directory context (.htaccess) and can generate query-string parts on result. The rewritten result can lead to internal sub-processing, external request redirection or even to an internal proxy throughput.


Further details, discussion, and examples, are provided in the detailed mod_rewrite documentation.

Friday, June 13, 2008

PDF Protection

Informations


Author: Klemen Vodopivec

License: Freeware

Description


This script allows to protect the PDF, that is to say prevent people from copying its content, print it or modify it.



SetProtection([array permissions [, string user_pass [, string owner_pass]]])



permissions: the set of permissions. Empty by default (only viewing is allowed).

user_pass: user password. Empty by default.

owner_pass: owner password. If not specified, a random value is used.



The permission array is composed of values taken from the following ones:




  • copy: copy text and images to the clipboard

  • print: print the document

  • modify: modify it (except for annotations and forms)

  • annot-forms: add annotations and forms


Remark: the protection against modification is for people who have the full Acrobat product.



If you don't set any password, the document will open as usual. If you set a user password, the PDF viewer will ask for it before displaying the document. The master password, if different from the user one, can be used to get full access.



Note: protecting a document requires to encrypt it, which increases the processing time a lot. This can cause a PHP time-out in some cases, especially if the document contains images or fonts.

Source








<?php

/****************************************************************************

* Software: FPDF_Protection                                                 *

* Version:  1.02                                                            *

* Date:     2005/05/08                                                      *

* Author:   Klemen VODOPIVEC                                                *

* License:  Freeware                                                        *

*                                                                           *

* You may use and modify this software as you wish as stated in original    *

* FPDF package.                                                             *

*                                                                           *

* Thanks: Cpdf (http://www.ros.co.nz/pdf) was my working sample of how to   *

* implement protection in pdf.                                              *

****************************************************************************/



require('fpdf.php');



class FPDF_Protection extends FPDF

{

    var $encrypted;          //whether document is protected

    var $Uvalue;             //U entry in pdf document

    var $Ovalue;             //O entry in pdf document

    var $Pvalue;             //P entry in pdf document

    var $enc_obj_id;         //encryption object id

    var $last_rc4_key;       //last RC4 key encrypted (cached for optimisation)

    var $last_rc4_key_c;     //last RC4 computed key



    function FPDF_Protection($orientation='P',$unit='mm',$format='A4')

    {

        parent::FPDF($orientation,$unit,$format);



        $this->encrypted=false;

        $this->last_rc4_key='';

        $this->padding="\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08".

                        "\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A";

    }



    /**

    * Function to set permissions as well as user and owner passwords

    *

    * - permissions is an array with values taken from the following list:

    *   copy, print, modify, annot-forms

    *   If a value is present it means that the permission is granted

    * - If a user password is set, user will be prompted before document is opened

    * - If an owner password is set, document can be opened in privilege mode with no

    *   restriction if that password is entered

    */

    function SetProtection($permissions=array(),$user_pass='',$owner_pass=null)

    {

        $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32 );

        $protection = 192;

        foreach($permissions as $permission){

            if (!isset($options[$permission]))

                $this->Error('Incorrect permission: '.$permission);

            $protection += $options[$permission];

        }

        if ($owner_pass === null)

            $owner_pass = uniqid(rand());

        $this->encrypted = true;

        $this->_generateencryptionkey($user_pass, $owner_pass, $protection);

    }



/****************************************************************************

*                                                                           *

*                              Private methods                              *

*                                                                           *

****************************************************************************/



    function _putstream($s)

    {

        if ($this->encrypted) {

            $s = $this->_RC4($this->_objectkey($this->n), $s);

        }

        parent::_putstream($s);

    }



    function _textstring($s)

    {

        if ($this->encrypted) {

            $s = $this->_RC4($this->_objectkey($this->n), $s);

        }

        return parent::_textstring($s);

    }



    /**

    * Compute key depending on object number where the encrypted data is stored

    */

    function _objectkey($n)

    {

        return substr($this->_md5_16($this->encryption_key.pack('VXxx',$n)),0,10);

    }



    /**

    * Escape special characters

    */

    function _escape($s)

    {

        $s=str_replace('\\','\\\\',$s);

        $s=str_replace(')','\\)',$s);

        $s=str_replace('(','\\(',$s);

        $s=str_replace("\r",'\\r',$s);

        return $s;

    }



    function _putresources()

    {

        parent::_putresources();

        if ($this->encrypted) {

            $this->_newobj();

            $this->enc_obj_id = $this->n;

            $this->_out('<<');

            $this->_putencryption();

            $this->_out('>>');

            $this->_out('endobj');

        }

    }



    function _putencryption()

    {

        $this->_out('/Filter /Standard');

        $this->_out('/V 1');

        $this->_out('/R 2');

        $this->_out('/O ('.$this->_escape($this->Ovalue).')');

        $this->_out('/U ('.$this->_escape($this->Uvalue).')');

        $this->_out('/P '.$this->Pvalue);

    }



    function _puttrailer()

    {

        parent::_puttrailer();

        if ($this->encrypted) {

            $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');

            $this->_out('/ID [()()]');

        }

    }



    /**

    * RC4 is the standard encryption algorithm used in PDF format

    */

    function _RC4($key, $text)

    {

        if ($this->last_rc4_key != $key) {

            $k = str_repeat($key, 256/strlen($key)+1);

            $rc4 = range(0,255);

            $j = 0;

            for ($i=0; $i<256; $i++){

                $t = $rc4[$i];

                $j = ($j + $t + ord($k{$i})) % 256;

                $rc4[$i] = $rc4[$j];

                $rc4[$j] = $t;

            }

            $this->last_rc4_key = $key;

            $this->last_rc4_key_c = $rc4;

        } else {

            $rc4 = $this->last_rc4_key_c;

        }



        $len = strlen($text);

        $a = 0;

        $b = 0;

        $out = '';

        for ($i=0; $i<$len; $i++){

            $a = ($a+1)%256;

            $t= $rc4[$a];

            $b = ($b+$t)%256;

            $rc4[$a] = $rc4[$b];

            $rc4[$b] = $t;

            $k = $rc4[($rc4[$a]+$rc4[$b])%256];

            $out.=chr(ord($text{$i}) ^ $k);

        }



        return $out;

    }



    /**

    * Get MD5 as binary string

    */

    function _md5_16($string)

    {

        return pack('H*',md5($string));

    }



    /**

    * Compute O value

    */

    function _Ovalue($user_pass, $owner_pass)

    {

        $tmp = $this->_md5_16($owner_pass);

        $owner_RC4_key = substr($tmp,0,5);

        return $this->_RC4($owner_RC4_key, $user_pass);

    }



    /**

    * Compute U value

    */

    function _Uvalue()

    {

        return $this->_RC4($this->encryption_key, $this->padding);

    }



    /**

    * Compute encryption key

    */

    function _generateencryptionkey($user_pass, $owner_pass, $protection)

    {

        // Pad passwords

        $user_pass = substr($user_pass.$this->padding,0,32);

        $owner_pass = substr($owner_pass.$this->padding,0,32);

        // Compute O value

        $this->Ovalue = $this->_Ovalue($user_pass,$owner_pass);

        // Compute encyption key

        $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");

        $this->encryption_key = substr($tmp,0,5);

        // Compute U value

        $this->Uvalue = $this->_Uvalue();

        // Compute P value

        $this->Pvalue = -(($protection^255)+1);

    }

}



?>

Example


This example shows how to allow only printing.









<?php

define('FPDF_FONTPATH','font/');

require('fpdf_protection.php');



$pdf=new FPDF_Protection();

$pdf->SetProtection(array('print'));

$pdf->Open();

$pdf->AddPage();

$pdf->SetFont('Arial');

$pdf->Write(10,'You can print me but not copy my text.');

$pdf->Output();

?>



View the result here.

Download


ZIP | TGZ

Friday, October 19, 2007

Get the date / time difference with PHP






Get the date / time difference with PHP




How do I calculate the difference between 2 time or date values with PHP?



It seems like a really popular question, I was so sure there would already be something ready-made out there. Searching the WWW with my favourite search engine, I was a bit surprised that it was clearly not the case -- okay, there were some example codes that do calculate the difference in time values, but they were not quite what I was hoping to find.

Before I paste my custom PHP function to calculate time differences, I need to explain that I have no use for this function myself. A disclaimer like that usually means I am writing it, testing it for a while and then I am done with it. In case you find a bug, I will appreciate it if you let me know, either via the comment link at the bottom of this page or by sending me an email.

Overview: get_time_difference()

array get_time_difference( string start, string end )

The function expects to be given 2 strings representing the start and end values of a time or date. These strings will be converted to Unix timestamps before the function works with them. Unix timestamp is the number of seconds since January 1, 1970 00:00:00 GMT.

The function returns an array that can be described like this:

Generic Code Example:



$diff['days'] = int
$diff['hours'] = int
$diff['minutes'] = int
$diff['seconds'] = int

or returns false on errors.

The custom PHP function: get_time_difference

PHP Code Example:

<?php
/**
 * Function to calculate date or time difference.

 * 
 * Function to calculate date or time difference. Returns an array or
 * false on error.

 *
 * @author       J de Silva                             <giddomains@gmail.com>
 * @copyright    Copyright &copy; 2005, J de Silva
 * @link         http://www.gidnetwork.com/b-16.html    Get the date / time difference with PHP

 * @param        string                                 $start
 * @param        string                                 $end
 * @return       array
 */
function get_time_difference$start$end )
{

    
$uts['start']      =    strtotime$start );
    
$uts['end']        =    strtotime$end );

    if( 
$uts['start']!==-&& $uts['end']!==-)
    {
        if( 
$uts['end'] >= $uts['start'] )

        {
            
$diff    =    $uts['end'] - $uts['start'];
            if( 
$days=intval((floor($diff/86400))) )

                
$diff $diff 86400;
            if( 
$hours=intval((floor($diff/3600))) )

                
$diff $diff 3600;
            if( 
$minutes=intval((floor($diff/60))) )

                
$diff $diff 60;
            
$diff    =    intval$diff );            
            return( array(
'days'=>$days'hours'=>$hours'minutes'=>$minutes'seconds'=>$diff) );

        }
        else
        {
            
trigger_error"Ending date/time is earlier than the start date/time"E_USER_WARNING );
        }

    }
    else
    {
        
trigger_error"Invalid date/time data detected"E_USER_WARNING );
    }
    return( 
false );
}
?>





Example PHP script using "get_time_difference"

Using justinhn's example, here is how you could use this function to get the time difference.

PHP Code Example:

<?php

// a START time value
$start '09:00';
// an END time value
$end   '10:30';


// what is the time difference between $end and $start?
if( $diff=@get_time_difference($start$end) )
{

  echo 
"Hours: " .
       
sprintf'%02d:%02d'$diff['hours'], $diff['minutes'] );
}
else
{

  echo 
"Hours: Error";
}

?>

The example code will result in this being output:

Generic Code Example:


Hours: 01:30
Your Ad Here