Thursday, 19 December 2013

php strtotime and mktime time functions

We have discussed about php's date and time functions . for refrence please see HERE
Now we are discussing two more functions . strtotime() and mktime() .

strtotime:- 

              This function will convert a string to timestamp format i.e. total number of seconds since 1st jan 1971 .
its usages are like :-

$var1 = strtotime("now");
$var2 = strtotime("10 September 2000");
$var3 = strtotime("+1 day");
$var4 = strtotime("+1 week");
$var5 = strtotime("+1 week 2 days 4 hours 2 seconds");
$var6 = strtotime("next Thursday");
$var7 = strtotime("last Monday");

echo date("Y-m-d H:i:s",$var1) . "<br/>";
echo date("Y-m-d H:i:s",$var2) . "<br/>";
echo date("Y-m-d H:i:s",$var3) . "<br/>";
echo date("Y-m-d H:i:s",$var4) . "<br/>";
echo date("Y-m-d H:i:s",$var5) . "<br/>";
echo date("Y-m-d H:i:s",$var6) . "<br/>";
echo date("Y-m-d H:i:s",$var7) . "<br/>";


explanation of above mentioned code is -
all $var1-7 variable will get timestamp according to string passed to the function  .
'now' will give current timestamp
'+1 day' will give tomorrow's timestamp i.e. +24 hours
and so on ..

also we can find the difference between two dates .
example : suppose we need to find the difference in days between '10 december 2012' and '12 july 1947' .  then we will write that program like this
$time1 = strtotime( "10 december 2012");
$time2 = strtotime( "12 july 1947");
$diff = $time1-$time2 ;
$no_of_days = $diff/86400 ;          // 1 day = 86400 seconds .

mktime :-

             This functions also create timestamp , but it take values as different parameters instead of one complete timed string .following is the syntax for mktime() function
mktime(hour,minutes,seconds,month,date,year,is_dst) ;
all parameters are optional .If we pass each parameter then it will show you the results. Just give a small try to the programs and will understand quickly , what it means . for example -
echo date("M-d-Y",mktime(0,0,0,12,36,2012)) . "<br>";
echo date("M-d-Y",mktime(0,0,0,14,1,2010)) . "<br>";
echo date("M-d-Y",mktime(0,0,0,1,1,1991)) . "<br>";
echo date("M-d-Y",mktime(0,0,0,1,1,99)) . "<br>";


Hope this post will help someone . Please ask me in comments if need any more help .



Thursday, 5 December 2013

advanced linux commands for quick system analysis

There are many linux commands which helps in many ways . If you are not linux administrator then these commands can help you in many ways .
Following commands are very important .

ifconfig
netsat
nslookup
who
w
who am i
whoami
uptime
wall
top
rsync
lsof
find 
whereis 
alias
unalias
df
su
diff
traceroute
iostat
mpstat
iftop

ifconfig :- 

this command is used to setup network details . Also we can see ip address of the system . there are many uses of this command . complete usage of this command can be seen use command  "man ifconfig " .
some uses of that commands are :-
ifconfig -a   --> will show all details of networks 
ifconfig eth0 --> will show details of fist ethernet network
 ifconfig eth0 down --> will take first ethernet down  or shutdown ethernet first
 ifconfig eth0  up -->  just opposite to the down command . it will start firsth ethernet
ifconfig eth0 172.18.100.4  netmask 255.255.255.255 -->  will set system ip to 172.18.100.4 and netmast to 255.255.255.255

netstat :-

 netstat is very important command to use on servers . it shows details about all port activities . which port are working and how many connections on the ports at any time . complete usage of this command can be seen using command "man netstat" .
Some uses of this commands are :-
netstat -a --> will show all port activities
netstat -at --> will show all TCP port activities
netstat -au --> will show all UDP port activities
netstat -l --> ports which are listening
netstat -tl --> TCP ports which are listening
netstat -s --> statistics for all ports
netstat -st --> statistics for alls TCP ports only
netstat -n --> will show hosts in numeric form i.e. in ip address forms
netstat -c --> continuously

use many commands combinations to get your desired results . like :-
netstat -atn | grep ":8080 "  --> it will show connections on only 8080 port
also
 netstat -tan | grep ':80 ' | awk '{print $6}' | sort | uniq -c
2 CLOSE_WAIT
140 CLOSING
13371 ESTABLISHED
1884 FIN_WAIT1
116 FIN_WAIT2
110 LAST_ACK
1 LISTEN
367 SYN_RECV
2168 TIME_WAIT

nslookup :-

this command is used to see dns entries of any domain or ip . like
nslookup pkonline.in --> it wil show details about pkonline.in , its ip and max available info
nslookup 1.1.1.1 --> will show details about this ip address
nslookup pkonline.in 2.2.2.2 --> will show details of pkonline.in from dns 2.2.2.2

 traceroute :-


this command is used to trace route between your system to destination . use :-
traceroute google.com --> will show all nodes of connectivity between your system and google.com servers .


iostat :-


this command is used to get all input and output statistics over all hard disks. to install this command in system use  "yum install sysstat " .uses :-
iostat --> will show average of input and output operation on every disk partition .
iostat 2 --> will show continuously current io statistics .


mpstat:-


mpstat shows output stats of every processor available .
mpstat , mpstat -P all --> will how all processors statistics .
mpstat -P 0 --> will show just first processor output statistics .


uptime :-

it will show uptime of your server . that means from how much time your server is running . This will reset after restart of server . to use it just write uptime in shell and hit enter

wall :-

this command is used to send a message to all shells of that system . Suppose many people are logged in on that server . If any one want to convey any message to all people then use wall .like :-
wall "dont delete anyfile from directory /home/parveen" --> the message will appear to every one logged in the server

w,who,whoami ,who am i :-

these three commands will provide you details about how many user are logged in the system and from how much time .
w --> will show details of all logged in users .
who -- > similar to w but show less details .
whoami --> will show you your username .
who am i --> will show you more details about your login .

top :-

top is most basic and mostly used command . it can provide complete overview of your system . This will show CPU usage , RAM usage , load on system ,which process is using maximum system .etc .

htop :-

slightly modified version of top command . It show use individually of every CPU .

rsync :- 

this command is used to make two directoris in sync with each other . This can be used over two different systems or on the same system itself .

rsynch -uar /home/parveen/   /home/backup/ --> this will send all updated file from /home/parveen/ directory to /home/backup directory .
rsync --rsh='ssh -p22' -aur root@192.168.0.1:/home/parveen/images/    /home/parveen/images/ --> this command will get all files from different machine to current machine .

lsof :- 

it will provide list of open files . there are many uses of this command . like :-
lsof --> list all opened files on the system
lsof /home/parveen/parveen.log --> will show open statistics for specific file  /home/parveen/parveen.log
lsof +D  /home/parveen/  --> will show files open under directory /home/parveen/
lsof -u root --> will show files opened by user root .
lsof -p 10 --> will specify opened file by specific process .i.e process id 10 .

find :- 

this command is used to search any file in the system .this can be used like that :-
find /home/ -name abc.txt --> this command will try to search file abc.txt under directory /home/ .
find / -name abc.txt --> this command will find abc.txt in the whole system .
find . -name abc.txt --> this command will find abc.txt in the current directory .

whereis :-

this command will search the location of commands . like:-
whereis cp --> will show the location of cp command . This may also search is binary files .

alias :-

this command is used to create aliasing for any command. this command is helping to create shortcuts of commands .like :-
alias pp="ls -lhtr" --> after this if you run pp command this it will show results equivalent to ls -lhtr

unalias:-

this command will remove the alias created .like:-
unalias pp --> now pp will no longer be any alias .

df :-

this command is used to show storage usage of all hard disk partitions . like :-
df -k --> this will show all partitions witgh there usage and free memory available in bits.
df -kh --> this will show size in MB KB and GB format .

du :-

this command is used to show disk usage by directories and files . this can be used in maby ways .
du --> will show directories which are using some space that means files which are non empty .
du -a --> this comamnd will show all files . also will show empty files
du -ah --> will show memory in human readle form like KB MB GB .
du -s --> will show summarised memory .
du -sh * --> will show memory taken by all files and directory at your current location with human readable form .

diff:-

this command is used to find difference between two files . for comparison of two files this is well structured command .
diff file1 file2 --> will print differences between this two files  .

Thursday, 21 November 2013

Basics commands of Unix / Linux

                                           

I will explain all basics of unix /linux here . Firstly basic directories of unix operating system .

** /bin  --> this directory contains all essential files for correct functioning of operating system .all users have permissions of these files .
** /home  in this directory all user's home directory resides . This is very commonly used directory .
** /var this directory contains all variables files like  logs , db directory etc .
** /etc all system configuration files are stored here .
** /dev  additional devices like cd-rom , pendrive , hard disk will found here .
** /sbin binary files , generaly super user uses these files .
** /tmp  all temporary files stay here .

These locations are by default . For our ease we can change them also and we can use it .

Linux is case sensitive .

Permissions :-  
As linux is multi-user operating system . Every file and directory have permissions defined for every user . Every file and directory have their owner . owner is a user . and also a group . group is group of users .

So we have three different type of permissions .
1) permissions given to owner
2) permissions given to group
3) permissions given to all other users .

And every file have three types of permissions
1) read permission -- those users who have read permission can read the file
2) write permission -- those users who have read permission can write into the file
3) execute permission -- user with this permission can execute the file .


Do  ls –l    in any directory
Then you will see something like
-rw-r--r--    1 root   root     13 June  5  11:21 file1
Here following will explain this .
r:readable,  w:writable,  x: executable

we can use two commands  chmod and chown to change permissions and owner of the file respectively .


Now about commands of unix .
One command consists of three parts  i.e command name , options , parameters .
example   # grep -i "abcds" file.txt
here ,
grep --> command name
i --> option
abcds and file.txt  are the parameters of the command .

Options will always start with - mark .


basic commands are :-
command name                     function

ls                                     show files in current position
 cd                                  change directory
 cp                                  copy file or directory
 mv                                 move file or directory
 rm                                 remove file or directory
 pwd                              show current position
 mkdir                           create directory
 rmdir                            remove directory
 less, more, cat          display file contents
 man                              display online manual
su                                   switch user
passwd                        change password
useradd                      create new user account
userdel                        delete user account
mount                         mount file system
umount                       unmount file system
df                                   show disk space usage
shutdown                   reboot or turn off machine
sort                            this command is used to sort 

to understand use of any command use man command
man <comand name >
e.g  man cp  -->> this comand will explain everything about cp


run some commands in your linux/unix machine then you will understand the difference .

ls
ls a
ls la
ls -Fa  
ls  .bash_profile
cp  .bash_profile  sample.txt
less  sample.txt  (note: to quit less, press q)
rm  sample.txt
mkdir linux
pwd
 cd linux
 pwd
 cd
 pwd
rmdir linux
ls  .bash_profile
 cp  .bash_profile  sample.txt
 less  sample.txt  (note: to quit less, press q)
 rm  sample.txt
df
df -k
df -hk

 Paths:-   relative and absolute path
Absolute Path :- 
Absolute pathe is address from root path . like 
/home/linux/
~/linux

Relative path :-
this path is relative to your current path 
. /    your current location
../   one directory above your current location
pwd    it will show you your current directory 

Run following command one-by-one and you will understand 
pwd 
cd .
 pwd
 cd ..
 pwd
 cd ..
 pwd 
 cd 
  mkdir mydir
 pwd 
 cd /Users/invite
 pwd 
 cd /Users
 pwd 
 cd /
 pwd 
 cd /Users/invite
cd ~/mydir 

Redirect, Append and Pipe 
We know output of a command is shown on the screen . i f we want to process the output then we will need some special parts .
Pipe  "|" :-
some commands need input from another command or any file .
"|" pipe will help u in giving output of one command as input to another command 

Append and redirect :-

'>' this sign will redirect output of a command to a file .
         '>>' this sign will append all output to the end of the file.




Please ask in comments if you need any more clearifications .



Thursday, 24 October 2013

php include all files from a directory

Include all files from a directory:-


Here is small code snippet to show that how we can include all files from a particular directory .

$all_files =  glob( "path to the directory/*") ;
foreach ( $all_files  as $filename)
{
include $filename;
}

If we try to explain it , then please understand glob() will return an array of all files on the path given as parameter .Rest everything is familiar with you all . foreach is the loop to iterate every element of any array . So by this we are including all files .

We can go in some tricky way also . example :-


Include all php files only :-

We can use regex syntax to achieve our goal . We will be able to include all php files only by following method

$all_files =  glob( "path to the directory/*.php") ;
foreach ( $all_files  as $filename)
{
include $filename;
}

Here only one parameter in the glob() function is changed and it will pic up all files which ends with .php extension .

Please ask question if you feel need of any clarification . 

Friday, 18 October 2013

php cache using APC cache in php and simple program to count pages views using apc cache


First of all we need to understand what is cache ?Cache is collection of items (data) stored in RAM . It is easily accessible . it does not require any I/O operation so its fast also .We use cache to optimize our application response time .

Cache in PHP :-

There are many ways we can use cache in php :-

      1)     Memcahce
       2)    APC


Here I will explain how to use APC .

APC is alternate php cache 

It is an extension to php . we can install it by following command .

             yum install pcre-devel
             yum install apc

Here are some predefined functions we need to use for APC .We can understand many functionalities just by name of the method .

apc_store () -- to store data in cache
apc_fetch() -- to fetch data from cache
apc_delete() -- to delete entries from cache
apc_inc() -- to increase integer value of any cache entry
apc_dec() -- to decrease integer value of any cache entry

Uses of functions :-

     apc_store('name','parveen');          //this will store name=’parveen ‘ in cache .
     apc_store('name','parveen',500);    // store in cache for 500 seconds.after that will be auto deleted 
     echo apc_fetch('name');                 // it will return ’parveen’
     apc_delete('name') ;                       // will delete from cache . if we try to fetch now then it will give error

example :-

apc_store('num',1);
apc_inc('num'); // now num is 2
apc_inc('num',5); //now num is 7
apc_dec('num'); // now num is 6
apc_dec('num',3); //now num is 3



Some points that we need to take care of :-

  1)  If memory of cache is full then it will delete all cache . so increase max limit size acording to your use . this can be achieved by making some entries in php.ini (php conf file)

   2) For better optimization we should set maximum time limit of cache . so that old entries get deleted automatically and free acquired space .


we can write following lines in php.ini file 

apc.shm_size="128M"       // this will set maximum size of cache to 128MB . default is 32 mb
apc.ttl="1800"                   // this will set maximum time to live for cache entry . default is unlimited


Simple page visits counter programs using cache :-

$key = 'visit_num';
if(apc_exists($key))
{
apc_inc($key, 1);

}
else
{
$count=1;
apc_store($key, $count);

}

and on hourly basis we can get that count from cache and store it in db . we can do it on daily basis or according to our convenience .

Wednesday, 16 October 2013

php using date and time for various purposes

We always need to deal with date and time in our programming specially when we are using php .
time() and date() these two functions are very important regarding our concern .

see following line of php code :-
$a = time();
time() function returns total number of seconds passed till date from 1st jan 1970 .
date() function is used to get date formatted according to our wish .
function date() can have two parametes:-
1) format of time stamp that we want to show
2) optional:- timestamp which we need to use to get date

first parameter is string that shows that exact output format  . some characters are usefull like
Y -- to show current year
m -- to show current month number
d -- to show today's dat
H -- current hour   24 hour format
i -- to show current minute
s -- to get current seconds
t -- shows number of days in current month  or last date of current month


following are some uses date() function :-

echo  date(""); // this will print nothing
echo date("Y-m-d H:i:s"); // this will show complete time stamp i.e.  2013-10-16 12:00:00 as your system time

echo date("Y-9-d 12:00:s"); // this will show  2013-9-16 12:00:45

these were examples of formatting of time stamp that we want to show ;

second parameter is time stamp itself .
for example :-

 echo date("Y-m-d H:i:s" , time());  // this will show  current time
  echo date("Y-m-d H:i:s" , time() + 500);  // this will show  time after 500 seconds

  echo date("Y-m-d H:i:s" , time() + 86400 );  // this will show tomorrow's time because 86400 is number of seconds in one day .

if we want to see time 5 days ahead  then we need to do is
  echo date("Y-m-d H:i:s" , time()  + 5*86400);

similarly if we want to see time 5 days back then we need to do is
  echo date("Y-m-d H:i:s" , time()  - 5*86400);


if we need to find how many days are in this month or any month then we use "t" in format string (first parameter) .
like

$number_of days_this month = date("t"); // it will give only last date of the month

Thanks and please ask in comment if you need any clearification .

Tuesday, 15 October 2013

PHP file to return image or return 1x1 pixel image

Using php file we can return image .  there are many benefits of this thing . we can keep count that how many times our image is fetched or from which us/ip that image is fetched.also we can change image from php code without changing in the real html file .

see following code

<img src="http://localhost/test.php"/>

if we want that test.php should return any image
following is the code snippet to return that image

test.php :-

$file = file_get_contents("full path to ur image fle");
$contenttype = "gif" ; // it is type or extension of image like jpeg for jpeg images and gif for .gif images
header("Content-type: image/$contenttype");
echo $file;


we need to  take care of some thing in this .
we should not print or echo any other variable or string from the same php file .then it will be showing some error and image will not be returned .

IF we want to return 1x1 image pixel then following is the code snippet .

header('Content-Type: image/gif');
header('Content-Length: 43');
echo base64_decode('R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==');



this code will provide us 1x1 image 

Thursday, 8 August 2013

python check if variable is empty

This is very easy to know in python that if any variable is empty or not

try to use :

if not ur_var:
     print "variable is empty 

get attention towards   not   keyword . This does all things .

This is equivalent to empty($ur_var)  in php

not keyword in python also checks for lists (array) , objects , strings , integrers , floats etc ..

example :

a= 0  or a = "" or a ={} or a= []
if not a :
    print "empty"

in all cases it will print empty .

Thursday, 23 May 2013

linux set ulimit

for setting ulimit u need to run following command

ulimit -n  10000  for setting limit to 10000

for soft files  
ulimit -Sn  10000

and for hard files
ulimit -Hn 10000


do it individually for all users

and this setting will be vanished after system restart

Saturday, 20 April 2013

virtual hosting in nginx

Virtual hosting in nginx is very simple :

see nginx.conf file 

one server block is generally available there .
see


server {
listen 80;
server_name _;

#charset koi8-r;

#access_log logs/host.access.log main;

location / {
   /root //html;
  index index.html index.htm index.php ;
}
}


this is default server setting. that means from all doamains this will work .

for virtual hosting define new server block 
 

:
server {
listen 80;
  server_name yourdomain.com;

#charset koi8-r;

#access_log logs/host.access.log main;

location / {
   /root /new_host;
  index index.html index.htm index.php ;
}
}





now settings have been changed

just restart nginx  and see
if traffic coming from  yourdomain.com  then it will point to /root/ new_host   directory .

else it will go to /root/html  directory and find related contents here.




thats it   . it was very simple



ask me if u want any further help .


Saturday, 13 April 2013

php call method froma string with parameters

very simple way to do that 


function abcd($parameter)
{
     return ture ;
}

$meth_str="abcd('ab')";
$res = false;
        $abc = '$res';
        $check = <<<bcd
if($meth_str)
{
        $abc= true;
} else
{
        $abc=false;
}
bcd;

        eval($check.";");    ///   that means $res=true;
     

Hope it helps
if need further help  comment here 


php check if IP lies in IP Range



first write function to check ip range

function Iprange_testing($iprange, $iptocheck)
{

    $ip = $iptocheck;


        list ($ip1, $ip2) = explode('-', $iprange);
        $ips = Array($ip,$ip1,$ip2);
        // sort ips and check if client ip is middle one
        natsort($ips);

        $sorted=implode("-", $ips);
        $ips=explode("-", $sorted);

        $ipcheck = true;

        if ($ips[1]!=$ip)
        {

            $ipcheck=false;
        }
return $ipcheck ;
    }

Now call this method

$res1  = Iprange_testing('192.168.1.10-192.168.1.100', '192.168.1.50');  //returns ture
$res2  = Iprange_testing('192.168.1.10-192.168.1.100', '192.168.1.101');  //returns false