Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, 3 August 2016

Ubuntu - Swap between PHP 5.5, 5.6 and 7.0

Hello,

This is tutorial how we can do it:
  1. Install PHP 5.5:
    • sudo apt-get install -y php5
  2. Install PHP 5.6:
    • sudo add-apt-repository ppa:ondrej/php
      • In some case, you will need to change Ubuntu codename in this file:
        • sudo vim /etc/apt/sources.list.d/ondrej-ubuntu-php-xenial.list
    •  sudo apt-get update
    • sudo apt-get install -y php5.6
  3. Install PHP 7.0:
    • sudo apt-get install -y php7.0
  4.   Create symlink in your .bashrc file for quick access:
    • vim ~/.bashrc
    • Apache2:
      • #################################################
        ############### PHP Version Toggle ##############
        #################################################
        # Remove the -q to see debugging information if there are problems
        alias enphp5.5="
         sudo a2dismod php5.6 -q;
         sudo a2dismod php7.0 -q;
         sudo a2enmod php5 -q;
         sudo ln -sf /usr/bin/php5 /usr/bin/php;
         sudo service apache2 restart"
        alias enphp5.6="
         sudo a2dismod php5 -q;
         sudo a2dismod php7.0 -q;
         sudo a2enmod php5.6 -q;
         sudo ln -sf /usr/bin/php5.6 /usr/bin/php;
         sudo service apache2 restart"
        alias enphp7.0="
         sudo a2dismod php5 -q;
         sudo a2dismod php5.6 -q;
         sudo a2enmod php7.0 -q;
         sudo ln -sf /usr/bin/php7.0 /usr/bin/php;
         sudo service apache2 restart"
        
    • Nginx:
      • Remove apache2:
        • sudo service apache2 stop
        • sudo apt-get remove apache2*
        • sudo apt-get purge apache2
      • Install php-fpm for all versions
        • sudo apt-get install php5-fpm
        • sudo apt-get install php5.6-fpm
        • sudo apt-get install php7.0-fpm
      • Stop all php-fpm:
        • sudo service php5-fpm stop
        • sudo service php5.6-fpm stop
        • sudo service php7.0-fpm stop
      • #################################################
        ############### PHP Version Toggle ##############
        #################################################
        # Remove the -q to see debugging information if there are problems
        alias enphp5.5="
         sudo ln -sf /usr/bin/php5 /usr/bin/php;
         sudo service php5.6-fpm stop;
         sudo service php7.0-fpm stop;
         sudo service php5-fpm start;
         sudo find /etc/nginx/sites-available -type f -exec sed -i 's,/run/php/php5.6-fpm.sock,/var/run/php5-fpm.sock,g;s,/run/php/php7.0-fpm.sock,/var/run/php5-fpm.sock,g' {} \;
         sudo service nginx restart"
        alias enphp5.6="
         sudo ln -sf /usr/bin/php5.6 /usr/bin/php;
         sudo service php5-fpm stop;
         sudo service php7.0-fpm stop;
         sudo service php5.6-fpm start;
         sudo find /etc/nginx/sites-available -type f -exec sed -i 's,/var/run/php5-fpm.sock,/run/php/php5.6-fpm.sock,g;s,/run/php/php7.0-fpm.sock,/run/php/php5.6-fpm.sock,g' {} \;
         sudo service nginx restart"
        alias enphp7.0="
         sudo ln -sf /usr/bin/php7.0 /usr/bin/php;
         sudo service php5-fpm stop;
         sudo service php5.6-fpm stop;
         sudo service php7.0-fpm start;
         sudo find /etc/nginx/sites-available -type f -exec sed -i 's,/var/run/php5-fpm.sock,/run/php/php7.0-fpm.sock,g;s,/run/php/php5.6-fpm.sock,/run/php/php7.0-fpm.sock,' {} \;
         sudo service nginx restart"
        
  5. Reload your new .bashrc commands:
    • source ~/.bashrc
  6. Done, now you can try it with:
    • enphp5.5
    • php -v
    • enphp5.6
    • php -v
    • enphp7.0
    • php -v

Good luck!
Source: https://github.com/JREAM/phalcon-xenial

Sunday, 15 June 2014

Phalcon DevTools commands


Phalcon DevTools commands:

  1. Create project:
    • phalcon create-controller --name project-name
  2. Create model:
    • All models:
      • Create and delete the old one:
        • phalcon all-models --relations --force
      • Create new:
        • phalcon all-models --relations
    • Individual model:
      • Create and delete the old one:
        • phalcon model --name table-name --relations --force
      • Create new:
        • phalcon model --name table-name --relations
  3. Create scaffold:
    • With volt engine:
      • phalcon scaffold model-name --template-engine=volt
    • Default:
      • phalcon scaffold model-name

Monday, 9 September 2013

PHP - Filter slow mysql in mysql log file

Hello,

This is the PHP script figure out which query make your system go down:
  • <?php 
    error_reporting(E_ALL);
    ini_set('error_reporting', E_ALL);
    ini_set('display_errors',1);
    
    $file      = file_get_contents('mysql-slow.log');
    $limitShow = 10;
    
    $explodes  = explode("Query_time: ", $file);
    
    $selects = array();
    $updates = array();
    $deletes = array();
    $inserts = array();
    
    foreach ($explodes as $k => $v) {
        if ($k > 0) {
            if (isQueryCategory($v, 'SELECT')) {
                $selects = updateArray($selects, $v, 'SELECT', 'WHERE');
            } elseif (isQueryCategory($v, 'UPDATE')) {
                $updates = updateArray($updates, $v, 'UPDATE', 'SET');
            } elseif (isQueryCategory($v, 'DELETE')) {
                $deletes = updateArray($deletes, $v, 'DELETE', 'WHERE');
            } else {
                $inserts = updateArray($inserts, $v, 'INSERT', ';');
            }
        }
    }
    
    function isQueryCategory($string, $category) {
        $string = substr($string, 0, 150);
    
        if (stripos($string, $category) > 0) {
            return true;
        } else {
            return false;
        }
    }
    
    function updateArray($arrays, $string, $keyFirst, $keyLast) {
        $posFirst = stripos($string, $keyFirst);
        $posLast  = stripos($string, $keyLast, $posFirst);
        if (! $posLast) $posLast = stripos($string, ";");
    
        $query    = substr($string, $posFirst, $posLast - $posFirst);
        $key      = trim(str_replace(" ", "", str_replace("\t", "", str_replace("\n", "", $query))));
        $time     = substr($string, 0, stripos($string, " "));
    
        if (! isset($arrays[$key])) $arrays[$key] = array('query' => $query, 'count' => 0, 'time' => 0);
        $arrays[$key]['count'] ++;
        $arrays[$key]['time'] += $time;
     
        return $arrays;
    }
    
    
    function sortArray($arrayIn = array(), $index = null) {
        $arrTemp = array();
        $arrayOut = array();
    
        foreach ($arrayIn as $key => $value) {
            reset($value);
            $arrTemp[$key] = is_null($index)
                             ? current($value)
                             : $value[$index];
        }
    
        natsort($arrTemp);
    
        foreach ( $arrTemp as $key=>$value ) {
            $arrayOut[$key] = $arrayIn[$key];
        }
    
        return $arrayOut;
    }
    
    
    function showReport($name, $arrays) {
        echo "<h1>" . $name . "</h1>";
        echo "<table border='1'>";
        echo "<tr>";
        echo "<th>Query</th>";
        echo "<th>Count</th>";
        echo "<th>Total Time</th>";
        echo "<th>Avg Time</th>";
        echo "<tr>";
    
        foreach ($arrays as $k => $v) {
            echo "<tr>";
            echo "<td>" . $v['query'] . "</td>";
            echo "<td>" . $v['count'] . "</td>";
            echo "<td>" . $v['time'] . "</td>";
            echo "<td>" . $v['time'] / $v['count'] . "</td>";
            echo "<tr>";
        }
        echo "<table>";
    }
    
    //print_r($selects);
    $selects = sortArray($selects, 'count');
    $updates = sortArray($updates, 'count');
    $deletes = sortArray($deletes, 'count');
    $inserts = sortArray($inserts, 'count');
    
    $selects = array_slice($selects, -$limitShow, $limitShow, true);
    $updates = array_slice($updates, -$limitShow, $limitShow, true);
    $deletes = array_slice($deletes, -$limitShow, $limitShow, true);
    $inserts = array_slice($inserts, -$limitShow, $limitShow, true);
    //print_r($selects);exit;
    
    
    showReport("SELECT", $selects);
    showReport("UPDATE", $updates);
    showReport("DELETE", $deletes);
    showReport("INSERT", $inserts);

Good luck!

Monday, 20 May 2013

PHP - SSL version

Hi,

I got this problem when I try using API from a service using SSL:
  1. Error log:
    • file_get_contents(): Failed to enable crypto
    • fopen(): Failed to enable crypto
  2. Resolved:
    • Checking your SSL version in browser:
      • The connection uses TLS 1.0
        • function getSSLPage($url) {
              $ch = curl_init();
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
              curl_setopt($ch, CURLOPT_HEADER, false);
              curl_setopt($ch, CURLOPT_URL, $url);
              curl_setopt($ch, CURLOPT_SSLVERSION,3); 
          
              ob_start();
              curl_exec($ch);
              curl_close($ch);
              $content = ob_get_contents();
              ob_end_clean();
          
              return $content;
          }
      • The connection uses TLS 1.1
        • You can use normal script

Good luck!

Friday, 1 March 2013

MacPorts - PHP, Apache & MySQL

Hi,

These some tutorials how to install lamp server using MarPorts:
  1. Install MacPorts:
    1. Install Xcode
    2. Launch Xcode > Preferences > Downloads > Install 'Command Line Tools'
    3. Go to MacPorts website and follow their structure to install MacPorts: http://www.macports.org/install.php
  2. Install PHP & Apache:
    1. sudo port install php5 +apache2 +mcrypt +curl +tidy +pear
    2. sudo port load apache2
    3. cd /opt/local/apache2/modules
    4. sudo /opt/local/apache2/bin/apxs -a -e -n "php5" libphp5.so
    5. sudo cp /opt/local/etc/php5/php.ini-development /opt/local/etc/php5/php.ini
    6. sudo nano /opt/local/apache2/conf/httpd.conf
      1. Go to line 119 (In Nano: CTRL+w then CTRL+t and write 119), and enter the following lines:
        • AddType application/x-httpd-php .php
        • AddType application/x-httpd-php-source .phps
    7. Now, change DocumentRoot from:
      1. From: DocumentRoot "/opt/local/apache2/htdocs"
      2. To: DocumentRoot "/Users/Shin/sites"
    8. Since we just change the documentRoot folder, we need to adjust some more settings
      1. From: <Directory “/opt/local/apache2/htdocs”>
      2. To: <Directory “/Users/Shin/Sites”>
    9. Now all we have left to do is setting the User and Group. Exchange the following:
      1. From:
        • User www
        • Group www
      2. To:
        • User Shin
        • Group staff
    10. sudo /opt/local/apache2/bin/apachectl restart
  3. Install MySQL:
    1. sudo port install mysql5 +server
    2. sudo -u mysql mysql_install_db5
    3. sudo chown -R mysql:mysql /opt/local/var/db/mysql5/
    4. sudo chown -R mysql:mysql /opt/local/var/run/mysql5/
    5. sudo chown -R mysql:mysql /opt/local/var/log/mysql5/
      • If that doesn’t work try this:
        • sudo mysql_install_db5 sudo chown -R mysql:mysql /opt/local/var/db/mysql5/
        • sudo chown -R mysql:mysql /opt/local/var/run/mysql5/
    6. sudo port load mysql5-server
    7. sudo ln -s /opt/local/bin/mysql5 /opt/local/bin/mysql
    8. sudo ln -s /opt/local/bin/mysqladmin5 /opt/local/bin/mysqladmin
    9. Change new root password:
      • mysqladmin5 -u root password 'new-password'
  4. Some small bugs:
    1. httpd: Could not reliably determine the server's fully qualified domain name, using <Computer-Name>.local for ServerName
      1. sudo vim /opt/local/apache2/conf/httpd.conf
        • ServerName localhost:80
    2. If you would like to be able to access web pages in the Sites directory of your home directory
      1. sudo vim /opt/local/apache2/conf/httpd.conf
        • Include conf/extra/httpd-userdir.conf
    3. ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
      1. sudo vim /opt/local/etc/mysql5/my.cnf
        • [mysqld_safe]
        • socket = /tmp/mysql.sock
        • [client]
        • socket = /tmp/mysql.sock
      2. sudo vim /opt/local/etc/php5/php.ini 
        • mysqli.default_socket = "/tmp/mysql.sock"
Good luck!

Monday, 15 October 2012

XMLHttpRequest cannot load

Hi,

We just need added this string for PHP files:
  • header('Access-Control-Allow-Origin: *');

Check out this reference:
  • http://stackoverflow.com/questions/7570571/xmlhttprequest-cannot-load

Good luck!

Friday, 12 October 2012

PHPUnit & Xdebug - Installation

Hi,

Default packages:
  1. Ubuntu:
    • sudo apt-get install php5-dev php-pear
    • sudo apt-get install php5-xdebug php5-dev
    • sudo apt-get install php-pear
    • sudo pear channel-discover pear.phpunit.de
    • sudo pear channel-discover components.ez.no
    • sudo pear channel-discover pear.symfony-project.com
    • sudo pear channel-discover pear.symfony.com
    • sudo pear update-channels
    • Uncomment of added in "/etc/php5/cli/php.ini":
      • include_path = ".:/usr/share/php"
  2. Centos:
    • yum install php-pear
    • yum install php-dom
    • yum install php-devel gcc
    • pear channel-discover pear.phpunit.de
    • pear channel-discover pear.symfony-project.com
    • pear channel-discover pear.symfony.com
    • pear channel-discover components.ez.no
    • pecl install xdebug
    • Added new file "/etc/php.d/xdebug.ini":
      • zend_extension=/usr/lib64/php/modules/xdebug.so
        • --OR--
      • extension=xdebug.so
    • Uncomment of added in "/etc/php.ini":
      • include_path = ".:/php/includes:/usr/share/pear:/usr/share/php"

Install latest PHPUnit:
  1. Ubuntu:
    • sudo apt-get remove phpunit
    • sudo pear install -a phpunit/PHPUnit
      • Testing: phpunit --version
  2. Centos:
    • pear install --alldeps phpunit/PHPUnit
      • Testing: phpunit --version

Downgrade current PHPUnit to 3.5.15:
  1. Uninstall current PHPUnit:
    • sudo pear uninstall phpunit/PHPUnit
    • sudo pear uninstall phpunit/DbUnit
    • sudo pear uninstall phpunit/PHP_CodeCoverage
    • sudo pear uninstall phpunit/File_Iterator
    • sudo pear uninstall phpunit/PHPUnit_MockObject
    • sudo pear uninstall phpunit/Text_Template
    • sudo pear uninstall phpunit/PHP_Invoker
    • sudo pear uninstall phpunit/PHP_TokenStream
    • sudo pear uninstall phpunit/PHP_Timer
    • sudo pear uninstall phpunit/PHPUnit_Selenium
    • sudo pear uninstall pear.symfony-project.com/YAML
  2. Install PHPUnit 3.5.15:
    • sudo pear clear-cache
    • sudo pear install pear.symfony-project.com/YAML-1.0.2
    • sudo pear install phpunit/PHPUnit_Selenium-1.0.1
    • sudo pear install phpunit/Text_Template-1.0.0
    • sudo pear install phpunit/PHPUnit_MockObject-1.0.3
    • sudo pear install phpunit/PHP_Timer-1.0.0
    • sudo pear install phpunit/File_Iterator-1.2.3
    • sudo pear install phpunit/PHP_TokenStream-1.0.1
    • sudo pear install phpunit/PHP_CodeCoverage-1.0.2
    • sudo pear install phpunit/DbUnit-1.0.0
    • sudo pear install phpunit/PHPUnit-3.5.15

Good luck!

Friday, 17 February 2012

PHP - Address Book (OpenID)


  1. Google:
    • http://25labs.com/import-gmail-or-google-contacts-using-google-contacts-data-api-3-0-and-oauth-2-0-in-php/
  2. Facebook:
    • http://shikii.net/blog/getting-a-list-of-a-facebook-users-friends-with-their-email-addresses/
    • http://stackoverflow.com/questions/3611682/facebook-graph-api-how-to-get-users-email
    • http://stackoverflow.com/questions/3889463/facebook-graph-api-and-friends-email
    • http://www.labnol.org/internet/export-email-addresses-from-facebook/12970/
    • http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/
    • http://giaiphapseo.com/thu-thuat-facebook.html
    • http://net.tutsplus.com/tutorials/php/wrangling-with-the-facebook-graph-api/
  3. Yahoo:
    • http://code.google.com/p/yahoo-api-oauth-flow-demo/source/browse/trunk/?r=2

Thursday, 16 February 2012

PHP - Install runkit extension

Hi,

I found it a bit tricky to install on Linux (Ubuntu)
  1. sudo aptitude install php-pear
  2. sudo aptitude install php5-dev
  3. cd /tmp
  4. cvs -d:pserver:cvsread@cvs.php.net:/repository co pecl/runkit
  5. cd pecl/runkit
  6. phpize
  7. ./configure
  8. make
  9. sudo cp modules/runkit.so /usr/lib/php5/20090626/
  10. sudo vim /et/php5/apache2/php.ini
    • Add the line: extension=runkit.so
  11. Restart apache
  12. Test phpinfo()

Good luck!

Wednesday, 15 February 2012

PHP - fuser forking uncontrollably in cron job (Ubuntu server 11.10)

Hi,

I have this problem with my Ubuntu server 11.10 and I fixed problem by editing /etc/cron.d/php5 and replace the codes with:
  • 09,39 *     * * *     root   [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) -delete

Good luck!

Friday, 14 October 2011

PHP, Apache & MySQL

Hi,

There are some tutorials active Webserver environment:
  1. Apache:
    1. Root folder: /Library/WebServer/Documents/
    2. Start: sudo apachectl start
    3. Stop: sudo apachectl stop
    4. Restart: sudo apachectl graceful
  2. PHP:
    1. Install:
      1. cd /etc && sudo cp php.ini.default php.ini
      2. sudo vim httpd.conf
      3. Uncomment out the hash # to leave it like:
        • LoadModule php5_module libexec/apache2/libphp5.so
      4. Restart Apache
    2. Warning: date_default_timezone_get():
      • sudo vim /private/etc/php.ini
      • date.timezone = "UTC"
    3. autoconf:
      1. Install:
        • Install Xcode
        • Launch Xcode > Preferences > Downloads > Install 'Command Line Tools'
      2. Cannot find autoconf. Please check your autoconf installation and the $PHP_AUTOCONF environment variable. Then, rerun this script.
        • curl -O http://ftp.gnu.org/gnu/autoconf/autoconf-latest.tar.gz
        • tar xvfz autoconf-latest.tar.gz
        • cd autoconf-2.69/
        • ./configure
        • make
        • sudo make install
    4. Missing extension:
      • http://www.coolestguyplanettech.com/how-to-install-mcrypt-for-php-on-mac-osx-lion-10-7-development-server/
      • Download the PHP's source code. You'll need to download the one that matches the version already installed on your system. To find out which one you're using, type php -v from the command line.
      • Extract the archive you downloaded using tar -zxvf followed by the filename. Type cd php-5.4.x/ext/sqlite3/ (where "5.4.x" should be replaced with your version number and "sqlite3" can be any of the modules you want to install from your list above minus the "php_" prefix)
      • Type phpize
      • Type ./configure
      • Type make
      • Type sudo make install
      • Find shared extenstions folder:
        • E.G.: /usr/lib/php/extensions/no-debug-non-zts-20090626/
      • Add extension_dir = "/usr/lib/php/extensions/no-debug-non-zts-20090626" to your php.ini
      • Add extension=sqlite3.so to your php.ini (again make sure to replace sqlite3.so with the name of the other extensions if you compile the others).
      • Restart Apache
    5. Or you can try this tutorials:
      • http://php-osx.liip.ch/
  3. MySQL:
    1. Install:
      • Go to: http://dev.mysql.com/downloads/mysql/
      • Download DMG file for your current operation: Mac OS X ver. 10.6 (x86, 64-bit), DMG Archive
      • Open the downloaded file and double click the file called mysql-x.x.xx-osx10.x-x86_64.pkg and continue through the installation
        • App can’t be opened because it is from an unidentified developer: http://osxdaily.com/2012/07/27/app-cant-be-opened-because-it-is-from-an-unidentified-developer/
      • Installation: MySQL.prefPane, MySQLStartupItem.pkg
    2. Enable command line:
      • sudo vim /etc/paths
      • Appended the line:
        • /usr/local/mysql/bin
      • Restart OS
    3. Missing /var/mysql/mysql.sock file:
      • Check it at:
        • /private/tmp/mysql.sock
        • /tmp/mysql.sock
        • /usr/local/mysql/run/mysql_socket
      • Try create symbolic link for: /var/mysql/mysql.sock
        • sudo ln -s /private/tmp/mysql.sock /var/mysql/mysql.sock
        • sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock
        • sudo ln -s /usr/local/mysql/run/mysql_socket /var/mysql/mysql.sock
    4. Reference:
      • http://blog.mclaughlinsoftware.com/2011/02/10/mac-os-x-mysql-install/
Good luck!

Friday, 30 September 2011

Saturday, 20 August 2011

PHP - Create virtual host for Zend Framework

Hi,

These are tutorials how to create virtual host for Zend Framework
  1. Ubuntu:
    1. Apache:
      • sudo vim /etc/apache2/sites-available/domain.com
        • <VirtualHost *:80>
              ServerName   my.domain.com
              ServerRoot   /path/to/server/root/
              DocumentRoot /path/to/server/root/my.domain.com/public
              RewriteEngine off
              <Location />
                  RewriteEngine on
                  RewriteCond %{REQUEST_FILENAME} !-f
                  RewriteCond %{REQUEST_FILENAME} !-d
                  RewriteRule !\.(js|ico|gif|jpg|png|css|swf|json|xml)$ /index.php
              </Location>
          </VirtualHost>
      • sudo ln -s /etc/apache2/sites-available/domain.com /etc/apache2/sites-enabled/domain.com
      • sudo /etc/init.d/apache2 restart:
    2. Lighttpd:
      • sudo vim /etc/lighttpd/conf-enabled/10-simple-vhost.conf:
        • $HTTP["host"] == "hostname" {
              server.document-root = "/home/web/123do.tracking/public/"
              url.rewrite-once = (".*\.(js|ico|gif|jpg|png|css|swf|xml)$" => "$0", "" => "/index.php")
          }
          • --OR--
        • $HTTP["host"] == "hostname" {
              server.document-root = "/home/web/123do.tracking/public/"
              url.rewrite-once = ( "^(/(?!(favicon.ico$|scripts/|styles/|images/)).*)" => "index.php" )
          }
      • sudo /etc/init.d/lighttpd restart
  2. Centos:
    1. Apache:
      • sudo vi /etc/httpd/conf/httpd.conf
        • <VirtualHost *:80>
              ServerName   domain.com
              ServerRoot   /var/www/domain
              DocumentRoot /var/www/domain

              RewriteEngine off

              <Location />
          RewriteEngine on
          RewriteCond %{REQUEST_FILENAME} !-f
          RewriteCond %{REQUEST_FILENAME} !-d
          RewriteRule !\.(js|ico|gif|jpg|png|css|swf|json|xml)$ /index.php
              </Location>
          </VirtualHost>
      • sudo /etc/init.d/httpd restart


Good luck!

Wednesday, 3 August 2011

PHP - ldap_bind(): Unable to bind to server: Protocol error

This is not my, I just copy original the post in here:

Note that you have to specify the protocol version prior to making a call to ldap_bind, when the server is expecting LDAP protocol version 3. If you do not, you will receive a warning and fail to bind, such as:

ldap_bind(): Unable to bind to server: Protocol error

In order to avoid this, make this call:

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
?>

Where $ds is the result returned by ldap_connect(...);


And this is example CODE for test your LDAP Server:

<?php

error_reporting(E_ALL & ~E_NOTICE);

$ldapconfig['host'] = 'ldap.kiss'; //Change your host
$ldapconfig['port'] = 389;         //Default port
$ldapconfig['basedn'] = 'dc=kiss'; //change your basedn
$username = "quang.nguyen";        //Change your username

$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$dn="uid=".$username.",ou=people,".$ldapconfig['basedn'];

if ($bind=ldap_bind($ds, $dn, $password)) {
    echo("Login correct");
} else {

    echo("Unable to bind to server.</br>");

    echo("msg:'".ldap_error($ds)."'</br>");#check if the message isn't: Can't contact LDAP server :)
    #if it say something about a cn or user then you are trying with the wrong $dn pattern i found this by looking at OpenLDAP source code :)
    #we can figure out the right pattern by searching the user tree
    #remember to turn on the anonymous search on the ldap server

    if ($bind=ldap_bind($ds)) {

        $filter = "(cn=*)";

        if (!($search=@ldap_search($ds, $ldapconfig['basedn'], $filter))) {
            echo("Unable to search ldap server<br>");
            echo("msg:'".ldap_error($ds)."'</br>");#check the message again
        } else {
            $number_returned = ldap_count_entries($ds,$search);
            $info = ldap_get_entries($ds, $search);
            echo "The number of entries returned is ". $number_returned."<p>";

            for ($i=0; $i<$info["count"]; $i++) {
                print_r($info[$i]);#look for your user account in this pile of junk and apply the whole pattern where you build $dn to match exactly the ldap tree entry
            }
        }

    } else {
        echo("Unable to bind anonymously<br>");
        echo("msg:".ldap_error($ds)."<br>");
    }
}



Good luck!

Thursday, 26 May 2011

PHP - Auto get Backup Database from Server Using ssh2


Hello,

This is function auto get backup database file from server using ssh2:

  1. Install ssh2 php module:
    • sudo apt-get update
    • sudo apt-get install php5-mcrypt libssh2-php
      • Check enable modules:
        • php -m | grep mcrypt
        • php -m | grep ssh2
      • Enable modules:
        • sudo php5enmod mcrypt
        • sudo php5enmod ssh2
      • Module ssh2 ini file doesn't exist:
        • echo "extension=ssh2.so" > /etc/php5/mods-available/ssh2.ini
      • service php5-fpm restart
  2. Create cron backup database from you server:
    • mysqldump -uroot -ppassword your-database | gzip -9 > /home/web/backup/`date +%y%m%d`-your-database.sql.gz
  3. Create cron get backup database file from your PC:
    • $host = 'your-ip-address'; //
      $port = 22; //default: 22
      $username = "root";
      $password = "your-password";

      //target want to get from Server
      $fileNameGet = '/home/web/backup/' . date('ymd', time()) . '-your-database.sql.gz';

      //target want to store backup file from your computer
      $fileNameSave = '/home/shin/Desktop/Data/Backup/' . date('ymd', time()) . '-your-database.sql.gz';

      $connection = ssh2_connect($host, $port);
      // use any of the ssh2_auth_* methods
      ssh2_auth_password($connection, $username, $password);
      $sftp = ssh2_sftp($connection);

      if (file_exists("ssh2.sftp://$sftp/" . $fileNameGet)) {
          ssh2_scp_recv($connection, $fileNameGet, $fileNameSave);
      }
  4. Done!

Good luck!

Monday, 25 April 2011

PHP - Call to undefined function ssh2_connect

Call to undefined function ssh2_connect()

sudo aptitude install libssh2-1-dev libssh2-php