Enabling SSH (https) for Apache 2 in Ubuntu/Mint/Possibly other Debian distro


# Intall apache
$ sudo apt-get install apache2

# Enable SSL module
$ sudo a2enmod ssl

# Restart Apache
$ sudo service apache2 restart

# Create a directory to store the SSLCertificateFile and SSLCertificateKeyFile
$ mkdir /etc/apache2/ssl

# Generate the keys
$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/apache.key -out /etc/apache2/ssl/apache.crt
Generating a 2048 bit RSA private key
...................................+++
................................+++
writing new private key to '/etc/apache2/ssl/apache.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:CA
State or Province Name (full name) [Some-State]:Ontario
Locality Name (eg, city) []:Ottawa
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Ronald Pringadi
Organizational Unit Name (eg, section) []:Engineering
Common Name (e.g. server FQDN or YOUR name) []:ronald-mint.com
Email Address []:webmaster@some-cool-website.com

# Edit your hosts file and add "127.0.0.1 some-cool-website.com"
$ gedit /etc/hosts

# Edit your sites-available ssl config
$ gedit /etc/apache2/sites-available/default-ssl.conf
# Make sure you add the following line under the email
ServerName some-cool-website:443
# Also replace
SSLCertificateFile /etc/apache2/ssl/apache.crt
SSLCertificateKeyFile /etc/apache2/ssl/apache.key

# Activte site
$ sudo a2ensite default-ssl

# Reload Apache
$ sudo service apache2 reload

Open your browser and point it to https://some-cool-website.com. The browser will prompt you that the website is using a self-sign certificate, and do you want to continue and accept that certificate. Answer yes and that’s all to it

PHP and CURL


function browse($url, $postData = null) {
$fields = '';
if(is_array($postData) && sizeof($postData) >= 1){
$fields = http_build_query($postData);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if($fields !=='') {
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
}

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

curl_setopt($ch, CURLOPT_COOKIESESSION, true);
// Write cookie if needed .. also try: dirname(__FILE__) . '/cookie.txt';
curl_setopt($ch, CURLOPT_COOKIEJAR , '/tmp/cookie.txt');
// Read cookie if needed
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookie.txt');

$result = curl_exec($ch);
curl_close($ch);

return $result;
}

Adding New VirtualHost in Apache2

On linux Ubuntu
1. If your apache has /etc/apache2/sites-available directory then just create a new file “dev.newwebsite.com.conf”
with the following content:


ServerName dev.newwebsite.com
DocumentRoot "/var/www/www.newwebsite.com"

# Error handlers
ErrorDocument 500 /errordocs/500.html


AllowOverride All
Options -Indexes FollowSymLinks
Allow from all


2. Also copy the same file into /etc/apache2/sites-enabled

3. Restart your apache

$ /etc/init.d/apach2 restart

4. Edit your hosts file: /etc/hosts
add the following line to it
127.0.0.1 dev.newwebsite.com

5. Open your web browser and open http://dev.newwebsite.com

If you are a windows user and are using xampp then you need to alter the vhost configuration file.
The default xampp file is in
“\xampp\apache\conf\extra\httpd-vhosts”
Then restart your apache

Memcache test connection script


connect('127.0.0.1', 11211) or die ("Could not connect");

// Add it to memcached server
// The parameters are: KEY, VALUE, USE COMPRESSION, EXPIRY IN SECONDS
$memcache->set('MyKey1', 'The value of My Key1 is me', false, 100);

echo $memcache->get('MyKey1');
// It will show you: The value of My Key1 is me
?>

Redis connection test script


"tcp",
"host" => "127.0.0.1",
"port" => 6379));
*/
echo "Connected to Redis";
}
catch (Exception $e) {
echo "Unable to connect to Redis";
echo $e->getMessage();
}

$redis->set("var1", "The value for var1 is me");
echo $redis->get("var1");

// You can alos use exits() function to test if a variable exists or not
echo ($redis->exists("var2")) ? "true" : "false";

Introduction to Logging and Tracing in PHP

If you still tracing variable in php using print_r() or var_dump() then you’ll see them directly in the screen or the web page that you’re working on. This is easy to see, but also prone to problems:

  1. What if visitors see your error trace? Surely you don’t want that.
  2. What if you have a function call that relies on no string has been printed yet, e.g.: header(), ini_set(), these functions will fail and depending on your settings most likely when they fail they don’t show any sign of error.

Best way to do code tracing in PHP is to write the following code into your file – one of the early-executed file, such as config/header file, where you don’t have any output yet:

ini_set('log_errors','On');
ini_set('error_log', '/var/wwwtmp/php.log');
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));

And at the part where you want to trace a certain variable

error_log(__FILE__.' ('.__LINE__.') '.__CLASS__.' :: '. __FUNCTION__ .' :: '. print_r($YOUR_VARIABLE_HERE,true));

By default apache2 and php will output their error in /var/log/apache2/error.log ,but after executing the ini_set above, the error log will be produced in /var/wwwtmp/php.log. And you need to make sure you that directory exists, if not use other directory that www-data has write access to. Why do we need to setup in a different location? Because the default file output doesn’t support showing new lines, you’ll see lot’s of \n. Thus make tracing hard to read.

Internet Explorer (IE) friendly table DOM manipulation

Occasionaly we can manipulate HTML DOM easily by accessing the innerHTML of an element. In IE however, the following elements’ innerHTML are read only: COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR.

This code will fail in IE

tBodyEl.innerHTML = '

' + 'Some Cell Value' + '

';

A more IE friendly solution using DOM table functions.

var row = tBodyEl.insertRow(0);
row.setAttribute('height', '24px');
var cell = row.insertCell(0);
cell.setAttribute('colspan', '7');
cell.innerHTML = 'Some Cell Value';

Extjs – Ext.apply


console.clear();
var a = {
abc : 1,
def : 2
};
var b = {
abc : 1.1,
def : 2.2
};

var c = Ext.apply( a , b ); //Ext.apply overwrites 1st variable (by ref) with the 2nd var

console.log('c');
console.log(c);

console.log('a');
console.log(a);

console.log('b');
console.log(b);

Result:
c
Object { abc=1.1, def=2.2}
a
Object { abc=1.1, def=2.2}
b
Object { abc=1.1, def=2.2}


var a = {
abc : 1,
def : 2
};
var b = {
abc : 1.1,
def : 2.2,
gij : 3.3
};

var d = Ext.applyIf( a , b ); //Ext.applyIf overwrites 1st variable (by ref) with the 2nd var, only if it doesn't exists
console.log('d');
console.log(d);

console.log('a');
console.log(a);

console.log('b');
console.log(b);

Result:
d
Object { abc=1, def=2, gij=3.3}
a
Object { abc=1, def=2, gij=3.3}
b
Object { abc=1.1, def=2.2, gij=3.3}

JSON Jumpstart


/**
* In JSON curly braket is a sign of a new object ({ or })
* Any variable inside the object, also known as object's attribute, is accessible using a period sign (.) object.attribute
* or you can also acces it using an "associative array" such as object['attribute']
* You'll need a Firefox with Firebug extension to see the result from console.log or IE9 with its built-in Developer Tools
*
*/

// =========================
// JSON Object
// =========================
var var1 = {
'var1_1':'value1_1',
'var1_2':'value1_2'
};
console.log(var1);
// The line above will output> Object { var1_1="value1_1", var1_2="value1_2"}
console.log(var1.var1_1);
// The line above will output> value1_1
console.log(var1['var1_1']);
// The line above will output> value1_1

// =========================
// JSON Array
// =========================
// In JSON square braket is a sign of an array ([ or ])
// Any array element is accessible by using a square bracket and followed by an index (0,1,2,...)
var var2 = ['value2_1', 'value2_2'];
console.log(var2);
// The line above will output> ["value2_1", "value2_2"]
console.log(var2[0]);
// The line above will output> value2_1

var var3 = [{
'var3_1':'value3_1',
'var3_2':'value3_2'
},{
'var3_3':'value3_3',
'var3_4':'value3_4'
}];
console.log(var3);
// The line above will output> [Object { var3_1="value3_1", var3_2="value3_2"}, Object { var3_3="value3_3", var3_4="value3_4"}]
console.log(var3[0].var3_1);
// The line above will output> value3_1

Check For Loaded PHP Extensions

Sometimes you want to make sure a certain php extension is loaded or not. These extension can be curl, xmlrpc, or ldap. After all when you move your application from one server to another the configuration not necessarily the same. So here how you do check for loaded or existing php extensions using get_loaded_extensions().


$extNeeded = array('ldap', 'mysql', 'xmlrpc','ron_ext');
$loadedExtension = get_loaded_extensions();
foreach($extNeeded as $ext){ 
 if(!in_array($ext, $loadedExtension)){
  echo 'The application cannot start properly, '.$ext.' extension is missing. 
  The following extensions are needed: '.implode(', ', $extNeeded).'. 
  Terminating application ...';
  die;
 }
}