satishgaudo.com

Understanding technology

Php: Function to remove unwanted utf-8 chars

Function removes unwanted utf-8 characters except correct ASCII & UTF-8 characters (excluding 4-byte+ UTF-8 sequences).

function removeInvalidUtf8Chars($s)  
{
 
		if(empty($s)) return $s;
			$s = preg_match_all("#[\x09\x0A\x0D\x20-\x7E]|
		[\xC2-\xDF][\x80-\xBF]|
		\xE0[\xA0-\xBF][\x80-\xBF]|
		[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|
		\xED[\x80-\x9F][\x80-\xBF]#x", $s, $m );
			return implode("",$m[0]); 
 
 
		return $s;
	}
Bookmark and Share
24 August 2011 at 18:53 - Comments

View counter application:source code

Here is the Full source code for view counter application for counting the page views .
Please use the example.txt for how to use the application.

It uses memcache. Install the memcached daemon and php library to use it.
It uses mysql 5 and php 5.

http://satishgaudo.com/satblog/ext_img/view_counter.rar

Bookmark and Share
31 May 2011 at 18:51 - Comments

Image resizer class: Resizes and saves image

<?php
	/*
     Purpose:   Resizes and saves image
     Requires : Requires PHP5, GD library.
     Usage Example:
                        include("classes/resize_class.php");
                        $resizeObj = new imageResize('images/cars/large/input.jpg');
                        $resizeObj -> resizeImage(150, 100, 0);
                        $resizeObj -> saveImage('images/cars/large/output.jpg', 100);
 
	*/
		Class imageResize
		{
			// *** Class variables
			private $image;
		    private $width;
		    private $height;
			private $imageResized;
 
			function __construct($fileName)
			{
				// *** Open up the file
				$this->image = $this->openImage($fileName);
 
			    // *** Get width and height
			    $this->width  = imagesx($this->image);
			    $this->height = imagesy($this->image);
			}
 
 
 
			private function openImage($file)
			{
				// *** Get extension
				$extension = strtolower(strrchr($file, '.'));
 
				switch($extension)
				{
					case '.jpg':
					case '.jpeg':
						$img = @imagecreatefromjpeg($file);
						break;
					case '.gif':
						$img = @imagecreatefromgif($file);
						break;
					case '.png':
						$img = @imagecreatefrompng($file);
						break;
					default:
						$img = false;
						break;
				}
				return $img;
			}
 
 
 
			public function resizeImage($newWidth, $newHeight, $option="auto")
			{
				// *** Get optimal width and height - based on $option
				$optionArray = $this->getDimensions($newWidth, $newHeight, $option);
 
				$optimalWidth  = $optionArray['optimalWidth'];
				$optimalHeight = $optionArray['optimalHeight'];
 
 
				// *** Resample - create image canvas of x, y size
				$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
				imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
 
 
				// *** if option is 'crop', then crop too
				if ($option == 'crop') {
					$this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
				}
			}
 
 
 
			private function getDimensions($newWidth, $newHeight, $option)
			{
 
			   switch ($option)
				{
					case 'exact':
						$optimalWidth = $newWidth;
						$optimalHeight= $newHeight;
						break;
					case 'portrait':
						$optimalWidth = $this->getSizeByFixedHeight($newHeight);
						$optimalHeight= $newHeight;
						break;
					case 'landscape':
						$optimalWidth = $newWidth;
						$optimalHeight= $this->getSizeByFixedWidth($newWidth);
						break;
					case 'auto':
						$optionArray = $this->getSizeByAuto($newWidth, $newHeight);
						$optimalWidth = $optionArray['optimalWidth'];
						$optimalHeight = $optionArray['optimalHeight'];
						break;
					case 'crop':
						$optionArray = $this->getOptimalCrop($newWidth, $newHeight);
						$optimalWidth = $optionArray['optimalWidth'];
						$optimalHeight = $optionArray['optimalHeight'];
						break;
				}
				return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
			}
 
 
 
			private function getSizeByFixedHeight($newHeight)
			{
				$ratio = $this->width / $this->height;
				$newWidth = $newHeight * $ratio;
				return $newWidth;
			}
 
			private function getSizeByFixedWidth($newWidth)
			{
				$ratio = $this->height / $this->width;
				$newHeight = $newWidth * $ratio;
				return $newHeight;
			}
 
			private function getSizeByAuto($newWidth, $newHeight)
			{
				if ($this->height < $this->width)
				// *** Image to be resized is wider (landscape)
				{
					$optimalWidth = $newWidth;
					$optimalHeight= $this->getSizeByFixedWidth($newWidth);
				}
				elseif ($this->height > $this->width)
				// *** Image to be resized is taller (portrait)
				{
					$optimalWidth = $this->getSizeByFixedHeight($newHeight);
					$optimalHeight= $newHeight;
				}
				else
				// *** Image to be resizerd is a square
				{
					if ($newHeight < $newWidth) {
						$optimalWidth = $newWidth;
						$optimalHeight= $this->getSizeByFixedWidth($newWidth);
					} else if ($newHeight > $newWidth) {
						$optimalWidth = $this->getSizeByFixedHeight($newHeight);
						$optimalHeight= $newHeight;
					} else {
						// *** Sqaure being resized to a square
						$optimalWidth = $newWidth;
						$optimalHeight= $newHeight;
					}
				}
				$optimalWidth = $newWidth;
				$optimalHeight= $newHeight;
 
				return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
			}
 
 
 
			private function getOptimalCrop($newWidth, $newHeight)
			{
 
				$heightRatio = $this->height / $newHeight;
				$widthRatio  = $this->width /  $newWidth;
 
				if ($heightRatio < $widthRatio) {
					$optimalRatio = $heightRatio;
				} else {
					$optimalRatio = $widthRatio;
				}
 
				$optimalHeight = $this->height / $optimalRatio;
				$optimalWidth  = $this->width  / $optimalRatio;
 
				return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
			}
 
 
 
			private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
			{
				// *** Find center - this will be used for the crop
				$cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
				$cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );
 
				$crop = $this->imageResized;
				//imagedestroy($this->imageResized);
 
				// *** Now crop from center to exact requested size
				$this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
				imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
			}
 
 
 
			public function saveImage($savePath, $imageQuality="100")
			{
				// *** Get extension
        		$extension = strrchr($savePath, '.');
       			$extension = strtolower($extension);
 
				switch($extension)
				{
					case '.jpg':
					case '.JPG':
					case '.jpeg':
						if (imagetypes() & IMG_JPG) {
							imagejpeg($this->imageResized, $savePath, $imageQuality);
						}
						break;
 
					case '.gif':
					case '.GIF':
						if (imagetypes() & IMG_GIF) {
							imagegif($this->imageResized, $savePath);
						}
						break;
 
					case '.png':
					case '.PNG':
						// *** Scale quality from 0-100 to 0-9
						$scaleQuality = round(($imageQuality/100) * 9);
 
						// *** Invert quality setting as 0 is best, not 9
						$invertScaleQuality = 9 - $scaleQuality;
 
						if (imagetypes() & IMG_PNG) {
							 imagepng($this->imageResized, $savePath, $invertScaleQuality);
						}
						break;
 
 
 
					default:
						// *** No extension - No save.
						break;
				}
 
				imagedestroy($this->imageResized);
			}
 
 
 
 
		}
?>
Bookmark and Share
31 May 2011 at 18:26 - Comments

Perl Batch convertion script for ffmpeg , to make flash video (flv) from several other videosources

#!/usr/bin/perl
use strict;
 
# Very crude batch convertion script for ffmpeg
# to make flash video (flv) from several other videosources
#
# First get the ffmpeg CVS version
# cvs -z9 -d:pserver:anonymous@mplayerhq.hu:/cvsroot/ffmpeg co ffmpeg
#
# compile it with:
# ./configure --enable-mp3lame --enable-gpl
# make
# make install
#
# next:
# make them flv files ;)

# input movie files dirname
my $input_dir = "/var/www/uploads/dummymedia/";
 
# output files dirname
# has to exist
my $output_dir = "/var/www/converted/";
 
# bit rate of audio (valid vaues are 16,32,64)
my $bitrate = 81920;
 
# sampling rate (valid values are 11025, 22050, 44100)
my $samprate = 44100;
 
# open input dir and get moviefile names
opendir( DIR, $input_dir ) || die "Can't open dir $input_dir: $!";
my @movies = grep { /\.asf|\.mov|\.mpg|\.mpeg|\.avi|\.wmv/ } readdir(DIR);
closedir DIR;
 
# get the filenames
my ( $movie, $filename, $size );
 
use File::Basename;    
 
foreach $movie (@movies) {
 
 # copy the full name
 $filename = $movie;
 
 my(undef, undef, $ftype) = fileparse($filename,qr{\..*});
 print "[$ftype]&lt;br&gt;";
 my $pos = index($ftype,'mpg');
 if($pos==1){
 # drop extensions
 $filename =~ s/\.asf|\.mpg|\.mpeg|\.avi|\.wmv//gi;
 
 # transcode the moviefile
 # -y overwrite previous file
 # -hq highquality
 # -f fileformat
 # -s size of output
 # -aspect aspectratio (duh)
 print "\ntranscoding $movie$filename\n";
 print "\nffmpeg -i $input_dir$movie -acodec libmp3lame -ar $samprate -ab $bitrate -b 524288 -f flv -s 352x288 -y $output_dir$filename.flv";
 
 system ("ffmpeg -i $input_dir$movie -acodec libmp3lame -ar $samprate -ab $bitrate -b 524288 -f flv -s 352x288 -y $output_dir$filename.flv");
 
 ## optional, just delete these if you don't want it
 # check file and make thumbnail

 # get the size of new flv file
 $size = ( stat "$output_dir$filename.flv" )[7];
 print "Size of $output_dir$filename.flv = $size\n";
 
 # now delete bad converted files
 if ( $size &lt;= 1 ) {
 
 print "\nOOPS, $filename.flv is broken\n";
 unlink "$output_dir$filename.flv";
 }
 else {
 
 # create preview JPG
 # -itsoffset sets the time where capture should take place
 # so in this example after 6 seconds in the movie
 system("ffmpeg -i $output_dir$filename.flv -an -itsoffset 00:00:06 -ss 00:00:10 -t 00:00:01 -r 1 -y $output_dir$filename%d.jpg");
 }
 
 # end of optional check file

 }
}
Bookmark and Share
4 May 2011 at 16:05 - Comments
jimmi at 18:05 on 31 May 2011
good article . thx
jeram at 18:07 on 31 May 2011
Great work man

Regular expression: code to get all the anchor tags from the html code

Regular expresion used:'#&lt;a\s*(?:href=[\'"]([^\'"]+)[\'"])?\s*(?:title=[\'"]([^\'"]+)[\'"])?.*?&gt;((?:(?!&lt;/a&gt;).)*)&lt;/a&gt;#i'
 
Example:
<code>
&lt;?</code>
 
<code>$strcontent="&lt;table&gt;&lt;tr&gt;&lt;td&gt;&lt;a href='http://satishgaudo.com' &gt;satishgaudo.com&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;a href='http://satishgaudo.com/1' &gt;satishgaudo.com/1&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;";</code>
 
<code>preg_match_all('#&lt;a\s*(?:href=[\'"]([^\'"]+)[\'"])?\s*(?:title=[\'"]([^\'"]+)[\'"])?.*?&gt;((?:(?!&lt;/a&gt;).)*)&lt;/a&gt;#i',$strcontent, $aOutput);
 
print_r($aOutput);
 
</code>
 
<code>?&gt;
</code>
Output:
<pre id="line1">Array
(
    [0] =&gt; Array
        (
            [0] =&gt; &lt;<span>a</span><span> href</span><span>='</span><a href="view-source:http://satishgaudo.com/">http://satishgaudo.com</a><span>' </span>&gt;satishgaudo.com&lt;/<span>a</span>&gt;
            [1] =&gt; &lt;<span>a</span><span> href</span><span>='</span><a href="view-source:http://satishgaudo.com/1">http://satishgaudo.com/1</a><span>' </span>&gt;satishgaudo.com/1&lt;/<span>a</span>&gt;
        )
 
    [1] =&gt; Array
        (
            [0] =&gt; http://satishgaudo.com
            [1] =&gt; http://satishgaudo.com/1
        )
 
    [2] =&gt; Array
        (
            [0] =&gt;
            [1] =&gt;
        )
 
    [3] =&gt; Array
        (
            [0] =&gt; satishgaudo.com
            [1] =&gt; satishgaudo.com/1
        )
 
)
Bookmark and Share
29 April 2011 at 16:30 - Comments
Brooks Leaming at 06:34 on 3 May 2011
I believe the author that we want to share the knowledge we gain!

Google Transliterate API

You can use Google Transliterate to transform a given written language into dozens of other languages.

Google documentation for above api: Google Transliterate

Demo url for Google Transliterate api on  satishgaudo.com:  http://satishgaudo.com/satblog/gapp/gtl.html

Bookmark and Share
6 February 2011 at 20:29 - Comments
Adalberto Hillers at 23:12 on 25 March 2011
Some genuinely nice stuff on this website , I it.
Alveo at 23:35 on 25 March 2011
Very Interesting Post! Thank You For Thi Post!

Concept Series: Seabird – A Community-driven Mobile Phone Concept

Since Mozilla Labs launched the Concept Series with an open call for participation we’ve had thousands of people join in, share ideas and develop concepts around Firefox, the Mozilla projects and the Open Web as a whole.

In response to our open call Billy May, in early 2009, produced a throw-away concept for an “Open Web Concept Phone”. Working directly off of that community feedback, Billy has since finished the exploration with his concept “Seabird”.

For Full article:  Mozilla Seabird

Bookmark and Share
29 October 2010 at 17:34 - Comments
VLC Media Player Free Download at 11:32 on 12 November 2010
i want it
david at 09:56 on 20 November 2010
Hah

Linux command to check the number connections to mysql server

///check the number of connections to database
netstat -antp | grep :3306 | wc -l

Bookmark and Share
29 October 2010 at 17:10 - Comments
kaitlin at 02:50 on 18 November 2010
sweet

PHP function to close html tags if not closed properly

/**
* closetags
* used to close html tags incase not closed properly
* @param string $html - html string
* @access public
*/
 
function closetags($html){
$arr_single_tags = array('meta','img','br','link','area');
preg_match_all('#&lt;([a-z]+)(?: .*)?(?&lt;![/|/ ])\s*&gt;#iU', $html, $result);
$openedtags = $result[1];
preg_match_all('#&lt;/([a-z]+)&gt;#iU', $html, $result);
$closedtags = $result[1];
$len_opened = count($openedtags);
if (count($closedtags) == $len_opened){
return $html;
}
$openedtags = array_reverse($openedtags);
//re arrange open tags and closed tags for count
$aOpenedtagsCnt=Array();
$aClosedtagsCnt=Array();
if(is_array($openedtags)){
foreach($openedtags as $iK =&gt;$sTag){
if(!isset($aOpenedtagsCnt[$sTag])){
$aOpenedtagsCnt[$sTag]=1;
}else{
$aOpenedtagsCnt[$sTag]++;
}
}
}
if(is_array($closedtags)){
foreach($closedtags as $iK =&gt;$sTag){
if(!isset($aClosedtagsCnt[$sTag])){
$aClosedtagsCnt[$sTag]=1;
}else{
$aClosedtagsCnt[$sTag]++;
}
}
}
for ($i=0; $i &lt; $len_opened; $i++){
if (!in_array($openedtags[$i],$arr_single_tags)){
if ($aOpenedtagsCnt[$openedtags[$i]]!=$aClosedtagsCnt[$openedtags[$i]]){
$html .= '&lt;/'.$openedtags[$i].'&gt;';
if(!isset($aClosedtagsCnt[$openedtags[$i]])){
$aClosedtagsCnt[$openedtags[$i]]=1;
}else{
$aClosedtagsCnt[$openedtags[$i]]++;
}
}
}
}
return $html;
}

Say we have input string as: <i><i>rr<b>rrr <i> dddd</i> <i> dddddd</i>  <i>ssss

Output would be :

<i><i>rr<b>rrr <i> dddd</i> <i> dddddd</i>  <i>ssss</i></i></b></i>
Bookmark and Share
24 September 2010 at 15:41 - Comments
jimmi at 18:07 on 29 September 2010
Nice function. Thanks
Private Krankenversicherung at 23:47 on 1 October 2010
the useful thoughts you provided do help our team's research for our group, thanks. - Lucas

Linux command to replace a string across multiple files

sed -i ’s/product1.php/product.php/g’ *.php

In the command above  “product1.php” is replaced with “product.php” across all files with extension “.php” within the project folder.

Bookmark and Share
26 August 2010 at 11:27 - Comments