I have a software app that checks for updates and downloads them from http://www.some_random_website.com/updatefile.rar
However, I’ve noticed that ISPS tend to cache these files so the software app isnt always getting the latest file.
step 1 – create a php function to download a file
<?php $filename = $_GET['filename']; $path = $_SERVER['DOCUMENT_ROOT'] . "/$filename"; if ($fd = fopen($path, "r")) { $fsize = filesize($path); header("Cache-Control: no-cache, must-revalidate"); header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); header("Content-type: application/octet-stream"); header("Content-Disposition: filename=\"" . $filename . "\""); header("Content-length: $fsize"); header("Cache-control: private"); //use this to open files directly while (!feof($fd)) { $buffer = fread($fd, 2048); echo $buffer; } } fclose($fd); ?> |
step 2 – rewrite urls so that when requesting /some_file.rar, it redirects to the php app as defined
Options +FollowSymlinks RewriteEngine on RewriteRule ^(.+)\.rar$ ./getfile.php?filename=$1.rar [NC] |
So some clever hackers managed to run an iframe injection attack on my site
heres how I cleaned it
find ./ type f -exec sed -i 's/<iframe src="http:\/\/byh1.co.cc\/index.php?tp=25971e546d04c7c2" width="1" height="1" frameborder="0"><\/iframe>//g' {} \; |
This is a departure from my usual posts, but I think everyone can make use of this.
I have encountered this error, which to my surprise occurred on a slave database.
mysql> SHOW SLAVE STATUS\G
error ‘Duplicate entry ’4534534′ for key 1′ on query ‘ INSERT INTO customer_history (DateStamp) VALUES (NOW())
solution :
mysql> set global sql_slave_skip_counter = 1;
Query OK, 0 rows affected (0.01 sec)
mysql> slave start;
Query OK, 0 rows affected (0.00 sec)
This will skip the error and continue replicating from the master
Pretty straightforward
To compress mysqldump output :
mysqldump -uroot -psome_password db_name| gzip -c > db_name.gz |
or alternatively, to compress it to a file on another host
mysqldump -uroot -psome_password dbname | gzip -c | ssh user@host -p22 'cat > /root/db_name.sql.gz' |
To restore a database from a compressed file
gunzip < db_name.gz | mysql -uroot -psome_password db_name |
Previously I was using SMS for notifications of failures on certain mission critical business servers. I recently decided to use twitter instead. The main reason being that twitter is free, and with the twitter for iphone app, I get push notifications immediately (actually faster than SMS).
Twitter API uses OAUTH, so its a little tricky, but not wildly complex – anyone with basic PHP knowledge should be able to implement it
Heres how to do it
* go to dev.twitter.com – sign in with the username you want to send notifications from
* click on “Register an app”
* Fill in the fields – dont worry about a callback url – we wont be using it
* change access type to “Read & Write”
* once you have completed the registration, click “view your applications” on the right hand side
* click “edit details”
* click “application detail” on the right
* copy “consumer key” and “consumer secret”
* click on “My access token”
* copy “Access token” and “Access token secret”
Ok – now we have all the info needed to start.
For the twitter integration we will use Abraham Twitter OAuth library
The only 2 files you need are “twitteroauth/OAuth.php” and “twitteroauth/twitteroauth.php”. Stick these wherever you want. For purposes of this demo, I’m putting them in the same folder as my index.php
<?php require_once 'TwitterOAuth.php'; $CONSUMER_KEY = "????"; $CONSUMER_SECRET = "????"; $OAUTH_TOKEN = "????"; $OAUTH_SECRET = "????"; //create connection $connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET, $OAUTH_TOKEN, $OAUTH_SECRET); //verify account $content = $connection->get('account/verify_credentials'); //post status update $connection->post('statuses/update', array('status' => "My first status update via twitter")); //mention someone $connection->post('statuses/update', array('status' => "@zayinkrige thanks for the blogpost")); //DM someone $connection->post('statuses/update', array('status' => "D zayinkrige thanks for the blogpost")); ?> |
Thats pretty much all there is to using twitter. For a full list of twitter api functions, visit http://api.twitter.com
By default, MYSQL with INNODB engine doesn’t create 1 file per table, but rather stores everything in the system file.
Step 1:
edit /etc/mysql/my.cnf
[mysqld] innodb_file_per_table |
This will only enable file per table. It will not convert your existing innodb tables into files
There are a couple of ways of doing this
1st Method
mysqldump -udbuser -ppassword db_name > outfile.sql mysql -udbuser -ppassword db_name < outfile.sql |
2nd Method – run this sql script for each table in your database
ALTER TABLE tbl_name ENGINE=INNODB; |
This means each table is stored in its own file.
Later on, you can look at moving each file to its own hard disk for performance gains
This snippet is for 2 way encrypted socket communications between us and a server.
This is *NOT* for normal web HTTPS traffic.
import java.net.*; import java.security.*; private Socket setupSocket() { try { String serverIP = "192.168.0.1"; Integer serverPort = 8880; Integer timeOut = 5000;//5000 millisecond timeout //get the address and port of the server InetAddress addr = InetAddress.getByName(serverIP); SocketAddress sockaddr = new InetSocketAddress(addr, serverPort); //get a keystore instance KeyStore localKeyStore = KeyStore.getInstance("JKS"); //password for keystore char[] localKeyStorePassword = "keyStorePassword".toCharArray(); //load the keystore localKeyStore.load(new FileInputStream("/var/local/keystore.jks"), localKeyStorePassword); //Create the trust manager factory TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); //point it to the local keystore for certificates tmf.init( localKeyStore ); //create the keymanager KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); //point it to the local store for certificates kmf.init(localKeyStore, localKeyStorePassword); //create and initialize a secure random number generator SecureRandom secureRandom = new SecureRandom(); secureRandom.nextInt(); // Force initialisation to occur now. //create our sslcontext and set it as type TLS SSLContext sslContext = SSLContext.getInstance("TLS"); //initialize it and tell it where the keystore and truststore are sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), secureRandom); //create a socket factory from our newly initialized sslContext SSLSocketFactory sf = sslContext.getSocketFactory(); //get a socket from the factory SSLSocket skt = (SSLSocket)sf.createSocket();//create the socket but dont connect yet //connect to the previously created address/port with a timeout skt.connect(sockaddr, timeOut); //set the timeout for any comms skt.setSoTimeout(timeOut); return skt; }catch( Exception e ) { return null; } } |
This is a very basic example of using memcache + PHP
Use at your own peril
$memcache = new Memcache; $memcache->connect("127.0.0.1"); $sql = "select * from some_huge_table where tx_date <= now()-365 limit 0, 5000"; $key = md5($sql); $query = $memcache->get($key); //the query isnt in the cache if ($query == null) { $query = $this->db->query($sql); $query = $query->result(); //put it in the cache $memcache->set($key,$query,0,600);//10 minute expiry } if (count($query) > 0) { //do something with $query } |
This example loads memcached, looks for a key, and if its not there, stores it. SIMPLE
****UPDATE****
Today while going through CI framework, I realized that CI can do its own query caching, albeit to disk. For more info on CI query caching, look go here
To change this to memcached caching should be a cinch, and indeed, it is. Head over here to see how.
So without having to change a single line of code in your application, you can take full advantage of memcached for caching query results
Memcache is a very simple caching system that uses memory to store objects. As you may already know, memory is faster to read than hard drive. A site will take a lot less time to read a database result cached in memory. To make the best use of memcache, you should install the memcached module. For this post we used Ubuntu Server 10.04, but all commands should work on most Ubuntu editions.
I have chosen to use memcached, rather than memcache. Have a look here to view a comparison
First, install the memcached package, php-pear (required for pecl), php5-dev (required for phpize) and libmemcached-dev
sudo apt-get install memcached sudo apt-get install php-pear sudo apt-get install php5-dev sudo apt-get install libmemcached-dev |
next, install memcached using pecl
sudo pecl install Memcache |
Also, we need to enable the memcache extension on php:
sudo echo "extension=memcache.so" > /etc/php5/apache2/conf.d/memcache.ini |
Add the following line to your php.ini file.
memcache.hash_strategy="consistent" |
You can add it anywhere in the file.
Next you need to start an instance of memcache, you can start a daemon with the following command:
memcached -d -m 2048 -l 10.0.0.40 -p 11211 |
If you are only using a single server, then you only need to include this line to your site’s settings.php file.
$conf['cache_inc'] = '/sites/all/modules/memcache/memcache.inc'; |
The final step is to restart apache and then switch your site back online if it was offline.

Categories
Tag Cloud
Blog RSS
Comments RSS
Last 50 Posts
Back
Void « Default
Life
Earth
Wind
Water
Fire
Light 