Archive for the ‘ Coding ’ Category

PHP emailing script

This is a tested script for correctly sending emails via php:

<?php
$to      = '[email protected]';
$subject = 'This is the subject';
$message = 'Hello! this is the bottom text';
$headers = 'Content-type: text/html; charset="UTF-8"' . "\r\n" .
'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers,"[email protected]");
?>

Jason’s default .bashrc file

alias mv='mv -i'
alias df='df -h'
alias du='du -sh'
alias vi=vim
alias scp='scp -P 10022'
alias dir='ls -lah'
alias clearall='history -c;clear'
alias cleard='clear;dir'
alias servicerestart='service httpd restart && service mysqld restart && service vsftpd restart'
alias networkrestart='service iptables restart && service network restart'
alias ipconfig=ifconfig
alias version='cat /etc/redhat-release && uname -a'
alias cdh='cd /var/www/html/sites/www.ewea.org'
alias apachify='chown -R apache:apache . ; find ./ -type d -print -exec chmod 775 {} \;; find ./ -type f -print -exec chmod 664 {} \;'
alias send='rsync -avze "ssh -p 10022 -i /root/.ssh/main_prv_key"'
alias wgett='wget --page-requisites'

EWEA Navigation include

Here’s how to include the EWEA navigation file in templates for microsites:

<div id="navigation">
<?php
// INCLUDE EWEA MENU
$naviURL = "http://www.ewea.org/navigation-file/";
if ($fh = fopen($naviURL,"r"))  {
   fpassthru($fh);
} else {
   echo "<p>Unable to load menu.</p>\n";
}
?>
</div><!-- end #navigation -->

PHP cURL to save remote RSS feed to local xml file

Here’s a script I found to get a remote RSS feed, for example the Feedburner feed, and save it to a local XML file.
This would be useful for moments when you cannot connect to the RSS feed directly in a plugin or application.
You could then try and load the local file instead. Obviously a cron task would be added to run this script to reload the RSS feed a couple of times a day.

<?php
$ch = curl_init("http://feeds.feedburner.com/EWEABlog?format=xml");
$fp = fopen("feedburner.xml", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

This script would then write the contents of the RSS feed to the local file “feedburner.xml”

Google Analyticator

I have installed the WordPress plugin “Google Analyticator” on all the WordPress-based websites.
However, for those that have the “EWEA Master Code” installed, I needed to edit the plugin code.

<script type="text/javascript">
var _gaq = _gaq || [];

// This website code here:
_gaq.push(['_setAccount', '<?php echo $uid; ?>']);
<?php if ($need_to_annon == '1' ): ?>
_gaq.push(['_gat._anonymizeIp']);
<?php endif; ?>
<?php

    # Add any tracking code before the trackPageview
    do_action('google_analyticator_extra_js_before');
    if ( '' != $extra )
            echo "$extra\n";

    # Add the track pageview function
    echo "_gaq.push(['_trackPageview']);\n\n";

    # Disable page tracking if admin is logged in
    if ( ( get_option(key_ga_admin) == ga_disabled ) && ( ga_current_user_is(get_option(key_ga_admin_role)) ) )
            echo "_gaq.push(['_setCustomVar', 'admin']);\n";

    # Add any tracking code after the trackPageview
    do_action('google_analyticator_extra_js_after');
    if ( '' != $extra_after )
            echo "$extra_after\n";

    # Add the final section of the tracking code
    ?>

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>

Now we add the EWEA Master Code in the plugin settings area:

EWEA Master

For copying/pasting:

// EWEA's master code here:
  _gaq.push(['_setAccount', 'UA-4609386-40']);
  _gaq.push(["_setDomainName", "none"]);
  _gaq.push(["_setAllowLinker", true]);
  _gaq.push(["_trackPageview"]);

 

Create a local copy of a web page

Using the following command on linux, you can create a local copy of a web page with all images and files saved:

wget --page-requisites http://example.com/

 

MySQL commands

Backup server data and rsync to offsite server

This is the current backup script used on all the web servers.
(Last updated 26 May, 2016)

#!/bin/bash
# srv.sh
# Backup of files to offsite server
# Jason Bickley, Senior Web Manager, WindEurope
# 26 MAY 2016

#==== RECEIVE VARIABLES FROM COMMAND LINE ====#
FREQ=$1
SERVER=$2
EXCLUDE="--exclude-from=/root/backup/excludelist"
OPTION=$3
DEST=backup.ewea.org
DATE=$(date +"%Y%m%d %T")
LOG=/var/log/backupSRV_log

#==== SET TIMESTAMP =============#
touch /root/.timestamp /etc/.timestamp /var/.timestamp

#==== DAILY BACKUP OF SERVER ====#
rsync -avzhe "ssh -p 10022 -i /root/.ssh/"$SERVER"_prv_key" $EXCLUDE $OPTION / root@$DEST:/backups/$FREQ/$SERVER/

#=== CONFIRM SUCCESS IN LOG FILE ====#
echo $DATE Backup successful! $DEST:/backups/$FREQ/$SERVER/ >> $LOG


To use it, you just have to run: srv.sh {freq} {servername} {option}
For example:

cd /root/Scripts/backup/
./srv.sh daily web1 --delete

Contents of /root/backup/excludelist


/bin
/boot
/cgroup
/db
/dev
/lib
/lib64
/lost+found
/media
/mnt
/opt
/proc
/run
/sbin
/selinux
/srv
/sys
/tmp
/usr
/var/cache
/var/db
/var/empty
/var/ftp
/var/games
/var/gandi
/var/local
/var/lock
/var/lost+found
/var/mail
/var/nis
/var/opt
/var/lib/php/session
/var/preserve
/var/run
/var/tmp
/var/www/html/sites/events
/var/www/html/sites/globalwindday.org
/var/www/html/sites/solutionwind.com
/var/www/html/sites/stats.ewea.org
/var/www/html/sites/testing.ewea.org
/var/www/html/sites/www.ewea.org
/var/www/html/sites/www.ewea.org/fileadmin/videos/health-and-safety
/var/yp

Using “SED” command to replace URL strings in SQL files

We want to change all references of events.ewea.org to www.ewea.org in an SQL dump, so a sed command line for this may be:

sed 's/OLDPHRASE/NEWPHRASE/g' database.sql > database.new.sql

sed 's/events\.ewea\.org/www\.ewea\.org/g' event.sql > event.new.sql

Note: We have to escape the periods and any slashes.

This is particularly useful when migrating a WordPress website off the development server and onto the production server.

Google Analytics Multiple Tracking Code

Here is a cool trick I have implemented across the EWEA web platform:

<script type="text/javascript">
 var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'UA-xxxxxxxx-yy']);
	_gaq.push(["_setDomainName", "none"]);
	_gaq.push(["_setAllowLinker", true]);
	_gaq.push(["_trackPageview"]);
 _gaq.push(['_setAccount', 'UA- xxxxxxxx-zz'']);
	_gaq.push(["_setDomainName", "none"]);
	_gaq.push(["_setAllowLinker", true]);
	_gaq.push(["_trackPageview"]);
 (function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	})();
</script>

This goes at the bottom of the tags and what it does is this:

• The “yy” code is for the local site, i.e. our individual event site or our blog.
• The “zz” code is common on all the sites. This gives me a global view over all the sites as to the most popular content across all platforms.