Thursday, December 25, 2008

How to attachMovie in AS3

In this example I will show you how to add a movieClip to your flash AS3 as you would in AS2 which use the attachMovie function.

e.g

var testClip:MovieClip = new clips();
addChild(testClip);

testClip.x = 200;
testClip.y = 200;


and then do this:



Get to properties of the movie clip by right clicking at the item at your library. Give the movieClip a name and click at the 'export for actionScript checkbox.

The class name will be generated automatically for you.

Your done. You may test your movie..

Take note that "var testClip:MovieClip = new clips();" the 'clips()' are actually the class name as in the properties box.

Friday, December 19, 2008

Cool PNG fix for IE6

This fix will automatically apply to all background images as well as in img tags:

SuperSleight adds a number of new and useful features that have come from the day-to-day needs of working with PNGs.

* Works with both inline and background images, replacing the need for both sleight and bgsleight
* Will automatically apply position: relative to links and form fields if they don’t already have position set. (Can be disabled.)
* Can be run on the entire document, or just a selected part where you know the PNGs are. This is better for performance.
* Detects background images set to no-repeat and sets the scaleMode to crop rather than scale.
* Can be re-applied by any other JavaScript in the page – useful if new content has been loaded by an Ajax request.


Implementation:

Getting SuperSleight running on a page is quite straightforward, you just need to link the supplied JavaScript file (or the minified version if you prefer) into your document inside conditional comments so that it is delivered to only Internet Explorer 6 or older.

<!--[if lte IE 6]>
<script type="text/javascript" src="supersleight-min.js"></script>
<![endif]-->

Download : http://24ways.org/code/supersleight-transparent-png-in-ie6/supersleight.zip

Flash as3 load xml data

This is how we load xml to flash using actionScript 3.0



//Create the loader, set dataFormat to text
//and listen when data is loaded
var loader:URLLoader = new URLLoader()
loader.dataFormat = URLLoaderDataFormat.TEXT
loader.addEventListener(Event.COMPLETE, onLoadXML)
loader.load(new URLRequest("anastasio.xml"))
function onLoadXML(ev:Event){
   
try{       
//Convert the downloaded text into an XML        
var myXML:XML = new XML(ev.target.data)      
var list:XMLList = myXML.data.title     
//walks the list and show in textfields    
for(var i=0; i<list.length(); i++){         
//trace(list[i].@name+"-"+list[i].comments+" - "+list[i].image)           
this["Title_txt"+i].text = list[i].@name          
this["Comments_txt"+i].text = list[i].comments         
var loader:Loader = new Loader()         
this["holder_mc"+i].addChild(loader)           
loader.load(new URLRequest(list[i].image))                

} catch (e:TypeError){       
//Could not convert the data, probavlu because       
//because is not formated correctly       
trace("Could not parse the XML")        
trace(e.message)    
}
}


:::::::another way:::::::

var xmlloader = new URLLoader();
xmlloader.addEventListener(Event.COMPLETE, handleComplete);
xmlloader.load(new URLRequest("test.xml"));

function handleComplete(e:Event):void {
var xDoc:XMLDocument = new XMLDocument();
xDoc.ignoreWhite = true;
var theXML:XML = XML(e.target.data);
xDoc.parseXML(theXML.toXMLString());
var value1 = new Array();
var value2 = new Array();
var value3 = new Array();
var value4 = new Array();
var value5 = new Array();

for (var v:Number = 0; v < xDoc.firstChild.childNodes.length; v++) {
value1.push(xDoc.firstChild.childNodes[v].childNodes[0].firstChild.nodeValue); value2.push(xDoc.firstChild.childNodes[v].childNodes[1].firstChild.nodeValue); value3.push(xDoc.firstChild.childNodes[v].childNodes[2].firstChild.nodeValue); value4.push(xDoc.firstChild.childNodes[v].childNodes[3].firstChild.nodeValue); value5.push(xDoc.firstChild.childNodes[v].childNodes[4].firstChild.nodeValue);
}

}

.htaccess usage

The .htaccess files (Hypertext Access file) is a very powerful configuration tool on Apache web server. The Apache web server has a number of configuration options that are available to the server administrator. The .htaccess is a simple ASCII text file placed in your website root directory. You can create and edit an .htaccess file using a text editor like notepad.


Here in this blog post I have come up with useful 16 tips and hacks to configure your web server.

As a configuration file .htaccess if a very powerful and a slight syntax error can result in a severe malfunction of your server. So to avoid that always try to keep a backup copies of all your files from the server before working with the .htaccess file.


1. Creating a custom error page with .htaccess on a linux apache is a very simple task. Using you a text editor like notepad you create an .htaccess files. Custom error pages give your website an professional look and catch those visitors who reach your website following a back link.



ErrorDocument 401 /error/401.php

ErrorDocument 403 /error/403.php

ErrorDocument 404 /error/404.php

ErrorDocument 500 /error/500.php



2. How to set the timezone on your server



SetEnv TZ America/Houston


3. Block IPs Using htaccess

Sometime you need to block certain IPs from accessing your entire site or directory. Its pretty simple task. All you have to do is inside the .htaccess file is put the following code.


allow from all

deny from 145.186.14.122

deny from 124.15


If you use the whole IP or a part of the IP to block and add the new ones in a new line.

When someone trying to access your site from the banned ip they will get a 403 error access forbidden message.


4. SEO Friendly 301 permanent redirects for bad/old links and moved links



Redirect 301 /d/file.html http://www.htaccesselite.com/r/file.html


5. Set the Email Address for the Server Administrator - Using this code you can specifying the default email address for the server administrator.



ServerSignature EMail

SetEnv SERVER_ADMIN default@domain.com



6. Hotlinking protection with .htaccess is very important because anyone can hot link to your images and eat up all your bandwith of your server. The following code will help you to prevent that.


Options +FollowSymlinks

# Protect Hotlinking

RewriteEngine On

RewriteCond %{HTTP_REFERER} !^$

RewriteCond %{HTTP_REFERER} !^http://(www\.)?domainname\.com/ [nc]

RewriteRule .*\.(gif|jpg|png)$ http://domainname.com/img/hotlink_f_o.png [nc]


7. Block all requests from user agent - by creating a perfect .htaccess ban list, you can block all of unwanted user agents that will keep your server load down. Also Check out this interesting thread on webmaster world about the  228 user agents ban list.


## .htaccess Code :: BEGIN

## Block Bad Bots by user-Agent

SetEnvIfNoCase user-Agent ^FrontPage [NC,OR]

SetEnvIfNoCase user-Agent ^Java.* [NC,OR]

SetEnvIfNoCase user-Agent ^Microsoft.URL [NC,OR]

SetEnvIfNoCase user-Agent ^MSFrontPage [NC,OR]

SetEnvIfNoCase user-Agent ^Offline.Explorer [NC,OR]

SetEnvIfNoCase user-Agent ^[Ww]eb[Bb]andit [NC,OR]

SetEnvIfNoCase user-Agent ^Zeus [NC]

<Limit GET POST HEAD>

Order Allow,Deny

Allow from all

Deny from env=bad_bot

</Limit>

## .htaccess Code :: END



8. Redirect everyone to different site except few IP
-If you want to redirect all the visitors to a different IP. Also give access to certain  few IPs. You can use the code below


ErrorDocument 403 http://www.youdomain.com

Order deny,allow

Deny from all

Allow from 124.34.48.165

Allow from 102.54.68.123


9. Don’t want to display download request - Usually when you try to download something from a web server you get a request asking whether you want to save the file or open it.

To avoid that you can use the below code on your .htaccess file.


AddType application/octet-stream .pdf

AddType application/octet-stream .zip

AddType application/octet-stream .mov


10. Change the file type - Make any file be a certain kind of file type Makes image.jpg, index.html, default.cgi all act as php


<Files test>

ForceType application/x-httpd-php

SetHandler application/x-httpd-php

</Files>


11. Block access to your .htaccess file - By adding he following code to your htaccess file will prevent attempts to access your htaccess file. This extra layer of security protects your htaccess file by displaying a 403 error message on the browser.


# secure htaccess file

<Files .htaccess>

 order allow,deny

 deny from all

</Files>



12. Protect access to certain specific file on your server - this can be done by adding the below mentioned code. For example you want to block with the file name default.jpg This will prevent the viewing of this file.


# prevent access of a certain file

<files default.jpg>

 order allow,deny

 deny from all

</files>



13. Prevent access to unauthorized browsing - Protecting specific directory browsing can be done by intructing the server to serve a Forbidden and Authorization required message while anyone requests to view that particular directory. Usually if you site doesn’t have a default index page any files within that directory is accessible to the visitors. To avoid that use the following code in the .htaccess file.


# disable directory browsing

Options All -Indexes



14. Setting the default page
- You can set the default page of a directory to any page you like. For example in this code the default page is set as about.html instead of index.html


# serve alternate default index page

DirectoryIndex about.html



15. Password protect your directories and files
- You can create authentication for certain files and directories from being access. The code has examples of both password protection for a single file and password protection for a entire directory.


# to protect a file

<Files secure.php>

AuthType Basic

AuthName “Prompt”

AuthUserFile /home/path/.htpasswd

Require valid-user

</Files>


# password-protect a directory

resides

AuthType basic

AuthName “This directory is protected”

AuthUserFile /home/path/.htpasswd

AuthGroupFile /dev/null

Require valid-user



16. Redirect an old domain to a new domain
- Using htaccess file you can redirect a old domain name to a new domain by adding the following code into the htaccess file. Basically what it does is it will remap the old domain to the new one.


# redirect from old domain to new domain

RewriteEngine On

RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]


As htaccess files are very powerful, even a slightest syntax error can cause sever malfunction of your server. So it is crucial to take the backup copies of everything before you try the hacks and tricks on your hypertext access files.

How to compress CSS files

The Reinhold Weber method


This is the best method for me do far and it's cool:


<?php
header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
/* remove comments */
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}


/* your css files */
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');


ob_end_flush();
?>

CSS Hacks

The hacks:


e.g:

*html body { <- only ie6 sees this
color: #FF0000;
}


*:first-child+html body { <- only ie7 sees this
color: #FF0000;
}


body:nth-of-type(1) body { <- only safari and chrome see this
color: #FF0000;
}


body {
_color: #FF0000; <- only ie6 sees this
}

more info: http://www.webdevout.net/css-hacks

Monday, November 17, 2008

Flash replace string function

code:

String.prototype.replace = function(searchStr, replaceStr):String {
var arr:Array = this.split(searchStr);
return arr.join(replaceStr);
};

----
to use:

string.replace("string to find","string to replace");

Sunday, November 9, 2008

PHP headers

To change php header to text/plain:

code:

header('Content-Type: text/plain');


To set php header to no-cache

code:

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // Always modified
header("Cache-Control: private, no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0

Sunday, November 2, 2008

Flash dataGrid component

Why not just use a DataGrid component? They're pretty easy to use actually.
Try this: start a new AS2 project and drag a DataGrid from the components
panel onto the stage. Use the properties panel to size it to 500 x 300. When
you add data to a grid it will just show a scroll bar if necessary, it
doesn't resize... Give it an instance name of "theGrid".

Now, add the following script to the frame:

import mx.controls.gridclasses.DataGridColumn;

function doGrid(gridRef, gArray:Array)
{
for (var i = 0; i < gArray.length; i++) {
var cat:DataGridColumn = new DataGridColumn(gArray[i][0]);
cat.width = gArray[i][2];
cat.headerText = gArray[i][1];
cat.editable = false;
gridRef.addColumn(cat);
}

}

var gFormat = new Array(["fname", "First Name:", 120], ["lname", "Last
Name:", 200], ["date", "Win Date:", 80]);
doGrid(theGrid, gFormat);

If you compile now, you'll see the grid with the field titles... I use the
doGrid function, and an array like this to make formatting the grid easy.
The first item in the array matches the dataProvider property, as you will
see in a moment - the second is the title, and the third the width of the
column... change these as you need.

To add data, you just create an array of objects, with the object properties
matching the first item in the format array - like so - add the following
and test again:

var gridData = new Array({fname:"Dave", lname:"Mennenoh", date:"09/14/08"},
{fname:"giga", lname:"saurus", date:"10/14/08"});

theGrid.dataProvider = gridData;

That's all there is to it... If you add more data than can be shown, you'll
get a scroll bar. You can add en event listener to know when someone selects
an item, etc...

Thursday, October 30, 2008

Flash - Event on selecting the text

code:

this.onMouseUp = function(){
var beginIndex:Number = Selection.getBeginIndex();
var endIndex = Selection.getEndIndex()
trace("TARGET : " + Selection.getFocus());
trace("Start Index = " + beginIndex + " :: End Index = " + endIndex)
trace("SelectedChar = " +
eval(Selection.getFocus()).text.slice(beginIndex,endIndex));
}

Thursday, October 23, 2008

PHP email validation

code:

function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") ||
checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}

Wednesday, October 8, 2008

Flash function to replace string

code:

String.prototype.replace = function(searchStr, replaceStr):String {
var arr:Array = this.split(searchStr);
return arr.join(replaceStr);
};


usage:

newString = replace("string to search", "string to replace");

Friday, September 26, 2008

Flash loadPolicyFile() - how to impliment loadPolicyFile in proper way / correct way and how to host loadPolicyFile using PHP

For those people who are searching for XMLSocket function to work properly, I will tell you step by step on how to create PHP socket server to support XMLSocket function in Flash, and also how to host your crossdomain.xml so it can be use by the Flash 9 loadPolicyFile function.

Step 1:

Since Flash 9 do not support loading the crossdomain.xml file directly by url, we must first create a socket to host the crossdomain.xml.

PHP (policySocketServer.php):

#!/usr/bin/php -q
<?php
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
function __autoload ($className)
{
$fileName = "Classes/".str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
$status = (@include_once $fileName);
if ($status === false) {
eval(sprintf('class %s {func' . 'tion __construct(){throw new Project_Exception_AutoLoad("%s");}}', $className, $className));
}
}
$ip = '127.0.0.1'; //change it to your webserver path
$port = 9996; //any port no you wish and it must be greater than 1024

//new SocketServer($ip, $port);
try{
$mySocketServer = new SocketServer($ip, $port);
} catch (Project_Exception_AutoLoad $e) {
//echo "FATAL ERROR: CAN'T FIND SOCKET SERVER CLASS.";
}
?>


Create a folder named Classes, and inside the folder create Logger.php and SocketServer.php

PHP (Logger.php):

<?php
class Logger
{
private static $instance;
public static function getInstance()
{
if(!isset($instance))
$instance = new Logger();
return $instance;
}
function __construct()
{
}

function log($message)
{
//echo "[".date('Y-m-d')."] ".$message."\n";
}
}

?>


PHP (SocketServer.php):

<?php
class SocketServer
{
var $ip;
var $port;
var $masterSocket;
var $logger;
private $currentSockets;

function __construct($ip, $port)
{
$this->ip = $ip;
$this->port = $port;
$this->logger = Logger::getInstance();
$this->initSocket();
$this->currentSockets = array();
$this->currentSockets[] = $this->masterSocket;
$this->listenToSockets();
}

private function initSocket()
{

//---- Start Socket creation for PHP 5 Socket Server -------------------------------------

if (($this->masterSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0)
{
$this->logger->log("[SocketServer] "."socket_create() failed, reason: " . socket_strerror($this->masterSocket));
}
socket_set_option($this->masterSocket, SOL_SOCKET,SO_REUSEADDR, 1);
if (($ret = socket_bind($this->masterSocket, $this->ip, $this->port)) < 0) {
$this->logger->log("[SocketServer] "."socket_bind() failed, reason: " . socket_strerror($ret));
}

if (($ret = socket_listen($this->masterSocket, 5)) < 0) {
$this->logger->log("[SocketServer] "."socket_listen() failed, reason: " . socket_strerror($ret));
}
}

private function parseRequest($socket, $data)
{
if(substr($data,0, 22) == "<policy-file-request/>")
{
//echo "POLICY FILE REQUEST\n";
$crossFile = file("http://localhost/crossdomain.xml"); //put your domain url where you uploaded the crossdomain.xml, it can also be any online webserver path
$crossFile = join('',$crossFile);
$this->sendMessage(array($socket),$crossFile);
return;
}
}

public function sendMessage($sockets, $message)
{
$message .= "\0";
if(!is_array($sockets))
$sockets = array($sockets);
foreach($sockets as $socket)
{
if($socket === NULL)
continue;
socket_write($socket, $message, strlen($message));
//$this->logger->log("[SocketServer] Wrote : ".$message." to ".$socket);
}
}

private function listenToSockets()
{
//---- Create Persistent Loop to continuously handle incoming socket messages ---------------------
while (true) {
$changed_sockets = $this->currentSockets;
$num_changed_sockets = socket_select($changed_sockets, $write = NULL, $except = NULL, NULL);
foreach($changed_sockets as $socket)
{
if ($socket == $this->masterSocket) {
if (($client = socket_accept($this->masterSocket)) < 0) {
$this->logger->log("[SocketServer] "."socket_accept() failed: reason: " . socket_strerror($socket));
continue;
} else {
// NEW CLIENT HAS CONNECTED
$this->currentSockets[] = $client;
socket_getpeername($client, $newClientAddress);
$this->logger->log("[SocketServer] "."NEW CLIENT ".$client." [IP: ".$newClientAddress."]");
}
} else {
$bytes = socket_recv($socket, $buffer, 4096, 0);
if ($bytes == 0) {
// CLIENT HAS DISCONNECTED
$this->logger->log("[SocketServer] "."REMOVING CLIENT ".$socket);
$index = array_search($socket, $this->currentSockets);
// Remove Socket from List
unset($this->currentSockets[$index]);
socket_close($socket);
}else{
// CLIENT HAS SENT DATA
$this->parseRequest($socket, $buffer);
}
}
}
}
}
}
?>


Create the crossdomain.xml file and put it in your webserver root:

XML (crossdomain.xml):

<cross-domain-policy>
<allow-access-from domain="*" to-ports="*"/>
</cross-domain-policy>


Step 2 (if you're running on local server):

Create a batch file in your desktop named runPolicyFile.bat:

Bat (runPolicyFile.bat):

c:/wamp/bin/php/php5.2.5/php.exe -q c:/wamp/www/policySocketServer.php

Click the batch file to run the script (make sure you have your webserver is up and running).

Alternative way is to run the policySocketServer.php straight away in your web browser.


Step 3:

In your flash file, include this script:

System.security.allowDomain("*");
System.security.loadPolicyFile("xmlsocket://127.0.0.1:9996"); //your webserver path and the port number you choose


You're done

You should be able to see that your XMLSocket function working now in the web browser :)

Check out the demo here . I have successfully implement PURE PHP SOCKET SERVER to build this chat application in Flash through XMLSocket function.
Any comment appreciated..

Thursday, September 25, 2008

Flash Interval / timer function

code:

interval = function() {
//do your things here
clearInterval(intervalInt);
}
var intervalInt = setInterval(interval, 1000);

*1000 refers to 1000ms = 1s

Tuesday, September 23, 2008

PHP list files in directory

code:

// open this directory
$myDirectory = opendir(".");
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// close directory
closedir($myDirectory);
// count elements in array
$indexCount = count($dirArray);
//Print ("$indexCount files<br>\n");
// sort 'em
sort($dirArray);
// print 'em
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th><th>Created</th></TR>\n");
// loop through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
$checkExt = explode(".", $dirArray[$index]);
if (substr("$dirArray[$index]", 0, 1) != "." && $checkExt[count($checkExt)-1] != "php"){ // don't list hidden and php files
print("<TR><TD><a href=\"$dirArray[$index]\">$dirArray[$index]</a></td>");
print("<td>");
print(filetype($dirArray[$index]));
print("</td>");
print("<td>");
print(filesize($dirArray[$index]));
print("</td>");
print("<td>");
print(date("F d Y H:i:s.", filectime($dirArray[$index])));
print("</td>");
print("</TR>\n");
}
}
print("</TABLE>\n");
clearstatcache();

Javascript for removing spaces in string

code:

<script type="text/javascript">
function removeSpace(obj) {
var tstring = "";
string = '' + document.getElementById(obj).value;
splitstring = string.split(" ");
for(g = 0; g < splitstring.length; g++){
tstring += splitstring[g];
document.getElementById(obj).value = tstring;
}
}
</script>

sample (put in your html code):

<script type="text/javascript">
function removeSpace(obj) {
var tstring = "";
string = '' + document.getElementById(obj).value;
splitstring = string.split(" ");
for(g = 0; g < splitstring.length; g++){
tstring += splitstring[g];
document.getElementById(obj).value = tstring;
}
}
</script>
<textarea name="tb" id="tb" cols="60" rows="10" onKeyUp="removeSpace('tb')"></textarea>
*Type anything inside the textArea

Monday, September 22, 2008

How to activate flash object without clicking in Internet Explorer (IE)

1. Create a file, flashIEfix.js and put this code in it:

objects = document.getElementsByTagName("object");
for (var i = 0; i < objects.length; i++)
{
objects[i].outerHTML = objects[i].outerHTML;
}

2. Put this script to your flash html page:
<script type="text/javascript" src="flashIEfix.js"></script>

Sunday, September 21, 2008

Flash simple alarm clock




source code: alarmClock.fla

Flash transform color

code:

colorChange = new Color(MovieClip);
myColorTransform = new Object();
// Set the values for myColorTransform
myColorTransform = { ra: _global.Rchange, rb: _global.Rchange, ga: _global.Gchange, gb: _global.Gchange, ba: _global.Bchange, bb: _global.Bchange, aa: Alpha, ab: Alpha};
colorChange.setTransform(myColorTransform);

variable: MovieClip

Flash set color

code:

var setColor = new Color(this);
setColor.setRGB(0x00ACEE);

Saturday, September 20, 2008

How to resize image using only PHP script

Here is the very small code sample that will resize images as they are uploaded from a web form. Please read the comments in detail. They explain exactly what is going on, and where you should make changes for the destination directory and output sizes.

This script only supports the JPG file format. The compression algorithm for GIF images is protected by a restrictive licensing agreement that prevents the developers of PHP from including support for GIF images in the base platform.

Part I: The HTML Form
<form action="upload.php" method="post" enctype="multipart/form-data" >
<input type="file" name="uploadfile"/>
<input type="submit"/>
</form>

Part II: Getting at the file, resizing the image, and saving to the server. (upload.php)
<?php
// This is the temporary file created by PHP
$uploadedfile = $_FILES['uploadfile']['tmp_name'];
// Create an Image from it so we can do the resize
$src = imagecreatefromjpeg($uploadedfile);
// Capture the original size of the uploaded image
list($width,$height)=getimagesize($uploadedfile);
// For our purposes, I have resized the image to be
// 600 pixels wide, and maintain the original aspect
// ratio. This prevents the image from being "stretched"
// or "squashed". If you prefer some max width other than
// 600, simply change the $newwidth variable
$newwidth=600;
$newheight=($height/$width)*600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
// this line actually does the image resizing, copying from the original
// image into the $tmp image
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
// now write the resized image to disk. I have assumed that you want the
// resized, uploaded image file to reside in the ./images subdirectory.
$filename = "images/". $_FILES['uploadfile']['name'];
imagejpeg($tmp,$filename,100);
imagedestroy($src);
imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request
// has completed.
?>

Flash movieClip drag

this.onPress = function() {
startDrag(this);
}

this.onRelease = function() {
stopDrag();
}

this.onReleaseOutside = function() {
stopDrag();
}

Flash dynamic swapDepth

code:

this.onPress = function() {
_root.x++;
this.swapDepths(_root.x);
}

Flash pixel collision detection





The CollisionDetection class is really simple to work with, there is a single static method called checkForCollision with four parameters:

checkForCollision(movieClip1,movieClip2,alphaTolerance);

movieClip1, movieClip2 - The MovieClip instances to check for collision.
alphaTolerance - a number from 0 to 255 that specifies the transparency tolerance when testing the collision. A higher number will increase the tolerance (ie. allow more transparent parts of the MovieClip to register collisions). Defaults to 255.

Returns a Rectangle object specifying the intersection of the two MovieClips in the _root coordinate space, or null if they do not intersect.


code (CollisionDetection.as):

import flash.display.BitmapData;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.geom.Rectangle;

class CollisionDetection {
static public function checkForCollision(p_clip1:MovieClip,p_clip2:MovieClip,p_alphaTolerance:Number):Rectangle {

// set up default params:
if (p_alphaTolerance == undefined) { p_alphaTolerance = 255; }

// get bounds:
var bounds1:Object = p_clip1.getBounds(_root);
var bounds2:Object = p_clip2.getBounds(_root);

// rule out anything that we know can't collide:
if (((bounds1.xMax < bounds2.xMin) || (bounds2.xMax < bounds1.xMin)) || ((bounds1.yMax < bounds2.yMin) || (bounds2.yMax < bounds1.yMin)) ) {
return null;
}

// determine test area boundaries:
var bounds:Object = {};
bounds.xMin = Math.max(bounds1.xMin,bounds2.xMin);
bounds.xMax = Math.min(bounds1.xMax,bounds2.xMax);
bounds.yMin = Math.max(bounds1.yMin,bounds2.yMin);
bounds.yMax = Math.min(bounds1.yMax,bounds2.yMax);

// set up the image to use:
var img:BitmapData = new BitmapData(bounds.xMax-bounds.xMin,bounds.yMax-bounds.yMin,false);

// draw in the first image:
var mat:Matrix = p_clip1.transform.concatenatedMatrix;
mat.tx -= bounds.xMin;
mat.ty -= bounds.yMin;
img.draw(p_clip1,mat, new ColorTransform(1,1,1,1,255,-255,-255,p_alphaTolerance));

// overlay the second image:
mat = p_clip2.transform.concatenatedMatrix;
mat.tx -= bounds.xMin;
mat.ty -= bounds.yMin;
img.draw(p_clip2,mat, new ColorTransform(1,1,1,1,255,255,255,p_alphaTolerance),"difference");

// find the intersection:
var intersection:Rectangle = img.getColorBoundsRect(0xFFFFFFFF,0xFF00FFFF);

// if there is no intersection, return null:
if (intersection.width == 0) { return null; }

// adjust the intersection to account for the bounds:
intersection.x += bounds.xMin;
intersection.y += bounds.yMin;

return intersection;
}
}

------------------------------------------------------------------------------------

code (in Flash):

import CollisionDetection;
import flash.geom.Rectangle;

createEmptyMovieClip("drawin",100);
drawin.clear();
// check for collisions:
var collisionRect:Rectangle = CollisionDetection.checkForCollision(mc1,mc2,120);

// if there is a collision, draw the intersection:
if (collisionRect) { with (drawin) {
beginFill(0x00FF00,20);
lineStyle(0,0x00FF00,40);
moveTo(collisionRect.x,collisionRect.y);
lineTo(collisionRect.x+collisionRect.width,collisionRect.y);
lineTo(collisionRect.x+collisionRect.width,collisionRect.y+collisionRect.height);
lineTo(collisionRect.x,collisionRect.y+collisionRect.height);
lineTo(collisionRect.x,collisionRect.y);
}}

if (collisionRect) {
//do your stuff
}

------------------------------------------------------------------------------------

Click here to download. It includes two simple demos to help you get started with it.

Flash local connection

code (outgoing msg):

var outgoing_lc:LocalConnection = new LocalConnection();
outgoing_lc.send("sessionName", "methodToExecute", "messageToSend");

code (incoming msg listen):

var incoming_lc:LocalConnection = new LocalConnection();
incoming_lc.connect("sessionName");
incoming_lc.methodToExecute = function(param:String):Void {
if (param == "messageToSend") {
//do your things
}
}

Friday, September 19, 2008

Flash load XML from php

code (in flash):

//set array
var company_name:Array = new Array();
var client_id:Array = new Array();

var ClientXML:XML = new XML();
ClientXML.ignoreWhite = true;
var height = 0;
ClientXML.onLoad = function() {
var nodes = this.firstChild.childNodes;
for (i=0;i<nodes.length;i++) {
movname="MovieClip_" + i;
company_name.push(nodes[i].firstChild.nodeValue);
client_id.push(nodes[i].attributes.id);
attachMovie("MovieClip_", movName, i);
eval("MovieClip_" + movName).company_name_tb.text = company_name[i];
eval("MovieClip_" + movName).clientID_tb.text = client_id[i];
eval("MovieClip_" + movName)._y = height;
height += eval("MovieClip_" + movName)._height;
}
}
ClientXML.load("clientflash.php");

-------------------------------------------------------------------------------------

code (clientflash.php - assuming you have the database connection, $client_listRS):

<?php
echo "<?xml version=\"1.0\"?>\n";
echo "<client>\n";
do {
echo "<company id="&quot; . $row_client_listRS[" client_id=""><![CDATA[" . $row_client_listRS['company_name'] . "]]></company>\n";
} while ($row_client_listRS = mysql_fetch_assoc($client_listRS));
echo "</client>\n";
?>

Flash create line art using actionScript


code:

//top line---------------------------------------------------------------
h=0;
while (h<15) {
colors = [0x381EA6, 0x381EA6];
alphas = [30, 20];
ratios = [0, 0xFF];
matrix = {a:500, b:0, c:0, d:0, e:200, f:0, g:200, h:200, i:1};
spreadMethod = "reflect";
interpolationMethod = "linearRGB";
focalPointRatio = 0.5;
lineStyle(1);
lineGradientStyle("linear", colors, alphas, ratios, matrix,
spreadMethod, interpolationMethod, focalPointRatio);
moveTo(0, 0 + (h * 50));
curveTo(500 + (h * 5), 100 + (h * 5), 200 + (h * 5), 0 + (h * 5));
curveTo(-400 + (h * 5), -170 + (h * 5), 1800 + (h * 100), 500 + (h * 100));
h++;
}

//bottom line------------------------------------------------------------
g=0;
while (g<15) {
colors = [0x381EA6, 0x381EA6];
alphas = [30, 20];
ratios = [0, 0xFF];
matrix = {a:500, b:0, c:0, d:0, e:200, f:0, g:200, h:200, i:1};
spreadMethod = "reflect";
interpolationMethod = "linearRGB";
focalPointRatio = 0.5;
lineStyle(1);
lineGradientStyle("linear", colors, alphas, ratios, matrix,
spreadMethod, interpolationMethod, focalPointRatio);
moveTo(0, 0 + (g * 50));
curveTo(500 + (g * 5), 100 + (g * 5), 200 + (g * 5), 0 + (g * 5));
curveTo(-400 + (g * 5), -170 + (g * 5), 1800 + (g * 100), 500 + (g * 100));
g++;
}

Flash glow effect

import flash.filters.*;

var glow:GlowFilter = new GlowFilter(0x00CCFF, 0.5, 2, 2, 4, 3);
MovieClip.filters = [glow];

Flash stage auto resize

code:

function init() {
MovieClip._width = Stage.width;
MovieClip._height = Stage.height;
}
init();

var stageListener:Object = new Object();

stageListener.onResize = function() {
init();
}

Stage.addListener(stageListener);

Flash fade effect

code:

import mx.transitions.Tween;
import mx.transitions.easing.*;

new Tween(MovieClip, "_alpha", Strong.easeOut, 0, 100, 2, true);

note:

variable is MovieClip

Flash movieClip randomizer

code:

function randomNo(high,low) {
generated = Math.floor(Math.random() * (high - low)) + low;
return generated;
}

_global.MovieClip_loader = function(MovieClip, url) {
var theLoader:MovieClipLoader = new MovieClipLoader();
theLoader.loadClip(Url, MovieClip);
var loaderListener:Object = new Object();
theLoader.addListener(loaderListener);
MovieClip.loader_txt.text = "0%";

loaderListener.onLoadProgress = function(_mc:MovieClip, loaded:Number, total:Number) {
MovieClip.loader_txt.text = Math.round((loaded/total) * 100) + "%";
}

loaderListener.onLoadComplete = function(_mc:MovieClip) {
MovieClip.loader_txt.text = "";
}
}

_global.MovieClip_randomizer = function(noOfClip) {
if (MovieClip_1.occupied == "") {
for (p=1;p<=noOfClip;p++) {
randomGenerated = randomNo(1,noOfClip);
if (p != 1 && p != noOfClip) {
while(eval("MovieClip_" + randomGenerated).occupied <> "") {
randomGenerated = randomNo(1,noOfClip);
}
}
if (p == noOfClip) {
for (r=1;r<=noOfClip;r++) {
if (eval("MovieClip_" + r).occupied == "") {
randomGenerated = r;
}
}
}
_global.MovieClip_loader("MovieClip_" + randomGenerated, swfName + p + ".swf");
}
}
}

note:
to use, e.g. _global.MovieClip_randomizer(3);
*if you have 3 mc: MovieClip_1, MovieClip_2, MovieClip_3
*the last clip will always be the last ;)

varibles are MovieClip, swfName, noOfClip
assuming that your movieClip names start from "MovieClip_"

Flash movieClip Loader

code:

var theLoader:MovieClipLoader = new MovieClipLoader();
theLoader.loadClip(Url, MovieClip);
var loaderListener:Object = new Object();
theLoader.addListener(loaderListener);
MovieClip.loader_txt.text = "0%";

loaderListener.onLoadProgress = function(_mc:MovieClip, loaded:Number, total:Number) {
MovieClip.loader_txt.text = Math.round((loaded/total) * 100) + "%";
}

loaderListener.onLoadComplete = function(_mc:MovieClip) {
MovieClip.loader_txt.text = "";
}

note:
variables are MovieClip and Url

Flash move dynamically


_global.moveXY = function(targetx,targety,speed) {
goAnimate = function() {
this._x += (targetx - this._x)/speed;
this._y += (targety - this._y)/speed;

if((Math.abs(this._x - targetx) < 0.5) && (Math.abs(this._y - targety) < 0.5)) {
delete this.onEnterFrame;
}
}
this.onEnterFrame = goAnimate;
}


to use the script,
_global.moveXY.call(movieClip name, x, y, speed);

Flash random number function

function randomNo(high,low) {
generated = Math.floor(Math.random() * (high - low)) + low;
return generated;
}

note:
high = the highest number to random
low = the lowest number to random