Archive

Archive for the ‘LAMP’ Category

PHP Remote CLI Script Debugging with PHPStorm

February 9, 2016 Leave a comment

PHPStorm is one of the best IDE’s to develop in PHP. I recently came across tons complex php cli scripts and needed a way to debug them.

Follow this PHPStorm Docs post first to set up php storm and the server.

Most important things to configure are

  • Set up xdebug correctly on the remote server. Dont use xdebug.remote_connect_back. Instead use xdebug.remote_host
  • Xdebug must be set up for php cli – check with the command php -i | grep xdebug and you should see many entries
  • Set up deployment path mapping correctly in your project settings – a lot of people miss this and wonder why debug is not working
  • Check your firewalls on both machines, make sure required ports are open, especially port 9000
  • Check debugger settings in phpstorm and make sure you have break at first line set up

In the PHPStorm tutorial, it asks you to set up SSH tunnel. If you are not doing tunneling, you should set these environment variables on the remote server

Eg, if my remote server is centos, i will set these 2 variables

export XDEBUG_CONFIG="idekey=PHPSTORM";
export PHP_IDE_CONFIG="serverName=myDeploymentServerName";

serverName is the name of the server you set up for deployment in phpstorm deployment settings

these variables are valid for the session, if you logout and log in, you have to set them again.

You can add these to your .bashrc file in your home folder to make them permanent

In case you want to use xdebug.remote_connect_back, you might have to run your php scripts on the command line with additional args like this

php -dxdebug.remote_enable=1  -dxdebug.remote_host=10.0.1.2 -dxdebug.remote_connect_back=0 /path-to-php-script

 

PHP 5.6 and Self Signed Certificates for Soap, file_get_contents

November 18, 2015 Leave a comment

Operating System: CentOS 7
PHP: 5.6

This is only for local machine and local development – use at your own risk

I a using a self signed SSL certificate on my local development machine and many functions in PHP refuse to work with self signed certificates.
Some of the functions are

  • file_get_contents()
  • fopen()
  • SoapClient()

my domain name for local machine: localhost
my Self Signed SSL certificate in PEM format: localhost.crt

If i use any of these functions to access a HTTPS resource, the calls fail with invalid certificate
eg file_get_contentc(“https://localhost/test.csv”); will fail

the easiest method is to force add your self signed certificate to the trusted ca-authority in the operating system and openssl

# this should already be installed if you have openssl installed
yum -y install ca-certificates

# copy your self signed cert to the /etc/pki/ca-trust/source/anchors - change certificate path as necessary
cp /etc/pki/tls/certs/localhost.crt /etc/pki/ca-trust/source/anchors

# update
sudo update-ca-trust

now SoapClient, file_get_contents and fopen should work without problems

Other way to do it is to manually send in the stream_context to each of the calls like here

http://stackoverflow.com/questions/18465567/php-soapclient-verify-peer-true-fails-with-ca-signed-certificate

Ajax File Upload without iframe

February 10, 2015 Leave a comment

The Invisible I-frame File Upload method works in almost all browsers.

This post explains using FormData to submit forms that is supported by most new browsers.

<?
if( isset($_POST) && ! empty($_POST) ) {
 
     $file = $_FILES['myfile'];
 
     $output ="Response From the Server\n";
     $output .= "myInput = ".$_POST['myInput'];
     $output .= "\n".'File Name: '.$file['name'];
     $output .= "\n".'File Type: '.$file['type'];
     $output .= "\n".'File Size: '.$file['size'];
     $output .= "\n".'File Tmp Name: '.$file['tmp_name'];
 
     echo $output;
     exit;
}
?>

<html>
<head>
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
     <script type="text/javascript">
         jQuery(document).ready(function($){

         /**
          * when the file is selected 
          */ 
          $("#myfile").change(function() {

               var file = $('#myfile')[0].files[0];

               // new form data 
               var formData = new FormData();
               formData.append('myfile', file); // add the file details
               formData.append('myInput', "Hello World"); // add other data as required
 
               // make an ajax post request 
               $.ajax({
                   url: '/test/file.php',
                   type: 'POST',
                   data: formData,
                   processData: false, // this has to be set to false
                   contentType: false, // this has to be set to false
                   error: function(jqXHR, textStatus, errorThrown){
                       alert("Failed"); 
                   },
                   success: function(data) {
                       alert(data);
                   }
              });
         });
     });
 
 </script>
</head>
<body>
    <input type="file" name="myfile" id="myfile">
</body>
</html>
Categories: Jquery, LAMP, Web Development

Zend Framework 1 – Simple Caching

You can cache data in Zend using the Zend Data Cache.

In the Boorstrap.php file add an _init method to initialize the zend cache

Zend will automatically call all methods in bootstrap that start with _init

protected function _initCache () {
 
   // check and create zend cache directory if it does not exist
   $zendCacheDir = '/tmp/zend-cache';
   if( ! file_exists($zendCacheDir) ) mkdir($zendCacheDir);
 
   $frontendOptions = array(
     'lifetime' => 24 * 60 * 60, // cache lifetime of 24 hours
     'automatic_serialization' => true // for objects and arrays 
   );
 
   $backendOptions = array(
     'cache_dir' => $zendCacheDir // Directory where to put the cache files
   );
 
   // getting a Zend_Cache_Core object
   // we are doing File caching here. Other options are SQLite DB, Memcached, APC
   $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
 
   // cache database table schemata metadata for faster SQL queries
   Zend_Db_Table_Abstract::setDefaultMetadataCache($cache); 
 
   // register the cache to zend registry so that we can use it anywhere in the application
   Zend_Registry::set('Cache', $cache);
 }

From your controller, you can then use this

public function getuserAction($userid) {
 
   // get the cache from the registry 
   $cache = Zend_Registry::get('Cache');
 
   // check if a cached user object exists 
   $cacheKey = "userid_$userid";
   $user = $cache->load($cacheKey);
   
   if( $user === false ) { // cache miss
    // get user data from the database 
    $user = $this->getUserFromDatabase($userid); // your custom function to get data from the database 
 
    // save user to cache 
    $cache->save($user, $cacheKey);
  }
 
  return $user;
}

Other things you can do with the cache

// remove a cache 
$cache->remove($cacheKey);

// clear the entire cache
$cache->clean(Zend_Cache::CLEANING_MODE_ALL);

// clean only outdated
$cache->clean(Zend_Cache::CLEANING_MODE_OLD);

 

Categories: LAMP, Web Development Tags: ,

PHP send text message

/**
 * send a text message via email to a phone 
 * a quick test is to open up gmail and put the phoneNumber@domainName
 * a list of domains can be found here http://www.venture-ware.com/kevin/web-development/email-to-sms/
 * put some text in the Subject and Body and hit send. 
 * If your number and domain is correct, you should get a text 
 * NOTE: Your carrier may charge you
 * 
 * example of how a text message might be routed 
 * php mail() -> http server -> cloud/internet -> SMS gateway -> Remote Tower -> Customer Phone
 * remember that the customer might get charged for non standard text messaging
 * make sure your mails are going out properly 
 * 
 */

/* number to send a text to and the domain
 * this should be in the form phoneNumber@domainName
 * see the link for domain names at the top
 * i am using a example number here, put the correct phone number
 */ 
$phonenumber = '0001112222@vmobile.ca';

mail( $phonenumber, 'Alert message from PHP', 'Testing' );
Categories: LAMP Tags: ,

Installing Zabbix on Ubuntu 12.04

September 18, 2013 Leave a comment

This post describes how to install Zabbix on Ubuntu 12.08 by compiling the Zabbix source.

This is is for test  systems – production systems must give more consideration to security not detailed in this post

  • Zabbix 2.0.8: doanload the Zabbix Sources package and unzip it
  • Ubuntu: I am 12.04 LTS fully updated
  • I have a working instance of LAMP
  • Database: MySQL
  • Create a user and database for zabbix and note down the password

First install some required packages

sudo apt-get install libmysqlclient-dev libcurl4-openssl-dev snmp snmpd libsnmp-dev libxml2-dev

Create zabbix user and group

groupadd zabbix
useradd -g zabbix zabbix

configure zabbix server and zabbix agent

sudo ./configure --enable-server --enable-agent --with-mysql --enable-ipv6 --with-net-snmp --with-libcurl --with-libxml2

install any missing packages – the above step will tell you if it needs any

if everything was satisfied, it will ask you to run the make install command

make install

edit the zabbix server conf file and update the database credentials /usr/local/etc/zabbix_server.conf

start zabbix server an zabbix agent

zabbix_server
zabbix_agentd

check if the zabbix server and agent is running – you will see a list of entries

ps -A | grep zabbix

Now to Set up the Web Front end

  • Copy zabbix-2.0.8/frontends/php to your webroot
  • I copied mine to /var/www/zabbix ( zabbix directory has all files from the php directory – dont do zabbix/php )
  • give write permissions to the web user to zabbix dir temporarily ( for creation of config files )
  • navigate to your-ip-address/zabbix ( mine is localhost/zabbix )
  • follow the installation directions
  • you will need to tweak php.ini to update some values ( /etc/php5/apache2/php.ini )
  • some of them I updated are as follows
  • post_max_size=16M

  • max_execution_time=300
  • max_input_time=300
  • date.timezone = US/Eastern

  • restart apache after updating php.ini
  • go back to your-ip-address/zabbix and follow the instructions
  • after installation is complete, you cannot directly login, you need to import database schema into your zabbix database
  • 3 files to import from zabbix-2.0.8/database/mysql to your zabbix database in this order schema.sql, images.sql, data.sql
  • now try to login using the default User: Admin and Password: zabbix
  • Hurray !!
  • Change default admin name and password
  • Remove write permissions to the zabbix directory

Set zabbix server and agent to start at boot 

# copy init scripts from the zabbix source download dir
sudo cp misc/init.d/debian/* /etc/init.d

# permissions  
sudo chmod 755 /etc/init.d/zabbix-server
sudo chmod 755 /etc/init.d/zabbix-agent

# add to start 
cd /etc/init.d
sudo update-rc.d zabbix-server defaults
sudo update-rc.d zabbix-agent defaults

# restart 
/etc/init.d/zabbix-server restart
/etc/init.d/zabbix-agent restart
Categories: LAMP, Linux Tags: ,

var_dump() output truncated ?

July 31, 2013 1 comment

if you are using xdebug for PHP debugging and your var_dump() output is being truncated, add the below lines to your php.ini or xdebug.ini

restart apache

xdebug.var_display_max_data = -1
xdebug.var_display_max_children = -1
xdebug.var_display_max_depth = -1 
each of these settings are explained here – http://xdebug.org/docs/all_settings
Categories: LAMP, Web Development