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

Thursday, November 13, 2014

IPv6 To PTR RDNS PHP

<?php
$addr = inet_pton($ip);
$unpack = unpack('H*hex', $addr);
$hex = $unpack['hex'];
$arpa = implode('.', array_reverse(str_split($hex))) . '.ip6.arpa';
?>

Monday, January 20, 2014

PHP Function To Convert CIDR To Netmask

<?php
function cidr2mask($cidr) {
     return long2ip(-1 << (32 - (int)$cidr));
}
?>

PHP Function To Convert Netmask To CIDR

<?php
function mask2cidr($mask){
     $long = ip2long($mask);
     $base = ip2long('255.255.255.255');
     return 32-log(($long ^ $base)+1,2);     
}
?>

Wednesday, October 23, 2013

Install Suhosin For PHP 5.4 On cPanel Linux

EDIT: Since the release of this article, new versions of SuHosin have been release with official PHP 5.4+ support.

Please go to:
https://github.com/stefanesser/suhosin/releases

...for the most current version.


1) Grab the current source from github:
cd /usr/local/src

wget https://github.com/stefanesser/suhosin/tarball/master

tar zxvf master
2) Change to the directory just created and then prep Suhosin for PHP
cd /usr/local/src/stefanesser-suhosin-[this will change]

mv session.c session.c.old
wget https://raw.github.com/blino/suhosin/117b6aa6efec61afaa1431c698dad8eb553b55f5/session.c

phpize
Note: We pull the custom session.c above to fix an issue with NULL sessions in PHP 5.4, more info:
https://github.com/stefanesser/suhosin/pull/26

3) Configure, make and install
./configure && make && make install
4) Enable in PHP
echo extension=suhosin.so >> /usr/local/lib/php.ini
5) Restart Apache and check PHP
service httpd restart

php -v
...and you should see:

PHP 5.4.21 (cli) (built: Oct 23 2013 16:48:02)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
with Zend Guard Loader v3.3, Copyright (c) 1998-2013, by Zend Technologies
with Suhosin v0.9.34-dev, Copyright (c) 2007-2012, by SektionEins GmbH

Tuesday, September 17, 2013

Install Memcache and PHP Memcache on cPanel

Step 1: Create work directory
cd /usr/local/src
mkdir memcached-sources
cd memcached-sources
Step 2: Download, compile and install LibEvent
mkdir libevent
cd libevent
wget https://github.com/downloads/libevent/libevent/libevent-2.0.21-stable.tar.gz
tar xvfz libevent-2.0.21-stable.tar.gz
cd libevent-2.0.21-stable
./configure; make; make install
cd /usr/local/src/memcached-sources/
Step 3: Download, compile and install Memcache
mkdir memcache
cd memcache
wget http://memcached.googlecode.com/files/memcached-1.4.15.tar.gz
tar xvfz memcached-1.4.15.tar.gz
cd memcached-1.4.15
./configure --with-lib-event=/usr/local/; make; make install
cd /usr/local/src/memcached-sources/
Step 4: Register LibEvent
echo /usr/local/lib/ > /etc/ld.so.conf.d/libevent-i386.conf
ldconfig
Step 5: Download, compile and install PHP Memcache module
mkdir memcache-php
cd memcache-php
wget http://pecl.php.net/get/memcache-3.0.8.tgz
tar xvfz memcache-3.0.8.tgz
cd memcache-3.0.8
phpize
./configure; make; make install
echo >> memcache.so /usr/local/lib/php.ini
service httpd restart
Step 6: Daemonize Memcache
See this article:
http://www.shiftedbytes.com/2013/06/daemonize-memcached-to-run-memcached-as.html

Wednesday, March 20, 2013

Install Imagick ImageMagick On cPanel

yum -y install ImageMagick-devel ImageMagick-c++-devel
/usr/bin/pecl install imagick
The PECL installer will not handle the module installation correctly so you have two things to do.

First add "extension=imagick.so" to the end of php.ini (/usr/local/lib/php.ini)

Second, move the module to the correct directory:
cp /usr/lib/php/extensions/no-debug-non-zts-20090626/imagick.so /usr/local/lib/php/extensions/no-debug-non-zts-20090626/
Please note your extension directory migght be different and can be found in php.ini under "extension_dir"

Now restart Apache:
service httpd restart
...and then check to see PHP is loading the module:
php -i | grep -i imagick
...which should provide this if installed:
imagick
imagick module => enabled
imagick module version => 3.0.1
imagick classes => Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator
ImageMagick version => ImageMagick 6.5.4-7 2012-05-07 Q16 OpenMP http://www.imagemagick.org
ImageMagick copyright => Copyright (C) 1999-2009 ImageMagick Studio LLC
ImageMagick release date => 2012-05-07
ImageMagick number of supported formats:  => 198
ImageMagick supported formats => A, AI, ART, ARW, AVI, AVS, B, BGR, BMP, BMP2, BMP3, BRF, BRG, C, CALS, CAPTION, CIN, CIP, CLIP, CMYK, CMYKA, CR2, CRW, CUR, CUT, DCM, DCR, DCX, DDS, DFONT, DNG, DOT, DPS, DPX, EPDF, EPI, EPS, EPS2, EPS3, EPSF, EPSI, EPT, EPT2, EPT3, ERF, FAX, FITS, FRACTAL, FTS, G, G3, GBR, GIF, GIF87, GRADIENT, GRAY, GRB, HALD, HISTOGRAM, HRZ, HTM, HTML, ICB, ICO, ICON, INFO, INLINE, IPL, ISOBRL, JNG, JP2, JPC, JPEG, JPG, JPX, K, K25, KDC, LABEL, M, M2V, M4V, MAP, MAT, MATTE, MIFF, MNG, MONO, MOV, MP4, MPC, MPEG, MPG, MRW, MSL, MSVG, MTV, MVG, NEF, NULL, O, ORF, OTB, OTF, PAL, PALM, PAM, PATTERN, PBM, PCD, PCDS, PCL, PCT, PCX, PDB, PDF, PDFA, PEF, PFA, PFB, PFM, PGM, PGX, PICON, PICT, PIX, PJPEG, PLASMA, PNG, PNG24, PNG32, PNG8, PNM, PPM, PREVIEW, PS, PS2, PS3, PSD, PTIF, PWP, R, RADIAL-GRADIENT, RAF, RAS, RBG, RGB, RGBA, RGBO, RLA, RLE, SCR, SCT, SFW, SGI, SHTML, SR2, SRF, STEGANO, SUN, SVG, SVGZ, TEXT, TGA, THUMBNAIL, TIFF, TIFF64, TILE, TIM, TTC, TTF, TXT, UBRL, UIL, UYVY, VDA, VICAR, VID, VIFF, VST, WBMP, WMF, WMV, WMZ, WPG, X, X3F, XBM, XC, XCF, XPM, XPS, XV, XWD, Y, YCbCr, YCbCrA, YUV
imagick.locale_fix => 0 => 0
imagick.progress_monitor => 0 => 0

Wednesday, January 16, 2013

Determine Version Of PHP From Command Line

php -v
This will give you ALL the information, but if you want just the numeric version:
php -v | head -1 | cut -d ' ' -f 2

Wednesday, January 2, 2013

Recursively Find All Array Keys In A Multi-Dimensional Array In PHP

<?php

$tmpArray = array (
  'root' => array (
    'a' => array(1,2,3,4,5),
    'b' => array(6,7,8,9,0),
    'c' => array(11,22,33,44,55),
    'd' => array(66,77,88,'99' => 
     array('apple','banana','cucumber'=> 
      array('alpha','beta','gamma'))
       )
      ),
  'user' => array('foo','bar')
    );
    
function array_keys_recursive($arr,&$rKeys = array())
{
 foreach ($arr as $key => $val)
 {
  if(is_array($val))
  {
   $rKeys[] = $key;
   array_keys_recursive($val,$rKeys);
  }  
 }
 return $rKeys;
}
print_r( array_keys_recursive($tmpArray) );

//Echos:
//Array
//(
//    [0] => root
//    [1] => a
//    [2] => b
//    [3] => c
//    [4] => d
//    [5] => 99
//    [6] => cucumber
//    [7] => user
//)
?>

Recursively Count Array Keys In A Multi-Dimensional Array In PHP

<?php
//Array With 8 Keys
$tmpArray = array (
  'root' => array (
    'a' => array(1,2,3,4,5),
    'b' => array(6,7,8,9,0),
    'c' => array(11,22,33,44,55),
    'd' => array(66,77,88,'99' => 
     array('apple','banana','cucumber'=> 
      array('alpha','beta','gamma'))
       )
      ),
  'user' => array('foo','bar')
    );
    
function num_array_keys_recursive($arr,$numKeys = 0)
{
 foreach ($arr as $key => $val)
 {
  if(is_array($val))
  {
   $numKeys ++;
   $numKeys = num_array_keys_recursive($val,$numKeys);
  }  
 }
 return $numKeys;
}
echo num_array_keys_recursive($tmpArray);
//Echos 8
?>

Wednesday, October 17, 2012

Using The Solarwinds IPmonitor API WSDL Webservice With SOAP And XPATH

<?php
function dumpDOMnodeList($xml)
{
    //USED TO DUMP THE XPATH RESULTS
    $docTmp = new DOMDocument();
    foreach($xml as $n) $docTmp->appendChild($docTmp->importNode($n,true));
    print_r($docTmp->saveHTML());
}

$soapVersion = '1.2';
$soapLocation = 'https://domain.com/soap/status.asmx?WSDL';
$soapContext = stream_context_create(array('ssl' => array('verify_peer' => FALSE)));
$soapParameters = array (
            'location' => $soapLocation,
            'login' => 'login',
            'password' => 'password',
            'stream_context' => $soapContext
            );         

//IPM.WSDL IS A LOCAL COPY OF STATUS.ASMX?WSDL
$soapClient = new SoapClient('ipm.wsdl',$soapParameters); 

//GET GROUPS
/*
$soapRequest = '<?xml version="1.0" encoding="utf-8"?>';
$soapAction = 'http://schemas.ipmonitor.com/ipm70/GetGroups';
*/

//GET MONITORS
/*MAIN GROUP WITHIN IPM, NEVER CHANGES CAN BE OBTAINED BY USING "GetGroups" METHOD... 
IT IS THE MAIN gtGroup ID WRAPPING THE RESPONSE*/
$groupID = 'XXXXXXXXXXXX'; 
$justTrouble = 'TRUE'; // ONLY RETURN DISTRESSED MONITORS

$soapRequest = '<?xml version="1.0" encoding="utf-8"?>'.$groupID.''.$justTrouble.'';
$soapAction = 'http://schemas.ipmonitor.com/ipm70/GetMonitors';

$soapResult = $soapClient->__doRequest($soapRequest, $soapLocation, $soapAction, $soapVersion); //REQUEST, LOCATION, ACTION, VERSION

$doc = new DOMDocument();
$doc->LoadXML($soapResult);

$xpath = new DOMXpath($doc);
$xpath->registerNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$xpath->registerNamespace('def', 'http://schemas.ipmonitor.com/ipm70/'); 

$alerts = $xpath->query("/soap:Envelope/soap:Body/def:GetMonitorsResponse/def:GetMonitorsResult/def:rtMonitor");

dumpDOMnodeList($alerts);
?>

Thursday, May 17, 2012

Install Imagick For PHP

Run the following commands (this was on Centos)
# yum install ImageM* netpbm gd gd-* libjpeg libexif gcc coreutils make
# cd /usr/local/src
# wget http://pecl.php.net/get/imagick-2.2.2.tgz
# tar zxvf ./imagick-2.2.2.tgz
# cd imagick-2.2.2
# phpize
# ./configure
# make
# make test
# make install
This will compile imagick.so, and move it to your extensions directory specified in php.ini. Now you’ll need to add the following to php.ini:
extension=imagick.so
...and restart Apache:
# service httpd restart

Wednesday, March 28, 2012

Return HTTP Status Code Only From CURL Call

<?php
$url = 'yoururl';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

?>

Friday, March 2, 2012

How To Add An XSL Stylesheet To PHP DOMDocument

<?php
$xslAttributes = 'href="sample.xsl" type="text/xsl"';
$xmlStylesheet = new DOMProcessingInstruction('xml-stylesheet',$xslAttributes);

$doc = new DOMDocument('1.0','UTF-8');
$doc->appendChild($xmlStylesheet);
?>

Tuesday, November 29, 2011

Installing Pear PHPUnit on cPanel

We first need to add two channels at the command prompt:
# pear channel-discover pear.phpunit.de
# pear channel-discover pear.symfony-project.com

Do a quick list for the package:
# pear remote-list -c phpunit

Now we install it:
# pear install --alldeps phpunit/PHPUnit

And then double check the information:
# pear info phpunit/PHPUnit

...and you should see something like:
About pear.phpunit.de/PHPUnit-3.6.4
===================================
Release Type          PEAR-style PHP-based Package
Name                  PHPUnit
Channel               pear.phpunit.de
Summary               The PHP Unit Testing framework.
Description           The PHP Unit Testing framework.
Maintainers           Sebastian Bergmann sebastian@phpunit.de (lead)
Release Date          2011-11-25 07:33:12
Release Version       3.6.4 (stable)
API Version           3.6.0 (stable)
License               BSD License
Release Notes         http://github.com/sebastianbergmann/phpunit/blob/master/README.markdown
Required Dependencies PHP version 5.2.7
                      PEAR installer version 1.9.4 or newer
                      Package pear.phpunit.de/File_Iterator
                        Version 1.3.0 or newer
                      Package pear.phpunit.de/Text_Template
                        Version 1.1.1 or newer
                      Package pear.phpunit.de/PHP_CodeCoverage
                        Version 1.1.0 or newer
                      Package pear.phpunit.de/PHP_Timer
                        Version 1.0.1 or newer
                      Package pear.phpunit.de/PHPUnit_MockObject
                        Version 1.1.0 or newer
                      Package pear.symfony-project.com/YAML
                        Version 1.0.2 or newer
                      Extension dom
                      Extension pcre
                      Extension reflection
                      Extension spl
Optional Dependencies Package pear.phpunit.de/PHP_Invoker
                        Version 1.0.0 or newer
                      Extension json
                      Extension simplexml
                      Extension tokenizer
package.xml version   2.0
Last Modified         2011-11-29 21:48
Previous Installed    - None -
Version

Friday, September 16, 2011

Iterate Over Nested / Multi-Level DOM NodeList

<?php
function processNodeList($nodeList)
{
    # text nodes don't have child nodes
    if ($root->nodeName == '#text')
    {
        $xml = $root->nodeValue;
    }
    else
    {
        # start tag
        $xml = sprintf('<%s>', $root->nodeName);
        # contents
        foreach ($root->childNodes as $node)
        {
            $xml .= processNodeList($node);
        }
        #end tag
        $xml .= sprintf('', $root->nodeName);
        # for some reason the blog puts html comment tags around the closing sprintf, just FYI to remove those as they are not intended
    }
    return $xml;
}

$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);

$nodeList = $xpath->query('/');
$xml = processNodeList($nodeList);

echo $xml; 
?>

Thursday, September 1, 2011

Import Xpath Query NodeList To A New XML Document

<?php

$doc = new DOMDocument();
$doc->loadxml($xml); //XML STRING
$xpath = new DOMXpath($doc);
$xpathResults = $xpath->query(""); //YOUR QUERY
$nodes = $xpathResults->length;

if($nodes > 0)
{
 $newDom = new DOMDocument('1.0','UTF-8');
 $root = $newDom->createElement('root');
 $root = $newDom->appendChild($root);
 
 foreach ($xpathResults as $domElement)
 {
  $domNode = $newDom->importNode($domElement, true);
  $root->appendChild($domNode);
  $newXML = $newDom->saveXML();     
 }   
 header("Content-type: application/xml");
 echo $newXML;
} 

?>

Monday, February 8, 2010

Twelve month historical reference (month/year) (rolling)

<?php
$m = date('m');
$y = date('Y');
for ($i = 1; $i < 12; ++$i) {
    $d[] = date($format, mktime(12, 12, 12, $m-$i, 1, $y));
}
$d = array_reverse($d);
array_unshift($d, date($format));
/*
WHEN YOU PARSE THE ARRAY YOULL GET A LISTING OF MONTHS (JAN-DEC)
WHERE BY THE CURRENT MONTH BACK TO JAN ARE OF THE CURRENT YEAR
AND WHEREBY THE NEXT MONTH TO DEC ARE OF THE PREVIOUS YEAR
E.G
TODAY: JAN 2010
OUTPUT:
Month=1&Year=2010
Month=2&Year=2009
Month=3&Year=2009
Month=4&Year=2009
Month=5&Year=2009
Month=6&Year=2009
Month=7&Year=2009
Month=8&Year=2009
Month=9&Year=2009
Month=10&Year=2009
Month=11&Year=2009
Month=12&Year=2009

E.G 
TODAY: NOV 2010
OUTPUT:
Month=11&Year=2010
Month=12&Year=2009
Month=1&Year=2010
Month=2&Year=2010
Month=3&Year=2010
Month=4&Year=2010
Month=5&Year=2010
Month=6&Year=2010
Month=7&Year=2010
Month=8&Year=2010
Month=9&Year=2010
Month=10&Year=2010
*/
?>

Friday, January 29, 2010

Twelve month historical reference (month/year) (non-rolling)

<?php
$format = "\M\o\\n\\t\h=n&\a\m\p;\Y\e\a\\r=Y"; //OUTPUT FORMAT  
$m = date('m');
$y = date('Y');
$dates = array();
for ($i = 1; $i < 13; ++$i) {
    if ($i == $m + 1)
        --$y;
    $dates[] = date($format, mktime(12, 0, 0, $i, 1, $y));
} 
/*
WHEN YOU PARSE THE ARRAY YOULL GET A LISTING OF MONTHS (JAN-DEC)
WHERE BY THE CURRENT MONTH BACK TO JAN ARE OF THE CURRENT YEAR
AND WHEREBY THE NEXT MONTH TO DEC ARE OF THE PREVIOUS YEAR
E.G
TODAY: JAN 2010
OUTPUT:
Month=1&Year=2010
Month=2&Year=2009
Month=3&Year=2009
Month=4&Year=2009
Month=5&Year=2009
Month=6&Year=2009
Month=7&Year=2009
Month=8&Year=2009
Month=9&Year=2009
Month=10&Year=2009
Month=11&Year=2009
Month=12&Year=2009

E.G 
TODAY: NOV 2010
OUTPUT:
Month=1&Year=2010
Month=2&Year=2010
Month=3&Year=2010
Month=4&Year=2010
Month=5&Year=2010
Month=6&Year=2010
Month=7&Year=2010
Month=8&Year=2010
Month=9&Year=2010
Month=10&Year=2010
Month=11&Year=2010
Month=12&Year=2009
*/
?>

Monday, January 25, 2010

Return the ordinal suffix for a number

<?php
function getOrdinal($number)
{
 $digit = abs($number) % 10;
 $ord = 'th'; //DEFAULT ORDINAL SUFFIX
 $ord = ((abs($number) %100 < 21 && abs($number) %100 > 4) ? 'th' : (($digit < 4) ? ($digit < 3) ? ($digit < 2) ? ($digit < 1) ? 'th' : 'st' : 'nd' : 'rd' : 'th'));
 return $ord;
}
?>

Recursive file/folder tree

<?php
function create_tree($dir)
{
 if ($handle = @opendir($dir))
 {
  $i=0;
  while (false !== ($file = @readdir($handle)))
  {
   if ($file != '.' && $file != '..')
   {
   $list[$i]=$file;
   $i++;
   }
  }
  $dir_length = count($list);

  for($i=0;$i<$dir_length;$i++)
  {
   if(strrpos($list[$i], '.') == FALSE)
   {
    echo '
  • '.$list[$i].'
      '; create_tree($dir.'/'.$list[$i]); echo '
  • '; } else { echo '
  • '.$list[$i].'
  • '; /* I REALIZE THE HREF ATTRIBUTE ABOVE LOOKS QUOTED WEIRD BLOGGER KEEPS OVERRIDING NESTED QUOTES FOR SOME REASON */ } } closedir($handle); } } $dir = '/'; echo '
      '.dirname($dir).'
    • '.basename($dir).'
        '; create_tree($dir); echo '
    '; ?>