Archive for the ‘PHP’ category

How To : Prevent Songs Download (Part-II)

March 28th, 2010

In the first post I showed how to setup basic audio player and play a song and left with this important part to show how we can secure our songs and prevent downloads. So lets see how we can make it most secured so that maximum users failed to download or get a direct access to the download link. After writing this, I will hope to hear from you, if there are any better ways we can make a song secured. Please discuss freely, hopefully, it will help others who are seeking same information.

To me best solution is, you have 2 types of songs of same song. One type contains only 30/40 seconds and you let them play on browser and if people want to buy then ask them to use user id and password to get full song access. But if you don’t want to go in that way, follow me here

Main Concept: Let’s not understand the users where they are downloading or where they are playing the song from. I mean lets hide the download location! And then let’s stop direct access to the folder location.

Lets say you have directory name /music where you are keeping all the songs. We will hide this location and will stop the direct access. First of all rename the folder where you are keeping all these secret weapons. (I.e : eTsscXXzwolF) and then create a htaccess file in that directory and put the following codes

Options -Indexes
<files *>
order allow,deny
deny from all
</files>

after placing this code in the directory, you will see you can’t get a direct access to the location via browser. So we have protected the direct access but we haven’t hides the directory yet. So let’s do it now…i have got this nice script that hide the location and let you download the file. I don’t need to allow people to download file but I need the location hider. So i modified this script for my needs.

//filename: hide.php
// Usage: <a href="hide.php?file=playlist.xml">How to use</a>
// Path to hide files (will not be revealed to users so they will never know your file's real address) 
$hiddenPath = "xrrcOXX/";
// VARIABLES 
if (!empty($_GET['file'])) {
    $file = str_replace('%20', ' ', $_GET['file']);
    $category = (!empty($_GET['category'])) ? $_GET['category'] . '/' : '';
} 
$file_real = $hiddenPath . $category . $file; 
$ip = $_SERVER['REMOTE_ADDR']; 
// Check to see if the hide script was called 
if (basename($_SERVER['PHP_SELF']) == 'hide.php') {
    if ($_SERVER['QUERY_STRING'] != null) {
// HACK ATTEMPT CHECK 
// Make sure the request isn't escaping to another directory 
//if (substr($file, 0, 1) == '.' ¦¦ strpos($file, '..') > 0 ¦¦ substr($file, 0, 1) == '/' ¦¦ strpos($file, '/') > 0)  { 
        if ((substr($file, 0, 1) == '.') || (strpos($file, '..') > 0) || (substr($file, 0, 1) == '/') || (strpos($file, '/') > 0)) {
// Display hack attempt error 
            echo("Hack attempt detected!");
//die(); 
        }
// If requested file exists 
        if (file_exists($file_real)) {
            $header_file = (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) ? preg_replace('/\./', '%2e', $file, substr_count($file, '.') - 1) : $file;
// Prepare headers 
            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: public", false);
            header("Accept-Ranges: bytes");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: " . filesize($file_real));
            if ($stream = fopen($file_real, 'rb')) {
                while(!feof($stream) && connection_status() == 0) {
                    set_time_limit(0);
                    print(fread($stream,1024*8));
                    flush();
                }
                fclose($stream);
            }
        }else {
       // Requested file does not exist (File not found) 
            echo("Requested file does not exist");
            die();
        }
    }
}

and now let’s call our previous example to see how we can use it ….

<h3>I Need You</h3>
<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='300' height='24' id='player1' name='player1'>
    <param name='movie' value='player.swf'>
    </param><param name='allowfullscreen' value='true'>
    </param><param name='allowscriptaccess' value='always'>
    </param><param name='playlistsize' value='180'>
    </param><param name='flashvars' value='hide.php?file=vol11.mp3&duration=231'>
    <embed id='player1'
           name='player1'
           src='player/player-viral.swf'
           width='300'
           height='24'
           allowscriptaccess='always'
           allowfullscreen='true'
           flashvars="file=hide.php?file=vol11.mp3&duration=231"
           />
</param></object>

Now these songs are more secured than before and if you try to access from the link you get by firebug, it wont work instead you will get a blank page download. You can try it yourself ;) and let me know if you have any questions.

How To : Simple Audio Streaming [Part-I]

March 26th, 2010

Starting the post with a well known verse “Your Songs Belong to Us”. Sounds funny but this is really true that you can’t hide your songs on the web. Your all songs that you put in your server, literally you also put on other computers . Because an advance user know how to download your songs/videos. You may use RTMP protocol or HTTP protocol for streaming and you may spend extra money to get a media server such as FMS, Wowza etc but it will hurt you that still you can’t save your songs from the web soldiers. What this RTMP connection does is, it can protect you from maximum users, because maximum general users will not get a direct link of download location of your songs. My question is, if I spend extra money , time and still can’t protect my songs from all users then what’s the point to spend extra money? Rather how about if we set it up such way so that I still can protect my songs that media server allows me to and I dont have to spend extra money and time?

Let’s say you have song albums, you don’t want let users to download your songs but listen to them and you want to pretend direct download from 95% users…i’m gonna discuss how we can do it. This part will describe the basic setup and how we can play a song on the web. So first part is going to be pretty simple but second part will be most interesting and important part.

No extra requirement needed! You have an apache server that will work. So let’s set it up….and well, we need a media player like JW Player. It’s free for no-commercial purpose. So we will use the free version for our example. Let’s download the free version and you have setup wizard to make your life easy. Once you have the player you can use the following example codes that has 2 tags for each song/playlist.

<script type='text/javascript' src='player/swfobject.js'></script>
<h3>I Need You</h3>
<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='300' height='24' id='player1' name='player1'>
    <param name='movie' value='player.swf'>
    </param><param name='allowfullscreen' value='true'>
    </param><param name='allowscriptaccess' value='always'>
    </param><param name='playlistsize' value='180'>
    </param><param name='flashvars' value='player/player-viral.swf'>
    <embed id='player1'
           name='player1'
           src='player/player-viral.swf'
           width='300'
           height='24'
           allowscriptaccess='always'
           allowfullscreen='true'
           flashvars="file=playlist.xml&playlist=bottom&playlistsize=180"
           />
</param></object>

You may wonder why I have 2 tags and for the same playlist. Well, IE doesn’t understand embed tag and Firefox, Safari, Chrome don’t understand object tag. Funny eh…this is why, we have to keep the both tags to run them in all browsers. Ok, now let’s create the xml file that will work as our playlist. Here is a sample list xml file

<rss version="2.0" 
     xmlns:media="http://search.yahoo.com/mrss/"
     xmlns:jwplayer="http://developer.longtailvideo.com/trac/wiki/FlashFormats">
    <channel>
        <title>Example media RSS playlist</title>
        <item>
            <title>MP3 Audio</title>
            <link>http://www.test.com/</link>
            <description>I miss you..</description>
            <media :content duration="44" />
            <media :credit role="author">Mr. X</media>
            <media :content url="you.mp3" />
            <media :thumbnail url="images/test.JPG" />
        </item>
 
        <item>
            <title>MP3 Audio</title>
            <link>http://www.test.com/</link>
            <description>Oye Oye..</description>
            <media :content duration="44" />
            <media :credit role="author">Mr. Y</media>
            <media :content url="you.mp3" />
            <media :thumbnail url="images/test.JPG" />
        </item>
        <item>
            <title>MP3 Audio</title>
            <link>http://www.test.com/</link>
            <description>I need you..</description>
            <media :content duration="44" />
            <media :credit role="author">Mr. X</media>
            <media :content url="test.mp3" />
            <media :thumbnail url="images/test.JPG" />
        </item>
    </channel>
</rss>

Now, simply just run the page where you placed your player code. And you will see something like the following screenshot.

 

Example Play List

Example Play List

  

Make sure you have songs in the same directory or the path you gave in the xml file. This is where we are done with basic setup songs list. But you see anybody can download it from xml list by finding the url. So we are left with main important part of this tutorial. Which I will do in the next part. Will discuss how we can make this list of songs secured so that most of the users face trouble to get it. Stay tune…

Regular Expression to Find All Mentioned Names by ‘@’

December 12th, 2009

Most of the time we use ‘@’ to mention someone’s name in email thread, forum, etc. How about to find those mentioned names using PHP regular expression? Let’s consider the following text.

“Hey @Junal how about going for a vacation to @Srimangal? @Jewel said it’s an awesome place”
We will find all names that is mentioned by @ here. So let’s write the pattern first.

$pattern = “/^(?:[a-zA-Z0-9?. ]?)+@([a-zA-Z0-9]+)(.+)?$/”;

See, first portion of the pattern is optional, some one can start your name @junal or hey @junal right. And then we are matching with ‘@’ separating them from @ sign. Rest portion of the patter is quite easy, as we can keep text after the name (I.e @junal you suck)

Ok, now let’s use the php preg_match() function to find the matches. If we find the matched it will return 1 else 0.

$pattern = "/^(?:[a-zA-Z0-9?. ]?)+@([a-zA-Z0-9]+)(.+)?$/";
$str = "Hey @Junal hey how are you?";
preg_match($pattern, $str, $matches);
print_r($matches);
//Output : 
Array
(
    [0] => Hey @Junal hey how are you?
    [1] => Junal
    [2] => hey how are you?
)

So, if we want to find first matched name then it’s pretty straight forward to get it from $matches[1]
but what if we want to find multiple name from a text? Well, then we have to search $matches[2] if there is anymore mentioned name wit @ right?… let’s do it this way…

do {
   preg_match($pattern, $matches[2], $more_matches);
   $name_list[$counter++]  = $more_matches[1];
   $count = count($more_matches);
   $matches[2]=$more_matches[($count-1)];
   $more_matches = "";
   } while($count>=3);

this above code might be confusing. So let’s see the complete function that returns us an array of names that are mentioned by ‘@’ and well, we will also remove the duplicate names.

< ?php
/*
 * isn't the name self explanatory ?
 */
function giveme_names_from_at($str) {
    $pattern = "/^(?:[a-zA-Z0-9?. ]?)+@([a-zA-Z0-9]+)(.+)?$/";
    $str = trim($str);
    preg_match($pattern, $str, $matches);;
    if($matches) {
        $counter = 0;
        $name_list = array();
        $name_list[$counter++] = $matches[1];
 
        do {
            preg_match($pattern, $matches[2], $more_matches);
            $name_list[$counter++]  = $more_matches[1];
            $count = count($more_matches);
            $matches[2]=$more_matches[($count-1)];
            $more_matches = "";
        } while($count>=3);
 
        if(!empty($name_list)) {
            $all_names = array();
            $i = 0;
            foreach ($name_list as $key => $value) {
                if (!is_null($value) && (!in_array($value, $all_names))) {
                    $all_names[$i] = $value;
                    $i++;
                }
            }
        }
        return $all_names;
    }
}
 
//Example 
 
$str = "Hey @Junal how about going for a vacation to @Srimangal? @Jewel said it's an awesome place";
$names = giveme_names_from_at($str)
print_r($names);
 
//Output: 
Array
(
    [0] => Junal
    [1] => Srimangal
    [2] => Jewel
)
?>

Ok well, output shows what we needed. But using regular expression is not always a good idea as it’s slower than standard string manipulation functions. How would you like to find these answers without using RE? Or can we improve this pattern to make It smarter?

Optimize All JPEG Images With Jpegtran Utility

July 15th, 2009

I was looking for an utility that compress an image without losing the current quality of it. According to Yslow guideline it says “Jpegtran does lossless JPEG operations such as rotation and can also be used to optimize and remove comments and other useless information (such as EXIF information) from your images. ”

Installing (Linux)

  • Download jpegtran library from here

  • Unpack and paste the executable file under /usr/bin folder.

  • Open the command-line and try this > jpegtran -h command to check if its working

Options:

-Optimize

Perform optimization of entropy encoding parameters.

-Progressive

Create progressive JPEG file.

-Restart N

Emit a JPEG restart marker every N MCU rows, or every N MCU blocks if “B” is attached to the number.

-Scans file

Use the scan script given in the specified text file.

Command example:

> jpegtran -copy none -rotate 270 -optimize /home/junal/Desktop/Junal/DSC_4164.JPG > /home/junal/Desktop/Junal/DSC_4166.JPG

it reduced the current size 3.4 MB to 3.2MB, keeping the same quality of the image, bingo!

The jpegtran command-line program is useful to:

  • Optimize the Huffman coding layer of a JPEG file to increase compression,
  • Convert between progressive and non-progressive JPEG formats,
  • Eliminate non-standard application-specific data inserted by some image programs, or
  • To perform certain transformations on a file, such as:
    • grayscaling,
    • rotating and flipping (within certain limits), and
    • cropping

to make all these tasks easier you can use imgopt which does all these above easier way. You just need to download the library file and paste it in the right path , now you just have to show the image folder that you want to optimize. And you can do it for both JPEG and PNG file as well.

Installing (Windows)

Windows users can get an executable file from here http://sylvana.net/jpegcrop/

Reference: http://en.wikipedia.org/wiki/Jpegtran

Presenting “Developing Facebook Application” at PHPExperts Semianr 2009

May 17th, 2009

Today, I was really honored to present “how to develop facebook application” at PHPExperts Semianr 2009. Indeed, that was a great experience for me to be in front of bunch of talent guys from whole Bangladesh. Though, it was not possible to show all important points/notes/stories by one presentation at a time, so my target audience were those who were willing to start developing facebook application and my aim was to make it as simple as possible, so that they can start…..

I dont know how successful I was for this…but I will be really happy if I see people are getting interest about developing facebook application.

Personally, I’m very much thrilled after this seminar, because I met lots of people I know from twitter, friendfeed or facebook. Now, i’m pretty sure we have this natural bonding between us. I would like to thank everybody whom I met or who enjoyed my presentation. Your suggestions are always welcome to me. If I ever get any chance again in any other seminar, I will try to talk about advance facebook application developing.

Thanks to all PHPExperts!

DOWNLOAD the source codes of the example i showed in the presentation

Check out the reference from here

Get Adobe Flash playerPlugin by wpburn.com wordpress themes