Sunday 22 July 2012

Run php Script Automatically on Windows

It is quiet often that we need to execute/run some php script on some time interval at server side. And that php scripts should run automatically on windows server. On internet you will many aps and cron job simulator for windows but they are not necessary.

U can simply run the task automatically with windows using "Task Scheduler". It is inbuilt in windows and very user friendly in use.

PHP files can easily be run on Command Prompt ( More details click here ).
           ex. C:\Path\to\php.exe -f "C:\Path\to\file.php"    
      where -f is file attribute - parse and execute file.

If you wants to run script on windows hosting server then you can try creating a batch file script that runs instead. So, you would create a file called something like "myfile.bat" using Notepad, and you would use this code in that file:
C:\Path\to\php.exe -f "C:\Path\to\file.php"   
And you would use the Task Scheduler program to run the myfile.bat

To start the windows task scheduler - Start -> All Programs -> Accessories -> System Tools -> Task Scheduler.

Or type in search bar of windows : Task Scheduler.

Steps to Schedule PHP Script in Task Schedular
  1. Open Task Scheduler as shown above.
  2. In Task Scheduler, Click on "Action -> Create Task" from menubar.
  3. In "General" tab write "Name"- Name of Task and "Description" - Description for Task.



  4. In "Triggers" tab click on "New" and give triggering time as per requirement.



  5. In "Actions" tab click on "New" and select Action - Start Program (Default).
    And from browse button select your php.exe file from your php installed files.
    And in "argument" give file path with Option  ex. -f c:\pathToHtdocs\fileName.php (here -f is option).



  6. In "Conditions" tab you can set condition when to run task means about the your pc status like idle/on AC power, etc. I suggest you to leave it as default.



  7. In "Settings" tab you can specify some extra settings.  I suggest you to leave it as default.



  8. Finally As you done, Click on "Run" from "Action" to run it manually.



Command Line Options


Option
Long Option
Description
-a
--interactive
Run PHP interactively. For more information, see the Interactive shell section.
-b
--bindpath
Bind Path for external FASTCGI Server mode (CGI only).
-C
--no-chdir
Do not chdir to the script's directory (CGI only).
-q
--no-header
Quiet-mode. Suppress HTTP header output (CGI only).
-T
--timing
Measure execution time of script repeated count times (CGI only).
-c
--php-ini
Specifies either a directory in which to look for php.ini, or a custom INI file (which does not need to be named php.ini), e.g.:
$ php -c /custom/directory/ my_script.php
$ php -c /custom/directory/custom-file.ini my_script.php
If this option is not specified, php.ini is searched for in the default locations.
-n
--no-php-ini
Ignore php.ini completely.
-d
--define
Set a custom value for any of the configuration directives allowed in php.ini. The syntax is:
-d configuration_directive[=value]
# Omitting the value part will set the given configuration directive to "1"
$ php -d max_execution_time
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"
# Passing an empty value part will set the configuration directive to ""
php -d max_execution_time=
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""
# The configuration directive will be set to anything passed after the '=' character
$  php -d max_execution_time=20
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php
-d max_execution_time=doesntmakesense
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"
-e
--profile-info
Activate the extended information mode, to be used by a debugger/profiler.
-f
--file
Parse and execute the specified file. The -f is optional and may be omitted - providing just the filename to execute is sufficient.
Note:
To pass arguments to a script, the first argument must be --, otherwise PHP will interpret them as PHP options.
-h and -?
--help and --usage
Output a list of command line options with one line descriptions of what they do.
-i
--info
Calls phpinfo(), and prints out the results. If PHP is not working correctly, it is advisable to use the command php -i and see whether any error messages are printed out before or in place of the information tables. Beware that when using the CGI mode the output is in HTML and therefore very large.
-l
--syntax-check
Provides a convenient way to perform only a syntax check on the given PHP code. On success, the text No syntax errors detected in <filename> is written to standard output and the shell return code is 0. On failure, the text Errors parsing <filename> in addition to the internal parser error message is written to standard output and the shell return code is set to -1.
This option won't find fatal errors (like undefined functions). Use the -f to test for fatal errors too.
Note:
This option does not work together with the -r option.
-m
--modules
Example #1 Printing built in (and loaded) PHP and Zend modules
$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype
[Zend Modules]
-r
--run
Allows execution of PHP included directly on the command line. The PHP start and end tags (<?php and ?>) are not needed and will cause a parse error if present.
Note:
Care must be taken when using this form of PHP not to collide with command line variable substitution done by the shell.
Example #2 Getting a syntax error when using double quotes
$ php -r "$foo = get_defined_constants();"
PHP Parse error:  syntax error, unexpected '=' in Command line code on line 1
Parse error: syntax error, unexpected '=' in Command line code on line 1
The problem here is that sh/bash performs variable substitution even when using double quotes ". Since the variable $foo is unlikely to be defined, it expands to nothing which results in the code passed to PHP for execution actually reading:
$ php -r " = get_defined_constants();"
The correct way would be to use single quotes '. Variables in single-quoted strings are not expanded by sh/bash.
Example #3 Using single quotes to prevent the shell's variable substitution
$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
["E_ERROR"]=>
int(1)
["E_WARNING"]=>
int(2)
["E_PARSE"]=>
int(4)
["E_NOTICE"]=>
int(8)
["E_CORE_ERROR"]=>
[...]
If using a shell other than sh/bash, further issues might be experienced - if appropriate, a bug report should be opened at » http://bugs.php.net/. It is still easy to run into trouble when trying to use variables (shell or PHP) in commnad-line code, or using backslashes for escaping, so take great care when doing so. You have been warned!
Note:
-r is available in the CLI SAPI, but not in the CGI SAPI.
Note:
This option is only intended for very basic code, so some configuration directives (such as auto_prepend_file and auto_append_file) are ignored in this mode.
-B
--process-begin
PHP code to execute before processing stdin. Added in PHP 5.
-R
--process-code
PHP code to execute for every input line. Added in PHP 5.
There are two special variables available in this mode: $argn and $argi$argn will contain the line PHP is processing at that moment, while $argi will contain the line number.
-F
--process-file
PHP file to execute for every input line. Added in PHP 5.
-E
--process-end
PHP code to execute after processing the input. Added in PHP 5.
Example #4 Using the -B , -R and -E options to count the number of lines of a project.
$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";'
Total Lines: 37328
-S
--server
Starts built-in web server. Available as of PHP 5.4.0.
-t
--docroot
Specifies document root for built-in web server. Available as of PHP 5.4.0.
-s
--syntax-highlight and --syntax-highlighting
Display colour syntax highlighted source.
This option uses the internal mechanism to parse the file and writes an HTML highlighted version of it to standard output. Note that all it does is generate a block of <code> [...] </code>HTML tags, no HTML headers.
Note:
This option does not work together with the -r option.
-v
--version
Example #5 Using -v to get the SAPI name and the version of PHP and Zend
$ php -v
PHP 5.3.1 (cli) (built: Dec 11 2009 19:55:07)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies
-w
--strip
Display source with comments and whitespace stripped.
Note:
This option does not work together with the -r option.
-z
--zend-extension
Load Zend extension. If only a filename is given, PHP tries to load this extension from the current default library path on your system (usually /etc/ld.so.conf on Linux systems, for example). Passing a filename with an absolute path will not use the system's library search path. A relative filename including directory information will tell PHP to try loading the extension relative to the current directory.
--ini
Show configuration file names and scanned directories. Available as of PHP 5.2.3.
Example #6 --ini example
$ php --ini
Configuration File (php.ini) Path: /usr/dev/php/5.2/lib
Loaded Configuration File:         /usr/dev/php/5.2/lib/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)
--rf
--rfunction
Show information about the given function or class method (e.g. number and name of the parameters). Available as of PHP 5.1.2.
This option is only available if PHP was compiled with Reflection support.
Example #7 basic --rf usage
$ php --rf var_dump
Function [ <internal> public function var_dump ] {
- Parameters [2] {
Parameter #0 [ <required> $var ]
Parameter #1 [ <optional> $... ]
}
}
--rc
--rclass
Show information about the given class (list of constants, properties and methods). Available as of PHP 5.1.2.
This option is only available if PHP was compiled with Reflection support.
Example #8 --rc example
$ php --rc Directory
Class [ <internal:standard> class Directory ] {
- Constants [0] {
}
- Static properties [0] {
}
- Static methods [0] {
}
- Properties [0] {
}
- Methods [3] {
Method [ <internal> public method close ] {
}
Method [ <internal> public method rewind ] {
}
Method [ <internal> public method read ] {
}
}
}
--re
--rextension
Show information about the given extension (list of php.ini options, defined functions, constants and classes). Available as of PHP 5.1.2.
This option is only available if PHP was compiled with Reflection support.
Example #9 --re example
$ php --re json
Extension [ <persistent> extension #19 json version 1.2.1 ] {
- Functions {
Function [ <internal> function json_encode ] {
}
Function [ <internal> function json_decode ] {
}
}
}
--rz
--rzendextension
Show the configuration information for the given Zend extension (the same information that is returned by phpinfo()). Available as of PHP 5.4.0.
--ri
--rextinfo
Show the configuration information for the given extension (the same information that is returned by phpinfo()). Available as of PHP 5.2.2. The core configuration information is available using "main" as extension name.
Example #10 --ri example
$ php --ri date
date
date/time support => enabled
"Olson" Timezone Database Version => 2009.20
Timezone Database => internal
Default timezone => Europe/Oslo
Directive => Local Value => Master Value
date.timezone => Europe/Oslo => Europe/Oslo
date.default_latitude => 59.930972 => 59.930972
date.default_longitude => 10.776699 => 10.776699
date.sunset_zenith => 90.583333 => 90.583333
date.sunrise_zenith => 90.583333 => 90.583333

Thursday 12 July 2012

Regular Expression for .htaccess

Regular expressions are patterns, typically defined in some specific format which server can understand and handle them automatically for string processing.

It was invented and defined by the American mathematician Stephen Kleene.

Regular Expression is mainly used in RewriteRule in .htaccess to manipulate urls.

Before getting into deep First look at some definitions:


literalliteral is any character, which used in a searching or matching expression, for example, to find ind in windows/india the ind is a literal string - each character plays a part in searching, it is literally the string we want to find.
metacharactermetacharacter is one or more special characters that have a unique meaning and are NOT used as literals in the search expression, for example, the character ^ (circumflex or caret) is a metacharacter.
target stringThis term describes the string that we will be searching, that is, the string in which we want to find our match or search pattern.
search expressionMost commonly called the regular expression. This term describes the search expression that we will be using to search our target string, that is, the pattern we use to find what we want.
escape sequenceAn escape sequence is a way of indicating that we want to use one of our metacharacters as a literal. In a regular expression an escape sequence involves placing the metacharacter \ (backslash) in front of the metacharacter that we want to use as a literal, for example, if we want to find (s) in the target string window(s) then we use the search expression \(s\) and if we want to find \\file in the target string c:\\file then we would need to use the search expression \\\\file (each \ we want to search for as a literal (there are 2) is preceded by an escape sequence \).



Now look at some patterns / signs which has specific meaning to them



^ Denotes Beginning of strings. Means starting of string. i.e. Begin arguments with the processing symbol.
ex - "^a" string starting with "a"
$ Denotes end of the string. Its called terminating symbol.
ex. "ab$" means there is no more characters after $.
* Denotes zero or more occurance of preceding symbols.
ex. "ab*" matches a, ab, abb, abbb, ..... string ".*" matches as a wildcard
+ Denotes one or more occurance of preceding symbols.
ex - "ab+" matches ab, abb, abbb, ....
\ Denotes Escape symbols. To determine special/literals symbols like "! @ # $ , ." etc.
\. Denotes "." literal. It is used to match "."
! Denotes negative symbols, means excepts sign, negation sign.
ex - "!ab" matches everything except ab
? Denotes Optional.
ex - "ab?" matches "a" or "ab" and "a(ab)?" matches "a" or "aab"
{} Denotes minimum and/or maximum occurance of preceding symbols.
ex - "ab{3,5} matches strings abbb, abbbb, abbbbb"
        "a{3}" matches occurance of literal "a" exactly three times, means matches string "aaa"
        "a{3,}" matches occurance of literal a minimum 3 times, means it matches "aaa, aaaa, aaaa, aaa..."
() Denotes Grouping. Used to group the symbols/literals in string.
ex - "a(ab)*" matches "a, aab, aabab"
[] Denotes character class. Matches any character within brackets.
ex - [abc] matches "a" or "b" or "c"
[a-z] Here "-" denotes range between a to z. Which is used to denote lowercase letters.
similarly, [a-zA-Z] matches any small and uppercase letters
[0-9] matches any number between 0 to 9
| Denotes pipeline | logical or. Used for logical oring of symbols. ex - "(a|b)" matches "a" or "b".
. Denotes any single character. It is wildcard character
ex - ".*" matches any the character, wildcard for all character
- Denotes range in square brackets.
ex - "[0-9]" matches character between 0 and 9
^$ Denotes empty string. Starting is ending.
\s Denotes white space
-d To test if string is existing directory or not
-f To test if string is existing file or not
-s To test whether file has non zero value or not
Check your regular expression here : Regular Expression Testerpowered by http://www.zytrax.com
Usually Flags are added at the end of rewrite rules to tell apache server how to interpret and handle the rule.

[C] Chain - Instruct server to chain with other rules.
[F] Forbidden - Sends 403 header to the user.
[G] Gone - Denotes / gives no longer exist status message.
[H] Handler - Instruct to set handler
[L] Last - Denotes last rule and instruct server to stop rewriting after preceding directory is processed.
[N] Next - Denotes continue to rule until all rewriting directives are processed.
[P] Proxy - Instructs server to handle requests by mod_proxy, i.e., apache should grab the remote content specified in the substitution section and return it
[R] Redirect - Denotes redirect to modified new url.
[CO] Cookie - Set specified cookie
[NC] No Case - Denotes case insensitive. i.e. "No Case"
[NE] No Escape - Instructs the server to parse output without escaping characters.
[NS] No Subrequest - Ignore this rule if request is subrequest
[OR] Logical OR - Ties two expressions together such that either one proving true will cause the associated rule to be applied.
[PT] Pass Through - Instructs mod_rewrite to pass the rewritten URL back to Apache for further processing.
Use when processing URLs with additional handlers, e.g., mod_alias
[QSA] Query String Append - It used to add query string at the end of experssion [URL]
[S=x] Skip - instructs the server to skip the next "x" number of rules if a match is detected.
[E=variable:value] Environmental Variable - Instructs the server to set the environmental variable "variable" to "value".
[T=MIME-type] Mime Type - Force specified Mime Type

Monday 2 July 2012

.htacceess tricks and tips

.htaccess is a powerful and essential thing for your apache web server. When you place your custom .htaccess file into your web root directory it will automatically executed through your webserver. And help to protect your files, directories and sub directories with help of .htaccess rules.

.htaccess stands hypertext access file. .htaccess file that defaultly resides into your php installation directory. 

You can place custom .htaccess file into your web directory too for file, directory and sub directory protection. For that just create one .htaccess file with the rules inside it.

lets look at some tips and tricks inside it.

To comment code in .htaccess

Commenting is essential thing for understanding the code / rule that you have specified for your server protection. Comment can be done with the help of leading symbol "#" which is called pound sign. For multiple line comment multiple # are required in .htaccess.
Ex. 
                 # This is comment line leading with pound sign
                 # Line two with another pound sign 

Enable Basic Rewriting Mode/ Engine

Rewriting mode - "mod_rewrite" is not enable in many servers defaultly, so, first just use line to enable "mod_rewrite". This will help you to add rewriting rules to servers.
Ex. 
                  # Enable Rewrite Engin  
                     RewriteEngin on

Enable Symbolic Links (FollowSymLinks)

FollowSymLinks is a directive in your web server configuration that tells your web server to follow so called symbolic links. As one would expect, FollowSymLinks is an acronym for Follow Symbolic Links. FollowSymLinks is a very important setting that plays a role in your website security.

Simply saying to show your image path which is not actual done by FolloSymLinks enabling. For working of this required to turn on the AllowOverride Option.
Ex.
     Options +FollowSymLinks
Enable AllowOverride Option

When this directive is set to None, then .htaccess files are completely ignored. In this case, the server will not even attempt to read .htaccess files in the filesystem.

When this directive is set to All, then any directive which has the .htaccess Context is allowed in .htaccess files.
Ex.      
AllowOverride All | None | directive-type      
For more infor about allow override visit :             
 http://httpd.apache.org/docs/2.2/mod/core.html#allowoverride
Rename .htaccess File

To protect and to hide content of .htaccess file its essential to rename the file with other name.
Note: This directive must be placed in the server-wide configuration file or it will not work:
# rename htaccess files
AccessFileName ht.access
Note: If you rename your htaccess files, remember to update any associated configuration settings. For example, if you are protecting your htaccess file via FilesMatch, remember to inform it of the renamed files:
# protect renamed htaccess files
<FilesMatch "^ht\.">
Order deny,allow
Deny from all
</FilesMatch> 
Make Custom Directory Index File

It is possible to change your default index file to some other location even in some directory with the help of following code.
Ex.
     DirectoryIndex index.html index.php index.htm
Set Custom Error Page

Replicate the following patterns to serve your own set of custom error pages. Simply replace the “/errors/###.html” with the correct path and file name. Also change the “###” preceding the path to pages for other errors. 

Note: your custom error pages must be larger than 512 bytes in size or they will be completely ignored by Internet Explorer:
# serve custom error pages 
ErrorDocument 400 /errors/400.html 
ErrorDocument 401 /errors/401.html 
ErrorDocument 403 /errors/403.html 
ErrorDocument 404 /errors/404.html 
ErrorDocument 500 /errors/500.html
# provide a universal error documentRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^.*$ /dir/error.php [L]
Prevent Access to Specific File

To restrict access to a specific file, add the following code block and edit the file name, “secretfile.jpg”, with the name of the file that you wish to protect:
# prevent viewing of a specific file
<files secretfile.jpg>
order allow,deny
deny from all
</files>
Prevent access to multiple file types

To restrict access to a variety of file types, add the following code block and edit the file types within parentheses to match the extensions of any files that you wish to protect:
<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)quot;>
Order Allow,Deny
Deny from all
</FilesMatch>
Prevent Unauthorized Directory Browsing

Very essential for hiding your directory index view.

Prevent unauthorized directory browsing by instructing the server to serve a “xxx Forbidden – Authorization Required” message for any request to view a directory. For example, if your site is missing it’s default index page, everything within the root of your site will be accessible to all visitors. To prevent this, include the following htaccess rule:
# disable directory browsing
Options All -Indexes
Conversely, to enable directory browsing, use the following directive:
# enable directory browsing
Options All +Indexes
Likewise, this rule will prevent the server from listing directory contents:
# prevent folder listing
IndexIgnore * 
And, finally, the IndexIgnore directive may be used to prevent the display of select file types:
# prevent display of select file types
IndexIgnore *.wmv *.mp4 *.avi *.etc
Redirect From Old URL to New URL / Redirect from One Domain to Another With 301 Redirect

Redirect an entire site via 301:
# redirect an entire site via 301
redirect 301 / http://www.domain.com/
Redirect a specific file via 301:
# redirect a specific file via 301
redirect 301 /current/currentfile.html http://www.newdomain.com/new/newfile.html
Redirect an entire site via permanent redirect:
# redirect an entire site via permanent redirect
Redirect permanent / http://www.domain.com/
Redirect a page or directory via permanent redirect:
# redirect a page or directory
Redirect permanent old_file.html http://www.new-domain.com/new_file.html
Redirect permanent /old_directory/ http://www.new-domain.com/new_directory/
Redirect browser to https (ssl)

Add following snippet to your htaccess and redirect entire website to https.
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Replace .php file extension with any other like .htm or .html or .asp or .pl (Any Desired extension)

It is very convinient and easy to replace the .php extension for security. It can be easily be shown like .htm and .html or some else with following code.
AddType application/x-httpd-php .htmlor for .htm extension
AddType application/x-httpd-php .html 
If your extension of php file is .php5 then replace http-php with httpd-php5 .yourDesiered 
 If you are looking to replace only one page url, means only for one page say pageName.html or file.html file then it is convenient  to use file directory tag
<FIles pageName.html>
AddType application/x-httpd-php .html
</Files>
 Hide extension of files

Its also very easy to hide .php extension in your webpage. Add following code to your .htaccess file. Your page will look like www.yourDomain.com/pageName instead of www.yourDomain.com/pageName.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php