Technical Archives - Mohamed Shaer https://shaer.me/blog/category/technical/ Software Developer Tue, 26 Oct 2021 09:27:40 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.2 https://shaer.me/wp-content/uploads/2014/11/cropped-xjZjS-54549aab_site_icon-1-32x32.png Technical Archives - Mohamed Shaer https://shaer.me/blog/category/technical/ 32 32 Introduction to Memcached and how to use it with PHP https://shaer.me/blog/technical/how-to-use-memcached-with-php/ https://shaer.me/blog/technical/how-to-use-memcached-with-php/#respond Sat, 01 Nov 2014 14:31:15 +0000 http://shaer.me/?p=1239 Memcached is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of ti-mes an external data source (such as a database or API) must be read

The post Introduction to Memcached and how to use it with PHP appeared first on Mohamed Shaer.

]]>
Hello all,
today I am going to talk about Memcached how to install/configure and using it along side with with PHP and any database, lets start.

memcached

What is Memcached?

Memcached is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of ti-mes an external data source (such as a database or API) must be read
Wikipedia: Memcached

Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering.
Memcached

So Memcached is a key-value store for small chunks of data “1MB” in RAM, then you can access these data any time from the RAM instead of querying the database again or read them from cached files, and of course all the data going to be deleted when you switch of your machine, also Memcached has the ability to distribute these keys/values in multiple servers. Memcaced is intended for use in speeding up dynamic web applications by alleviating database load.

How to Install Memcached

sudo apt-get install memcached

This command going to install memcached and you can now use telnet to connect to it and start setting/getting values

telnet localhost 11211

But in this tutorial we are going to use libmemcached-tools which is a command line tools for talking to memcached so go ahead and type

sudo apt-get install libmemcached-tools

after installing libmemcached-tools now we have some tools that we can use from the command line like memccat, memcdump, etc, we are going to use some of them for the sake of testing and debugging.

Creating Your First Memcached Record

First of all we are going to make new file called product and echo any value into it “190”
the second command memccp which take we specified out server to be localhost as we installed memcached locally and the third option is the file name

echo "190" > product
memccp --servers localhost product

now we stored a new key-value in memcached with the file name as a key and file contents as a value; what about retrieving it? to retrieve a value from memcached we use the command memccat

memccat --servers localhost product

This command going to output the value that we just added which is 190.

Some useful command that you can use is also memcdump which is useful for debugging as it is going to dump all the keys in memcached, memrm which is going to remove a specific key you provide, memcstat which going to display some statistics about memcached and finally memflush that can be used to invalidate all the keys on the server.

wanna try them?, run these commands one by one

#dump all the keys in the server
memcdump --servers localhost

#create new file
echo "80" > product80

#copy this file to memcached
memccp --servers localhost product80

#check the newly created key-value
memccat --servers localhost product80

#remove the newly created item
memcrm --servers localhost product80

#flush all the server
memcflush --servers localhost

#get the status
memcstats --servers localhost

 

Using Memcached with PHP

Now we know enough about memcached from the command line, what about creating our first php script to create/read/update/delete records from memcached.

First of all we have to install php5-memcache then restart your apache

sudo apt-get install php5-memcache
sudo service apache2 restart

create a new file in your www folder called memcached.php and add these line into it

//create a new object of memcache
$memcache = new Memcache;
 
//trying to connect to memcached server locally using port number 11211
$memcache->connect('localhost', 11211) or die ("Could not connect");
 
//store new value
$memcache->set("key", "value");
 
//retrive the previouly created value
$result = $memcache->get("key");
 
echo $result;

In the previous example we created a new memcache object and then used the method connect to make a connection with our server, we can also use the method addServer() to add as many servers as we want.

Then we used the method set() to set a new key, the method set() take two parameters key & value and could take more parameters for the expiration date of the item if you want.

finally we retrieved the newly created item by using the method get() which take the key of the item that we want to retrieve as a parameter.

Real World Example

Now we have created a simple PHP write/read example to demonstrate how to usage of memcached now we are going to create a better example that we may use something like it in our websites.

Suppose we have a page the display some information about specific product, each time a user open this page we query the database to get these data,  we want to cache these data instead of querying the database every time.

First of all I am going to create a method to retrieve the product from the database and for the sake of simplicity I am not going to query the database am just going to return an array of some dummy data

function get_product_data_from_db($product_id){
    //Simulate retrieving data from the database for simplicity.
    $product = array(
                  "product_id"  => $product_id,
                  "title"       => "Test Product Name",
                  "description" => "Some Description about this product",
                  "image"       => "http://www.example.com/url/to/the/product/image.jpg",
                  "price"       => "20.00",
              );
    //sleep for 5 seconds to simulate a waiting time.
    sleep(5);
    return $product;
}

Then I am going to create another method in the same file which we are going to use to retrieve the product data

function get_product($product_id){
    //connect to the memcached server
    //of course it is not the best place to make the connection
    //but I just created it here for the sake of simplicity again :).
    $memcache = new Memcache;
    $memcache->connect('localhost', 11211) or die("Could not connect");
     
    //get the product from the cache
    //going to return false if the key didn't exist on the cache
    $product_data = $memcache->get($product_id);
     
    //if product data isn't false then return it
    if($product_data)
        return $product_data;
         
    //else we are going to retrieve the data from the database
    $product_data = get_product_data_from_db($product_id);
     
    //store the reterieved data in the cache
    $memcache->set($product_id, $product_data);
     
    //return the data
    return $product_data;
}

Now we have a method which is used to get the data from the cache, and if it failed to retrieve it, It will get the data from the database and store it in the cache to use the cached version data in the next time.

Finally I am going to write a line of code to get product data and print it.
in the end of the file add

print_r(get_product(100));

Now point your browser to this page you will notice that the page going to take a little bit long time to load in the first time “due to the sleep(5)” which mean that it didn’t find the data in the cache and going to query the database to get it; then refresh the page again it should work fine because the data is in the cache now. if you refreshed the page again and again it will keep getting the data from the cache.

The full code

<?php
function get_product_data_from_db($product_id){
    //Simulate reteriving data from the database for simplicty.
    $product = array(
            "product_id"  => $product_id,
            "title"       => "Test Product Name",
            "description" => "Some Description about this product",
            "image"       => "http://www.example.com/url/to/the/product/image.jpg",
            "price"       => "20.00",
        );
 
    //sleep for 5 seconds to simulate a waiting time.
    sleep(5);
 
    return $product;
}
function get_product($product_id){
    //connect to the memcached server
    //of course it is not the best place to make the connection
    //but I just created it here for the sake of simplicity again.
    $memcache = new Memcache;
    $memcache->connect('localhost', 11211) or die("Could not connect");
 
    //get the product from the cache
    //going to return false if the key dont exist on the cache
    $product_data = $memcache->get($product_id);
 
    //if product data isn't false then return it
    if($product_data)
        return $product_data;
 
    //else we are going to retrieve the data from the database
    $product_data = get_product_data_from_db($product_id);
 
    //store the reterieved data in the cache
    $memcache->set($product_id, $product_data);
 
    //return the data
    return $product_data;
}
print_r(get_product(100));

In the next post I am going to talk about how to make this cache persistent, as you might know if you rebooted your computer all the data in the cache going to be deleted, simply because it is on the RAM.

That is all what I have for now, if you have any questions don’t hesitate and post your comment

Thanks!

The post Introduction to Memcached and how to use it with PHP appeared first on Mohamed Shaer.

]]>
https://shaer.me/blog/technical/how-to-use-memcached-with-php/feed/ 0
How to Enable Ad-hoc Connection on your Android https://shaer.me/blog/technical/how-to-enable-ad-hoc-connection-on-your-android/ https://shaer.me/blog/technical/how-to-enable-ad-hoc-connection-on-your-android/#comments Thu, 09 Aug 2012 01:58:46 +0000 http://shaer.me/blog/?p=893 Hello, I was searching for a long time how to enable ad-hoc connections on my HTC chacha and finally I found it!, so I decided to share my experience with you. btw I found many ways but guess what?! most of them didn’t work 🙁 lets stop talking and start enjoying the unlimited internet connection […]

The post How to Enable Ad-hoc Connection on your Android appeared first on Mohamed Shaer.

]]>

Hello,
I was searching for a long time how to enable ad-hoc connections on my HTC chacha and finally I found it!, so I decided to share my experience with you.
btw I found many ways but guess what?! most of them didn’t work 🙁

lets stop talking and start enjoying the unlimited internet connection on your mobile 🙂

Ubuntu Users

First of all you had to install hostapd

“In simple words, hostapd allows you to create software wifi access points allowing decent amount of configuration options. In rest of this post, I will show how to create a software access point in Linux using hostapd and share your internet to the devices through it”

To Install hostapd just type this command on the terminal

sudo apt-get install hostapd

Then, open a text editor program, for example gedit. Copy the following into it.

interface=wlan0
driver=nl80211
ssid=MyAP
hw_mode=g
channel=11
wpa=1
wpa_passphrase=MyPasswordHere
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP CCMP
wpa_ptk_rekey=600

Please don’t forget to fill in the name of your network after “ssid=”, as well as the password after “wpa_passphrase=”.

After all these, save the file as hostapd.conf in your home folder.

Then create a normal ad-hoc network from the wireless menu from the top bar click on “Create New Wireless Network

after the new network created successfully proceed to the next and the final step

Now, in your terminal:

sudo hostapd hostapd.conf

Turn the wifi connection on in your devices and enjoy the fast network share!

Windows Users

You can install Virtual Router

Project Description

Virtual Router turns any Windows 7 or Windows 2008 R2 Computer into a Wifi Hot Spot using Windows 7’s Wireless Hosted Network (Virtual Wifi) technology.

What is Virtual Router?

Virtual Router is a free, open source software based router for PCs running Windows 7 or Windows Server 2008 R2. Using Virtual Router, users can wirelessly share any internet connection (Wifi, LAN, Cable Modem, Dial-up, Cellular, etc.) with any Wifi device (Laptop, Smart Phone, iPod Touch, iPhone, Android Phone, Zune, Netbook, wireless printer, etc.) These devices connect to Virtual Router just like any other access point, and the connection is completely secured using WPA2 (the most secure wireless encryption.)

Download Virtual Router

http://virtualrouter.codeplex.com/downloads/get/93540

 Preparing your Wireless Connection

After installing Virtual Router and restarting, open the application this window will appear

Type your network name ,, and your password ,, choose network to share ,, and click on Start Virtual Router

Turn the wifi connection on in your devices and enjoy the fast network share!

 

Resources

http://nims11.wordpress.com/2012/04/27/hostapd-the-linux-way-to-create-virtual-wifi-access-point/

http://exain.wordpress.com/tag/hostapd/

http://zhangyou.wordpress.com/2010/08/26/easily-turn-your-ubuntu-into-a-virtual-router/

http://virtualrouter.codeplex.com

The post How to Enable Ad-hoc Connection on your Android appeared first on Mohamed Shaer.

]]>
https://shaer.me/blog/technical/how-to-enable-ad-hoc-connection-on-your-android/feed/ 62