Monday, 25 November 2013

import CSV using php

//echo $_FILES["importBulkOrder"]["tmp_name"];
//die;
// path where your CSV file is located
define('CSV_PATH','D:/');

// Name of your CSV file
//$csv_file = CSV_PATH . "channelOrderingBulkUpload.csv";

$csv_file = $_FILES["importBulkOrder"]["tmp_name"];


$row = 1;
if (($handle = fopen($csv_file, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
       // echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            //echo $data[$c] . "<br />\n";
$col1 = $data[0];
             $col2 = $data[1];
             $col3 = $data[2];
$col4 = $data[3];
if($col1!=''&&$col2!=''&&$col3!=''&&$col4!=''){
$UpdateQuery ="update channel_detail_view set CMV_CHANNEL_DISPLAY_ORDER='".$col3."' where CMV_CHANNEL_CODE='".$col1."' and CMV_OPERATOR='".$col4."'";
mysql_query($UpdateQuery) or die(mysql_error());
}
        $data="";}
    }
    fclose($handle);
//die;
$mess="File data successfully imported.";
$url="channelDetails.php?mess=".base64_encode($mess);
redirectPage($url);
}

Sunday, 1 September 2013

some linux commands

1:-
   df -h  show the drive information how many drive exist in linux plateform as well as how many percent he fill.

2:- vmstat -s      , show the RAM status.

cp -r /var/lib/mysql      /extra    , copy file from one source to given destinaction.


3:- show free and used memory in the system:-

               cat  /proc/meminfo

OR
    # free
  # free -m
# free -mt
#free -gt


4:- linux finf out  current running version :-
   cat/proc/version


5:- Take mysql dump for perticular database:-
mysqldump -u root -padmin123 databasename >bacupfile,sql


6:- copy command
cp -avr /var/www/html/unified_HD_old  /data/WWW_bkup


7:-  open   /etc/security/limits.conf file
in vi editer and change configuration for increase user limit 
add this 


*       soft    nofile  16384
*       hard    nofile  16384

apache           soft    nproc            1457280

apache           hard    nproc           3000000

check user limit command in linux is ulimit -n

http://stackoverflow.com/questions/34588/how-do-i-change-the-number-of-open-files-limit-in-linux



8:- mpstat -P ALL

9:-SHOW STATUS WHERE `variable_name` = 'Threads_connected';

10:- /etc/init.d/httpd fullstatus | more

11:-  tail -f error_log
/var/log/httpd

12. using given command i can know thw replaction of id

ps ax | grep 80

ps ax | grep 3306


kill -9 28013

13:-  netstat -an |grep :3306 |wc -l

           netstat -an |grep :80 |wc -l

14:- /etc/init.d/httpd fullstatus | more
15:-  tail -f error_log

16:-
netstat -n | grep :80 |wc -l
1952

netstat -na|grep ESTABLISHED|wc -l
26

ps -ef|grep httpd|wc -l
62

netstat -anp | grep 3306 | wc -l


netstat -anp | grep 3306

show Mysql connection in Linux

netstat -anp | grep 3306 | grep EST | wc -l



17:-

compress file

 tar -zcvf mysqlbackup_8sep_14.tar.gz  MysqlBacup/


uncompress file 


tar -zxvf mysqlbackup_8sep_14.tar.gz 


17 (a):-  tail -f /data/httplog/access_log|grep "/unified/admin"
               cat  /data/httplog/access_log|grep "/unified/admin"

   using above command i can find data.

(B) :-  du -sh * given command i can see size of disk with directory.

(c):-  su - customscript  create new user in linux.



18a:-

find / -type f -name "*.php" -exec grep -il tapan {} \;








18:-

From Master:

1. Error log
2. my.cnf configuration file
3. output of following SQL statements:

TEE output.txt;
SHOW FULL PROCESSLIST;
SHOW GLOBAL VARIABLES;
SHOW GLOBAL STATUS;
SHOW MASTER STATUS;
SELECT sleep(60);
SHOW FULL PROCESSLIST;
SHOW MASTER STATUS;
SHOW GLOBAL STATUS;
SHOW SLAVE STATUS\G
SHOW ENGINE INNODB STATUS\G
\s
NOTEE;

From Slave:

1. Error log
2. my.cnf configuration file
3. output of following SQL statements:

TEE output2.txt;
SHOW FULL PROCESSLIST;
SHOW GLOBAL VARIABLES;
SHOW GLOBAL STATUS;
SHOW SLAVE STATUS\G
SELECT sleep(60);
SHOW FULL PROCESSLIST;
SHOW GLOBAL STATUS;
SHOW SLAVE STATUS\G
SHOW MASTER STATUS;
SHOW ENGINE INNODB STATUS\G
\s
NOTEE;


19.
        Change file permission in apache

chown -R apache:apache logs

chmod 755 logs


tar -xvzf html-2016-08-24.tar.gz

// check port listen or not
*  netstat -tulpn|grep 27017









========================================================================





 2  df -h
    3  crontab -e
    4  sh /data/MySQLdump.sh
    5  crontab -e
    6  sh /data/cronshfile/MySQLCronDBdump.sh
    7  telnet 172.31.22.60
    8  telnet 172.31.22.60 3306
    9  telnet 172.31.22.58 3306
   10  echo PAESSHSTART;df -P;echo PAESSHEND
   11  telnet 172.31.22.58 3306
   12  telnet 172.31.22.59 3306
   13  telnet 172.31.22.58 3306
   14  exit
   15  echo PAESSHSTART;df -P;echo PAESSHEND
   16  telnet 172.31.22.60 3306
   17  telnet 172.31.22.59 3306
   18  telnet 172.31.22.58 3306
   19  echo PAESSHSTART;df -P;echo PAESSHEND
   20  telnet 172.31.22.59 3306
   21  telnet 172.31.22.58 3306
   22  echo PAESSHSTART;df -P;echo PAESSHEND
   23  telnet 172.31.22.60 3306
   24  echo PAESSHSTART;df -P;echo PAESSHEND
    25  telnet 172.31.22.60 3306
   26  telnet 172.31.22.58  3306
   27  telnet 172.31.22.59  3306
   28  echo PAESSHSTART;df -P;echo PAESSHEND
   29  crontab -e
   30  sh /share/syncservice/sync_ondeck_aircel_hd/src/epgsync_common_hd.run.sh
   31  crontab -e
   32  sh /share/syncservice/src/epgsync_airteldth.run.sh
   33  sh /share/syncservice/sync_ondeck_aircel_hd/src/epgsync_ondeck.run.sh
   34  sh  /share/syncservice/src/epgsync_viddth.run.sh
   35  echo PAESSHSTART;df -P;echo PAESSHEND
   36  mysqldump -u root -h 172.31.22.59 -p unified >/home/unified_10June_15.sql
   37  mysql -u root -p
   38  mysqldump -u root -p --databases unified common_hd aircel dth_airtel onde
ck vid_dth >/home/db159Allbcup.sql
   39  cd /home
   40  rsync -r db159Allbcup.sql 172.31.22.60:/home
   41  mysql -u root -p
   42  echo PAESSHSTART;df -P;echo PAESSHEND
   43  crontab -e
   44  /data/cronshfile/MySQLCronDBdump.sh
   45  mysqldump -u neo -h172.31.22.58 -padmin123 unified > /data/databas
 
   50  service crond status
   51  systemctl status crond.service
   52   service crond status
   53  /etc/init.d/crond start
   54   service crond status
   55  crontab -e
   56  mysqldump -u root -p --databases common_hd aircel dth_airtel ondeck vid_d
th >/data/databaseBackup/unified/add159masterDB.sql
   57  cd /data/databaseBackup/unified
   58  mysqldump -u root -p --databases common_hd aircel dth_airtel ondeck vid_d
th >/data/databaseBackup/unified/add159masterDB.sql
   59  rsync -r add159masterDB.sql 172.31.22.60:/home
   60  mysql -u root -p
   61  echo PAESSHSTART;df -P;echo PAESSHEND
   62  crontab -e
   63  sh /share/syncservice/src/epgsync_airteldth.run.sh
   64  share/syncservice/sync_ondeck_aircel_hd/src/epgsync_common_hd.run.sh
   65  /share/syncservice/sync_ondeck_aircel_hd/src/epgsync_aircel.run.sh
   66  /share/syncservice/sync_ondeck_aircel_hd/src/epgsync_ondeck.run.sh
   67  /share/syncservice/src/epgsync_viddth.run.sh
   68  /share/syncservice/sync_ondeck_aircel_hd/src/epgsync_common_hd.run.sh
   69  echo PAESSHSTART;df -P;echo PAESSHEND
 
   488  rpm -e MySQL-server-advanced MySQL-shared-advanced MySQL-client-advanced
MySQL-shared-compat-advanced MySQL-devel-advanced
  489  rpm -e MySQL-server-advanced
  490  rpm -qa |grep MySQL
  491  rpm -e MySQL-client-advanced MySQL-devel-advanced
  492  rpm -qa |grep MySQL
  493  rpm -e MySQL-shared-advanced
  494  rpm -qa |grep MySQL
  495  rpm -e MySQL-shared-compat-advanced
  496  cd /root/tools/
  497  ll
  498  rpm -Uvh MySQL-*
  499  rpm -qa |grep MySQL
  500  /etc/init.d/mysql start
  501  mysql -u root -p
  502  rpm -qa |grep MySQL
  503  mysql -u root -p
  504  cd /root/
  505  ll
  506  mkdir tools
 
  ifconifg
  619  ifconfig
  620  ifconfig | more
  621  ping 172.31.22.1
  622  iptables -l
  623  iptables -L
  624  /etc/init.d/iptables stop
  625  ifconfig eth0 down
  626  exit
  627  route -n
  628  ifconfig
  629  vim /etc/sysconfig/network-scripts/ifcfg-eth0
  630  route -n
  631  route add 0.0.0.0 gw 172.31.22.1
  632  route -n
633  iptables -L -n
  634  getenforce
  635  ifconfig
  636  route -n
  637  service iptables status
  638  service iptables stop
  639  service iptables start
  640  service iptables status
  641  exit
  642  service network restart
  643  echo PAESSHSTART;df -P;echo PAESSHEND
881  curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install
.sh | bash
  882  exit
  883  command -v nvm
  884  nvm install node
  885  cat /etc/redhat-release
  886  uname -a
  887  node -v
  888  curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install
.sh | bash
  889  telent raw.githubusercontent.com 443
  890  yum install telnet
  891  cat /etc/redhat-release
  892  cat /etc/rees
  893  cat /etc/resolv.conf
  894  vim /etc/resolv.conf
  895  dig yahoo.com
  896  ifconfig -a
  897  dig yahoo.com
  898  yum install telnet
  899  yum clean all
  900  yum install telnet

  ssh root@172.31.22.91
  902  cd /etc/scripts/digiapis/
  903  ls -ltr
  904  cat package.json
  905  top -d 2
  906  node -v
  907  npm -v
  908  npm install pm2 -g
  909  pm2 install
  910  cat .ssh/id_rsa.pub
  911  ssh root@172.31.22.91
  912  ls -ltr
  913  ssh root@172.31.22.91
  914  mkdir -p /etc/scripts
  915  scp -r root@172.31.22.91:/etc/scripts/digiapis /etc/scripts/
  916  cd /etc/scripts/
  917  ll
  918  cd digiapis/

  921  ls -ltr
  922  npm install
  923  ls -ltr
  924  vim app.js
  925  pm2 start app.js -n digiapis -i 0
  926  pm2 save
  927  pm2 list
  928  ls -ltr
  929  tail -f /root/.pm2/logs/digiapis-*
  930  netstat -tulpn
  931  ls -ltr
  932  vim app.js
  933  netstat -tulpn
  934  ls -lt
  935  vim app.js
  936  vim config.js
  937  cat /etc/hosts
  938  vim /etc/hosts
  939  vim config.js
  940  vim /etc/hosts

 
 
  941  vim config.js
  942  cat /etc/hosts
  943  pm2 list
  944  pm2 reload digiapis
  945  ls -ltr
  946  vim config.js
  947  ifconfig
  948  cd
  949  cd tools/
  950  ll
  951  vim test.php
  952  php test.php
  953  vim test.php
  954  vi test1.php
  955  vim test1.php
  956  php test1.php
  957  date

 
   958  cd
  959  scp -r root@172.31.22.91:/etc/scripts/epgrecording /etc/scripts/

   960  cd /etc/scripts/
  961  ls -ltr
  962  cd epgrecording/
  963  ll
  964  rm -rf node_modules/
  965  npm install
  966  ls -ltr
  967  vim index.js
  968  crontab -e
  969  which node
  970  crontab -e
  971  vim scheduleworker.js
  972  pm2 start scheduleworker.js -n cathcup
  973  pm2 stop cathcup
  974  ls -ltr
  975  vim config.js
  976  yum install redis
  977  yum install make gcc wget
  978  cd
  979  cd tools/
  980  ll
  981  wget http://download.redis.io/releases/redis-3.0.2.tar.gz

   982  tar -zxvf redis-3.0.2.tar.gz
  983  cd redis-3.0.2
  984  ll
  985  make
  986  make install
  987  cd utils/
  988  ./install_server.sh
  989  /etc/init.d/redis_6379 start
  990  chkconfig redis on
  991  chkconfig redis_6379 on
  992  netstat -tulpn
  993  ps -wef|grep 17704
  994  cd /etc/scripts/
  995  ll
  996  cd epgrecording/
  997  ll
  998  vim config.js


 

 
 
 
 
 
 
 






------------------------------------------------------------------------------------------





Goal: Using netstat to view information about connections
Difficulty: Easy
Prerequisites: Access to a Linux console
Lets start with the basics. The "netstat" command is quite useful for checking connections to your machine. If we wanted to see ALL of the connections (which i really recommend you don't do unless you're trying to debug something and then you should probably pipe it to a file) we could use the "netstat -a" command.
Using "netstat -a" will give you something sort of like this (this is a segment of my server):
tcp  0  0 app.mydomain.com:http  93.184.216.119:16494  SYN_RECV
tcp  0  0 app.mydomain.com:http  93.184.216.119:18733  SYN_RECV
tcp  0  0 app.mydomain.com:http  93.184.216.119.dsl.mwe:64775 SYN_RECV
tcp  0  0 app.mydomain.com:http  93.184.216.119.threembb.:16490 SYN_RECV
tcp  0  0 app.mydomain.com:http  93.184.216.119:video-activmail SYN_RECV
tcp  0  0 app.mydomain.com:http  93.184.216.119:45025  SYN_RECV
tcp  0  0 app.mydomain.com:http  93.184.216.119:dvl-activemail SYN_RECV
tcp  0  0 app.mydomain.com:http  41-135-22-100.dsl.mwe:64774 SYN_RECV
As you can see it does name resolving for us and all that good stuff. Sometimes very hand but that's not what this is about. We want to get some solid numbers so we can take a broader perspective. To do this we can use the following command:
netstat -an | wc -l
This will show us a count of all connections that we presently have to our machine. But we can take this one step further even. Lets say you only wanted to see traffic comming across port 80 (standard http). We can grep our netstat then count it like so:
netstat -an | grep :80 | wc -l
Finally, lets take a look at the big picture in a category form. It is often extremely useful to see what those connections are doing, especially when you think you might just have tons of open connections that are idle and are trying to tweak your settings.
netstat -ant | awk '{print $6}' | sort | uniq -c | sort -n
So there you have it. A quick way to return counts on your connections in your linux environment. (Note the netstat command is standard on most operating systems, including windows, but you may need to use some other way to count your results)
Occasionally, when using netstat you may only care about ports that you are listening on. This is especially important if you are running a server that isn't behind a firewall because it helps you determine what you may be vulnerable to that you aren't aware of. using the netstat -l provides us with an excellent way to view this information.
root@nox [~]# netstat -l
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 *:mysql                     *:*                         LISTEN
tcp        0      0 *:submission                *:*                         LISTEN
tcp        0      0 *:pop3                      *:*                         LISTEN
tcp        0      0 localhost:783               *:*                         LISTEN
Another very common thing and powerful tool that netstat has built in is to show you network statistics in an overview fashion. If you're just trying to get a good idea about packet statistics then the netstat -s command may be what you're looking for. Here is some sample output. Keep in mind that netstat -s will show statistics broken down by protocol, so the fewer protocol stacks you are running the more compacted this summary will be.
netstat -s
Ip:
    139502653 total packets received
    28 with invalid addresses
    0 forwarded
    0 incoming packets discarded
    133312468 incoming packets delivered
    84570989 requests sent out
    366 outgoing packets dropped
    50 reassemblies required
    25 packets reassembled ok
    110 fragments received ok
    220 fragments created
Icmp:
    180285 ICMP messages received
    1586 input ICMP message failed.
    ICMP input histogram:
        destination unreachable: 9516
        timeout in transit: 331
        echo requests: 170151
        echo replies: 284
    172009 ICMP messages sent
    0 ICMP messages failed
    ICMP output histogram:
        destination unreachable: 1818
        echo request: 40
        echo replies: 170151
IcmpMsg:
        InType0: 284
        InType3: 9516
        InType8: 170151
        InType11: 331
        OutType0: 170151
        OutType3: 1818
        OutType8: 40
Tcp:
    1104118 active connections openings
    2918161 passive connection openings
    26607 failed connection attempts
    256788 connection resets received
    10 connections established
    128535136 segments received
    78146054 segments send out
    1645036 segments retransmited
    0 bad segments received.
    185776 resets sent
Udp:
    5125395 packets received
    1867 packets to unknown port received.
    0 packet receive errors
    5158639 packets sent
TcpExt:
    511 SYN cookies sent
    511 SYN cookies received
    12748 invalid SYN cookies received
    14894 resets received for embryonic SYN_RECV sockets
    159972 packets pruned from receive queue because of socket buffer overrun
    2 packets pruned from receive queue
    73 ICMP packets dropped because they were out-of-window
    1965839 TCP sockets finished time wait in fast timer
    78 time wait sockets recycled by time stamp
    36503 packets rejects in established connections because of timestamp
    2487605 delayed acks sent
    33477 delayed acks further delayed because of locked socket
    Quick ack mode was activated 45146 times
    233 times the listen queue of a socket overflowed
    233 SYNs to LISTEN sockets ignored
    9643039 packets directly queued to recvmsg prequeue.
    7969358 packets directly received from backlog
    3291115817 packets directly received from prequeue
    24087199 packets header predicted
    5532135 packets header predicted and directly queued to user
    30481401 acknowledgments not containing data received
    42935286 predicted acknowledgments
    814 times recovered from packet loss due to fast retransmit
    339835 times recovered from packet loss due to SACK data
    336 bad SACKs received
    Detected reordering 2070 times using FACK
    Detected reordering 854 times using SACK
    Detected reordering 10 times using reno fast retransmit
    Detected reordering 1840 times using time stamp
    3234 congestion windows fully recovered
    20175 congestion windows partially recovered using Hoe heuristic
    TCPDSACKUndo: 11509
    14757 congestion windows recovered after partial ack
    1004274 TCP data loss events
    TCPLostRetransmit: 54568
    129 timeouts after reno fast retransmit
    33120 timeouts after SACK recovery
    31346 timeouts in loss state
    885023 fast retransmits
    93299 forward retransmits
    337378 retransmits in slow start
    128472 other TCP timeouts
    TCPRenoRecoveryFail: 356
    35936 sack retransmits failed
    9 times receiver scheduled too late for direct processing
    57242284 packets collapsed in receive queue due to low socket buffer
    49286 DSACKs sent for old packets
    157 DSACKs sent for out of order packets
    95033 DSACKs received
    2091 DSACKs for out of order packets received
    39363 connections reset due to unexpected data
    35517 connections reset due to early user close
    12861 connections aborted due to timeout
    6 times unable to send RST due to no memory
    TCPSACKDiscard: 60
    TCPDSACKIgnoredOld: 2937
    TCPDSACKIgnoredNoUndo: 38596
    TCPSpuriousRTOs: 2925
    TCPSackShifted: 1905464
    TCPSackMerged: 2048679
    TCPSackShiftFallback: 995770
    TCPBacklogDrop: 41842
IpExt:
    InBcastPkts: 20
    InOctets: 60455654365
    OutOctets: 154094094438
    InBcastOctets: 6560
Another extremely useful tool for server administrators who are trying to track down processes that have run amuck is the netstat -p command. This returns the PID of the process that has the connection. It's also quite useful if you've got someone abusing a PID and you need to find out what IP it is so that you can get in touch with that individual or to block connections from that IP in the future. Here's some sample output from netstat -p.
netstat -p
tcp        0      0 localhost:56423  example.domain.com:https ESTABLISHED 27911/java
tcp        0     52 localhost:ssh    oh-76-76-76-76.dhcp.e:51653 ESTABLISHED 3344/sshd
tcp        0      0 localhost:imaps  76.sub-76-76-76.myvz:9258 ESTABLISHED 14501/dovecot/imap-




















Monday, 5 August 2013

set cron tab in linux

1. crontab -e command open crontab file save path of file like
0 0 * * * /usr/syncservice/src/catalog.run.sh
0 0 * * * /usr/syncservice/src/catalog_aircel.run.sh
0 0 * * * /usr/syncservice/src/epgsync.run.sh
0 0 * * * /usr/syncservice/src/epgsync_aircel.run.sh
0 0 * * * /usr/syncservice/src/epgsync_hd.run.sh
0 0 * * * /root/MySQLdump.sh


in the path like ex:-

0 0 * * * /root/MySQLdump.sh

in MySQLdump.sh we write give code of mysql dump:- dump will be created every mid night.

mysqldump -u root -padmin123 unified > /root/mysqlBackup/unified/$(date +\%Y-\%m-\%d_\%Hh\%M).sql

mysqldump -u root -padmin123 unified_hd > /root/mysqlBackup/unified_hd/$(date +\%Y-\%m-\%d_\%Hh\%M).sql






find in set.



                                $this->db->where("((FIND_IN_SET('ALL',VVM_REGION_RIGHTS) > 0 or FIND_IN_SET('".$this->usrCountry."',VVM_REGION_RIGHTS) > 0) and FIND_IN_SET('!".$this->usrCountry."',VVM_REGION_RIGHTS) = 0)");





Wednesday, 3 July 2013

date function in php

function datediff($interval, $date1, $date2)
{
 $seconds = strtotime($date2) - strtotime($date1);
   $date1=date("Y-m-d", strtotime($date1));
          $date2=date("Y-m-d",strtotime($date2));

          switch($interval)
      {
                  case "y":
                    list($year1, $month1, $day1) = split('-', $date1);
                    list($year2, $month2, $day2) = split('-', $date2);
                    $time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1));
                    $time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2));
                    $diff = $year2 - $year1;
                    if($month1 > $month2)
    {
                            $diff -= 1;
                         }
elseif($month1 == $month2)
{
                         if($day1 > $day2)
{
                          $diff -= 1;
                         }
elseif($day1 == $day2)
{
                         if($time1 > $time2)
{
                      $diff -= 1;
                         }
              }
          }
          break;
      case "m":
          list($year1, $month1, $day1) = explode('-', $date1);
          list($year2, $month2, $day2) = explode('-',$date2);
          $time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1));
          $time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2));
         
  $diff = ($year2 * 12 + $month2) - ($year1 * 12 + $month1);
          if($day1 > $day2)
  {
              $diff -= 1;
           }
  elseif($day1 == $day2)
  {
              if($time1 > $time2)
  {
                  $diff -= 1;
               }
          }
          break;
      case "w":
          $diff = floor($seconds / 604800);
          break;
      case "d":
          $diff = floor($seconds / 86400);
          break;
      case "h":
          $diff = floor($seconds / 3600);
          break;      
      case "i":
          $diff = floor($seconds / 60);
          break;      
      case "s":
          $diff = $seconds;
          break;      
  }
 
   return $diff;
}

datediff("d",$stdate1,$linePkg['PMV_CLOSE_DATE']);

Force download any file in php

//$file = $filepath . $filename;
$file = $downloadFilePath;
$logger->info("downloadFilePath::::".$downloadFilePath);
//CREATE/OUTPUT THE HEADER
header("Content-type: application/force-download");
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize($file));
header("Content-disposition: attachment; filename=\"".basename($file)."\"");
readfile($file);

Tuesday, 11 June 2013

SSH Configure in PHP

If i want to upload files in multi server then we will be use of SSH using of that i can upload a file in
simultaneously in  servers:-

SSH INSTILLATION link given below:-

http://php.net/manual/en/ssh2.installation.php

ex code here :-

create object :-
 $multiServerObj->UpdateUploadFileSsh($chann_icon_name,$_FILES["chan_icon"]["tmp_name"],'notuse',$deleteIcon);

Than

according to need use given  function:-



<?php
class SshUplaodImage{
function UploadFileSsh($chan_icon_name,$tempFileValue,$previewImg=null){
$host=$ip;
$user = 'root';
$pass = 'Matrix@123';
if($previewImg=='previewImg'){
$destDir = '/var/www/html/unified/admin/upload';
}else{
$destDir = '/var/www/html/unified/admin/upload/icon';

}
$HostServersCount = 4;

//$workDir = '../../tmp'; // define this as per local system
$workDir = '/var/www/html/unified/admin/includes/tmp'; // define this as per local system

$chan_icon_name;

// get temporary file name for the uploaded file
 $tmpName = basename($tempFileValue);


// copy uploaded file into current directory
if($TotalHost==4){
move_uploaded_file($tempFileValue, $workDir.'/'.$tmpName) or die("Cannot move uploaded file to working directory");
}else{
copy($tempFileValue, $workDir.'/'.$tmpName) or die("Cannot move uploaded file to working directory");
}

// open connection
for($i=0;$i<$HostServersCount;$i++){
if($i==0){
$host="211.01.02.50";
}else if($i==1){
$host="211.01.02.51";
}else if($i==2){
$host="211.01.02.54";
}else if($i==3){
$host="211.01.02.55";
}
$conn = ssh2_connect($host,22) or die ("Cannot initiate connection to host");

// send access parameters
ssh2_auth_password($conn, $user, $pass) or die("Cannot login");

// perform file upload
$upload = ssh2_scp_send($conn, $workDir.'/'.$tmpName, $destDir.'/'.$chan_icon_name, 0777);

// check upload status
// display message
if (!$upload) {
 echo "Cannot upload";
} else {
 echo "Upload complete";
}
ssh2_exec($conn, 'ls -al; echo "__COMMAND_FINISHED__"' );
//ssh2_exec($conn, 'exit');
}
// close the FTP stream
//ftp_close($conn);

// delete local copy of uploaded file
//die;
unlink($workDir.'/'.$tmpName) or die("Cannot delete uploaded file from working directory -- manual deletion recommended");

return $chann_icon_name ;
}

function UpdateUploadFileSsh($chan_icon_name,$tempFileValue,$previewImg=null,$deleteIcon=null){

$host=$ip;
$user = 'root';
$pass = 'Matrix@123';
if($previewImg=='previewImg'){
$destDir = '/var/www/html/unified/admin/upload';
}else{
$destDir = '/var/www/html/unified/admin/upload/icon';

}
$HostServersCount = 4;

//$workDir = '../../tmp'; // define this as per local system
$workDir = '/var/www/html/unified/admin/includes/tmp'; // define this as per local system

//echo $chan_icon_name;

// get temporary file name for the uploaded file
 $tmpName = basename($tempFileValue);


// copy uploaded file into current directory
if($TotalHost==4){
move_uploaded_file($tempFileValue, $workDir.'/'.$tmpName) or die("Cannot move uploaded file to working directory");
}else{
copy($tempFileValue, $workDir.'/'.$tmpName) or die("Cannot move uploaded file to working directory");
}

// open connection
for($i=0;$i<$HostServersCount;$i++){
if($i==0){
$host="211.01.02.50";
}else if($i==1){
$host="211.01.02.51";
}else if($i==2){
$host="211.01.02.54";
}else if($i==3){
$host="211.01.02.55";
}
$conn = ssh2_connect($host,22) or die ("Cannot initiate connection to host");

// send access parameters
ssh2_auth_password($conn, $user, $pass) or die("Cannot login");

if($deleteIcon!=null){
//unlink($destDir.'/'.$deleteIcon);

$sftp = ssh2_sftp($conn);
ssh2_sftp_unlink($sftp, $destDir.'/'.$deleteIcon);
}
if($previewImg!=null){
$sftp = ssh2_sftp($conn);
ssh2_sftp_unlink($sftp, $destDir.'/'.$deleteIcon);
}

// perform file upload
$upload = ssh2_scp_send($conn, $workDir.'/'.$tmpName, $destDir.'/'.$chan_icon_name, 0777);

// check upload status
// display message
if (!$upload) {
  "Cannot upload";
} else {
  "Upload complete";
}
ssh2_exec($conn, 'ls -al; echo "__COMMAND_FINISHED__"' );
//ssh2_exec($conn, 'exit');
}
// close the FTP stream
//ftp_close($conn);

// delete local copy of uploaded file
//die;
unlink($workDir.'/'.$tmpName) or die("Cannot delete uploaded file from working directory -- manual deletion recommended");

return $chann_icon_name ;
}
}

class uploadBuild{


function multiUploadAndroidBuild($chan_icon_name,$tempFileValue,$deleteIcon=null){

//$host=$ip;
$user ='root';
$pass = 'Matrix@123';
// $pass ='Cyberlinks';


$workDir = '/var/www/html/unified/admin/includes/tmp'; // define this as per local system
$destDir = '/var/www/html/unified/admin/upload/builds';
// get temporary file name for the uploaded file
$tmpName = basename($tempFileValue);


if($TotalHost==4){
move_uploaded_file($tempFileValue, $workDir.'/'.$tmpName) or die("Cannot move uploaded file to working directory");
}else{
copy($tempFileValue, $workDir.'/'.$tmpName) or die("Cannot move uploaded file to working directory");
}


$HostServersCount = 4;
// open connection
for($i=0;$i<$HostServersCount;$i++){
if($i==0){
$host="211.01.02.50";
//$host="211.01.02.45";
}else if($i==1){
$host="211.01.02.51";
}else if($i==2){
$host="211.01.02.54";
}else if($i==3){
$host="211.01.02.55";
}
$conn = ssh2_connect($host,22) or die ("Cannot initiate connection to host");

// send access parameters
ssh2_auth_password($conn, $user, $pass) or die("Cannot login");
//ssh2_auth_password($conn, 'root', 'Cyberlinks') or die("Cannot login");

if($deleteIcon!=null){
//unlink($destDir.'/'.$deleteIcon);

$sftp = ssh2_sftp($conn);
ssh2_sftp_unlink($sftp, $destDir.'/'.$deleteIcon);
}



// perform file upload
$upload = ssh2_scp_send($conn, $workDir.'/'.$tmpName, $destDir.'/'.$chan_icon_name, 0777);

// check upload status
// display message
if (!$upload) {
  "Cannot upload";
} else {
  "Upload complete";
}
ssh2_exec($conn, 'ls -al; echo "__COMMAND_FINISHED__"' );
//ssh2_exec($conn, 'exit');
}
// close the FTP stream
//ftp_close($conn);

// delete local copy of uploaded file
//die;
unlink($workDir.'/'.$tmpName) or die("Cannot delete uploaded file from working directory -- manual deletion recommended");


//return $chann_icon_name ;



}

}

?>

Wednesday, 29 May 2013

Master Slave Configuration in Mysql

CONTENT TAKEN BY GIVEN URL:-

http://erlycoder.com/43/mysql-master-slave-and-master-master-replication-step-by-step-configuration-instructions-

http://studioshorts.com/blog/2010/03/mysql-master-slave-replication-on-centos-rhel/






MySQL master-slave and master-master replication. Step by step configuration instructions.

If you are looking for the options to csale your MySQL installation you may be also interested in MySQL partitioning and subpartitioning. It may improve each node speed and capacity parameters.
One may say that there are a lot of MySQL replication manuals, but latest versions of MySQL server have changed the way how configuration should be applied. Most of the manuals do not reflect these changes. I want to describe some other aspects of configurations also. As far as there are a lot of good manuals about replication, I think there is no need to dove into details what is the replication. Just want to mention that this technique is usually used for load balancing on database servers. If you have a lot of read requests (most common for web applications) master-slave replication should suit your needs well. In this case you will do write transactions on master host and read requests on slave hosts, because data is populated from master to slave much faster than from slaves to master and to other slaves.
mysql master-slave replication
But sometimes you might have more write requests or may have other (application related) reasons to start another type of replication. You can see it on the next fugure and that is so called  master-master replication.
mysql master-master replication
In this article I will describe simple master-slave architecture with 2 hosts and simple master-master replication with the same 2 hosts. Our final goal is to configure master-master replication, what includes several sub-steps, so lets  start. Sure you should configure network services on both systems. For example:
Master 1/Slave 2 ip: 192.168.16.4
Master 2/Slave 1 ip : 192.168.16.5

Iptables rules for MySQL replication

It will be good practice to allow connections only from other nodes envolved into the replication and deny from other. By the way this will work good for some other services that are allowed to communicate nly with the known hosts. You can define port range like 1025:3306 (I am going to write more about iptables soon, so follow my blog on twitter).
  1. iptables -A INPUT -p tcp -s 192.168.16.4 --sport 3306 -d 192.168.16.5 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
  2. iptables -A OUTPUT -p tcp -s 192.168.16.5 --sport 3306 -d 192.168.16.4 --dport 3306 -m state --state ESTABLISHED -j ACCEPT

MySQL master-slave replication

Basically master-master replication consists of two master-slave replications. Now we will configure master-slave replication from the first server to the second one.
Create relication user on Master 1:
  1. mysql> grant replication slave on *.* to 'replication'@192.168.16.5 identified by 'slave';
And start master:
  1. mysql> start master;
Master 1 changes to /etc/my.cnf:
  1. [mysqld]
  2. datadir=/var/lib/mysql
  3. socket=/var/lib/mysql/mysql.sock
  4. old_passwords=1
  5. log-bin
  6. binlog-do-db=<database name>  # input the database which should be replicated
  7. binlog-ignore-db=mysql            # input the database that should be ignored for replication
  8. binlog-ignore-db=test
  9. server-id=1
  10. [mysql.server]
  11. user=mysql
  12. basedir=/var/lib
  13. [mysqld_safe]
  14. err-log=/var/log/mysqld.log
  15. pid-file=/var/run/mysqld/mysqld.pid
Slave 1 changes to /etc/my.cnf:
  1. [mysqld]
  2. datadir=/var/lib/mysql
  3. socket=/var/lib/mysql/mysql.sock
  4. old_passwords=1
  5. server-id=2
  6. [mysql.server]
  7. user=mysql
  8. basedir=/var/lib
  9. [mysqld_safe]
  10. err-log=/var/log/mysqld.log
  11. pid-file=/var/run/mysqld/mysqld.pid
Important! Pay attention that you should not configure master-host, master-user, master-password, master-port via my.cnf on slave server now.
On Master 1:
  1. mysql> show master status;
  2. +------------------------+----------+--------------+------------------+
  3. | File                   | Position | Binlog_Do_DB | Binlog_Ignore_DB |
  4. +------------------------+----------+--------------+------------------+
  5. |mysqld-bin.000012       |      106 | adam         |                  |
  6. +------------------------+----------+--------------+------------------+
  7. 1 row in set (0.00 sec)
On Slave 1:
  1. mysql> CHANGE MASTER TO MASTER_HOST='192.168.16.4', MASTER_USER='replication', MASTER_PASSWORD='password', MASTER_PORT=3306,MASTER_LOG_FILE='mysqld-bin.000012', MASTER_LOG_POS=106, MASTER_CONNECT_RETRY=10;
Attention! This will configure slave and server will remember settings, so this replaces my.cnf settings in latest versions of MySQL server.
Start slave on Slave 1:
  1. mysql> start slave;
  2. mysql> show slave statusG;
  3. *************************** 1. row ***************************
  4.                Slave_IO_State: Waiting for master to send event
  5.                   Master_Host: 192.168.16.5
  6.                   Master_User: slave
  7.                   Master_Port: 3306
  8.                 Connect_Retry: 10
  9.               Master_Log_File: mysqld-bin.000012
  10.           Read_Master_Log_Pos: 1368129
  11.                Relay_Log_File: mysqld-relay-bin.000005
  12.                 Relay_Log_Pos: 605530
  13.         Relay_Master_Log_File: mysqld-bin.000012
  14.              Slave_IO_Running: Yes
  15.             Slave_SQL_Running: Yes
  16.               Replicate_Do_DB:
  17.           Replicate_Ignore_DB:
  18.            Replicate_Do_Table:
  19.        Replicate_Ignore_Table:
  20.       Replicate_Wild_Do_Table:
  21.   Replicate_Wild_Ignore_Table:
  22.                    Last_Errno: 0
  23.                    Last_Error:
  24.                  Skip_Counter: 0
  25.           Exec_Master_Log_Pos: 1368129
  26.               Relay_Log_Space: 1367083
  27.               Until_Condition: None
  28.                Until_Log_File:
  29.                 Until_Log_Pos: 0
  30.            Master_SSL_Allowed: No
  31.            Master_SSL_CA_File:
  32.            Master_SSL_CA_Path:
  33.               Master_SSL_Cert:
  34.             Master_SSL_Cipher:
  35.                Master_SSL_Key:
  36.         Seconds_Behind_Master: 0
  37. Master_SSL_Verify_Server_Cert: No
  38.                 Last_IO_Errno: 0
  39.                 Last_IO_Error:
  40.                Last_SQL_Errno: 0
  41.                Last_SQL_Error:
  42.   Replicate_Ignore_Server_Ids:
  43.              Master_Server_Id: 1
  44. 1 row in set (0.02 sec)
Above highlighted rows must be indicate related log files and  Slave_IO_Running and   Slave_SQL_Running: must be to YES.

MySQL master-master replication

Master-master replication is actually two master-slave replications. This allows to make read and write transactions on both servers, as data propagation from master to slave goes very fast oposit to data propagation from slave to master which requires much more time. So, to create master-master replication we should now configure Master 2 - Slave 2 replication.
Create a replication slave account on Master 2 for Master 1/Slave 2:
  1. mysql> grant replication slave on *.* to 'replication'@192.168.16.4 identified by 'slave';
And start master:
  1. mysql> start master;
Master 2 changes to /etc/my.cnf:
  1. [mysqld]
  2. datadir=/var/lib/mysql
  3. socket=/var/lib/mysql/mysql.sock
  4. old_passwords=1
  5. log-bin
  6. binlog-do-db=<database name>  # input the database which should be replicated
  7. binlog-ignore-db=mysql            # input the database that should be ignored for replication
  8. binlog-ignore-db=test
  9. server-id=2
  10. [mysql.server]
  11. user=mysql
  12. basedir=/var/lib
  13. [mysqld_safe]
  14. err-log=/var/log/mysqld.log
  15. pid-file=/var/run/mysqld/mysqld.pid
Slave 2 / Master 1 changes to /etc/my.cnf:
  1. [mysqld]
  2. datadir=/var/lib/mysql
  3. socket=/var/lib/mysql/mysql.sock
  4. old_passwords=1
  5. log-bin
  6. binlog-do-db=<database name>  # input the database which should be replicated
  7. binlog-ignore-db=mysql            # input the database that should be ignored for replication
  8. binlog-ignore-db=test
  9. server-id=1
  10. [mysql.server]
  11. user=mysql
  12. basedir=/var/lib
  13. [mysqld_safe]
  14. err-log=/var/log/mysqld.log
  15. pid-file=/var/run/mysqld/mysqld.pid
Important! And again you should not configure master-host, master-user, master-password, master-port via my.cnf on slave server now.
On Master 2:
  1. mysql> show master status;
  2. +------------------------+----------+--------------+------------------+
  3. | File                   | Position | Binlog_Do_DB | Binlog_Ignore_DB |
  4. +------------------------+----------+--------------+------------------+
  5. |mysqld-bin.000012       |      106 | adam         |                  |
  6. +------------------------+----------+--------------+------------------+
  7. 1 row in set (0.00 sec)
On Slave 2:
  1. mysql> CHANGE MASTER TO MASTER_HOST='192.168.16.5', MASTER_USER='replication', MASTER_PASSWORD='password', MASTER_PORT=3306,MASTER_LOG_FILE='mysqld-bin.000012', MASTER_LOG_POS=106, MASTER_CONNECT_RETRY=10;
Attention! As I have already mentioned in the previous section this will configure slave and server will remember settings, so this replaces my.cnf settings in latest versions of MySQL server.

MySQL master-master replication and autoincrement indexes

If you are using master-slave replication, than most likely you will design your application the way to write to master and read from slave or several slaves. But when you are using master-master replication you are going to read and write to any of master servers. So, in this case the problem with autoincremental indexes will raise. When both servers will have to add a record (different one each server simultaneously) to the same table. Each one will assign them the same index and will try to replicate to the salve, this will create a collision. Simple trick will allow to avoid such collisions on MySQL server.
On the Master 1/Slave 2 add to /etc/my.cnf:
  1. auto_increment_increment= 2
  2. auto_increment_offset   = 1
On the Master 2/Slave 1 add to /etc/my.cnf:
  1. auto_increment_increment= 2
  2. auto_increment_offset   = 2
THIS CONTENT tAKEN bY gIVEN uRL:-
  1. Today I set up some MySQL replication for a server that I set up a few weeks ago. This was my first time doing replication and it was quite a learning experience. This was using MySQL 5.0 and CentOS 5.3, but this should work for most semi-recent versions of both. In this setup, transactions are mirrored to the slave server as they happen on the master.
    In this tutorial I’ll use the following setup:
    Master Server: 10.1.100.1
    Slave Server: 10.2.200.2
    MySQL Data path: /var/lib/mysql
    MySQL slave user named slave_user
    

    [Master]

    First, edit the master server MySQL config file. Add/Replace the following lines
    1
    vim /etc/my.cnf
    # [mysqld] section
    # Start Modification
    # First line is probably already there
    datadir = /var/lib/mysql
    server-id = 1
    relay-log = /var/lib/mysql/mysql-relay-bin
    relay-log-index = /var/lib/mysql/var/mysql-relay-bin.index
    log-error = /var/lib/mysql/mysql.err
    master-info-file = /var/lib/mysql/mysql-master.info
    relay-log-info-file = /var/lib/mysql/mysql-relay-log.info
    log-bin = /var/lib/mysql/mysql-bin
    # Stop Modification
    
    Restart MySQL to load the changes
    1
    service mysqld restart

    [Slave]

    Now we’ll do about the same thing on the slave server
    1
    vim /etc/my.cnf
    # [mysqld] section
    # Start Modification
    # First line is probably already there
    datadir = /var/lib/mysql
    server-id = 2
    relay-log = /var/lib/mysql/mysql-relay-bin
    relay-log-index = /var/lib/mysql/mysql-relay-bin.index
    log-error = /var/lib/mysql/var/mysql.err
    master-info-file = /var/lib/mysql/mysql-master.info
    relay-log-info-file = /var/lib/mysql/mysql-relay-log.info
    # Stop Modification
    
    Restart MySQL to load the changes
    1
    service mysqld restart

    [Master]

    Now we need to tell MySQL where we are replicating to and what user we will do it with.
    1 2 3 4
    mysql -u root -p mysql> STOP SLAVE; mysql> GRANT REPLICATION SLAVE ON *.* TO 'slave_user'@'%' IDENTIFIED BY 'slave_password'; mysql> FLUSH PRIVILEGES;
    Now we will test that this side of the replication is working and get the location that we will start the replication from.
    1 2 3 4 5 6 7 8 9
    mysql> USE Any_database_name; mysql> FLUSH TABLES WITH READ LOCK; mysql> SHOW MASTER STATUS; +------------------+----------+--------------+------------------+ | File             | POSITION | Binlog_Do_DB | Binlog_Ignore_DB | +------------------+----------+--------------+------------------+ | mysql-bin.000001 |   451228 |              |                  | +------------------+----------+--------------+------------------+ 1 ROW IN SET (0.00 sec)
    Write down the File, Position number, as this is where we will start the replication from. Here it is a good idea to do a dump of your master database(s) and pipe it into your slave server.
    1
    mysqldump -u root --all-databases --single-transaction --master-data=1 > /home/MasterSnapshot.sql

    [Slave]

    First grab your SQL dump file from the master server. You can use whatever method you would like to transfer the file. SCP example:
    1
    scp root@10.1.100.1:/path/to/MasterSnapshot.sql root@10.2.200.2:/home/MasterSnapshot.sql
    Import the SQL file into MySQL
    1
    mysql -u root -p < /home/MasterSnapshot.sql
    Now we’ll set the slave to read from the master server, starting at the record position we wrote down earlier. Make sure you use the MASTER_LOG_FILE and MASTER_LOG_POS from a few steps back.
    1 2 3
    mysql> CHANGE MASTER TO MASTER_HOST='10.1.100.1', MASTER_USER='slave_user', MASTER_PASSWORD='slave_password', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=451228; mysql> START SLAVE; mysql> SHOW SLAVE STATUS\G;
    Make sure that from the resulting output you have the following: Slave_IO_Running: Yes Slave_SQL_Running: Yes
    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    Master1
    grant replication slave on *.* to 'root'@'172.31.22.57' identified by 'admin123';
    GRANT REPLICATION SLAVE ON *.* TO 'root'@'172.31.22.57' IDENTIFIED BY 'admin123';
    Slave1/master2
    CHANGE MASTER TO MASTER_HOST='172.31.22.52', MASTER_USER='root', MASTER_PASSWORD='admin123', MASTER_PORT=3306,MASTER_LOG_FILE='mysqld-bin.000006', MASTER_LOG_POS=66302851, MASTER_CONNECT_RETRY=10;
    CHANGE MASTER TO MASTER_HOST='172.31.22.56', MASTER_USER='root', MASTER_PASSWORD='admin123', MASTER_LOG_FILE='mysql-bin.000008', MASTER_LOG_POS=310;
    master2/slave1
    grant replication slave on *.* to 'root'@'172.31.22.56' identified by 'admin123';
    GRANT REPLICATION SLAVE ON *.* TO 'root'@'172.31.22.56' IDENTIFIED BY 'admin123';
    slave2/master1:
    CHANGE MASTER TO MASTER_HOST='172.31.22.53', MASTER_USER='root', MASTER_PASSWORD='admin123', MASTER_PORT=3306,MASTER_LOG_FILE='mysqld-bin.000020', MASTER_LOG_POS=89253722, MASTER_CONNECT_RETRY=10;
    iptables -A INPUT -p tcp -s 172.31.22.56 --sport 3306 -d 172.31.22.57 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
    iptables -A INPUT -p tcp -s 172.31.22.57 --sport 3306 -d 172.31.22.56 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT