Php – flash Actionscript 3 and php image upload
recently i am going through a project of badge-builder with action-script and flash.now i need some help for image uploading from the flash interface to the server and showing it back in the flash interface,
the back-end programing language is php and i am using action-scrip 3 and flash cs5
can anyone please give me a right direction how to achieve this job.
Best Solution
Here is the AS3 code, it’s just some quick and dirty timeline code:
var fileRef:FileReference = new FileReference(); fileRef.addEventListener( Event.SELECT, uploadFile ); fileRef.addEventListener( ProgressEvent.PROGRESS, fileUploadProgress ); fileRef.addEventListener( Event.COMPLETE, fileUploadComplete ); button.addEventListener( MouseEvent.CLICK, browseForFile ); function browseForFile( e:Event ):void < fileRef.browse(); >function uploadFile( e:Event ):void < fileRef.upload( new URLRequest( "http://localhost/php5dev/test/upload_script.php" ), "as3File", false ); >function fileUploadProgress( e:ProgressEvent ):void < trace( ( e.bytesLoaded / e.bytesTotal ) * 100 ); >function fileUploadComplete( e:Event ):void
" ); else echo( "error uploading file
" );
Hope this helps, let me know if you need me to clarify anything.
Related Solutions
Php – How to prevent SQL injection in PHP
The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create SQL statement with correctly formatted data parts, but if you don’t fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
- Using PDO (for any supported database driver):
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute([ 'name' => $name ]); foreach ($stmt as $row) < // Do something with $row >
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string' $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) < // Do something with $row >
If you’re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.
Correctly setting up the connection
Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password'); $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
In the above example the error mode isn’t strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And it gives the developer the chance to catch any error(s) which are throw n as PDOException s.
What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Although you can set the charset in the options of the constructor, it’s important to note that ‘older’ versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.
Explanation
The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute , the prepared statement is combined with the parameter values you specify.
The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn’t intend.
Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains ‘Sarah’; DELETE FROM employees the result would simply be a search for the string «‘Sarah’; DELETE FROM employees» , and you will not end up with an empty table.
Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here’s an example (using PDO):
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)'); $preparedStatement->execute([ 'column' => $unsafeValue ]);
Can prepared statements be used for dynamic queries?
While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.
For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.
// Value whitelist // $dir can only be 'DESC', otherwise it will be 'ASC' if (empty($dir) || $dir !== 'DESC')
Php – Enumerations on PHP
Depending upon use case, I would normally use something simple like the following:
abstract class DaysOfWeek < const Sunday = 0; const Monday = 1; // etc. >$today = DaysOfWeek::Sunday;
However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and a few other notes, here’s an expanded example which may better serve a much wider range of cases:
abstract class BasicEnum < private static $constCacheArray = NULL; private static function getConstants() < if (self::$constCacheArray == NULL) < self::$constCacheArray = []; >$calledClass = get_called_class(); if (!array_key_exists($calledClass, self::$constCacheArray)) < $reflect = new ReflectionClass($calledClass); self::$constCacheArray[$calledClass] = $reflect->getConstants(); > return self::$constCacheArray[$calledClass]; > public static function isValidName($name, $strict = false) < $constants = self::getConstants(); if ($strict) < return array_key_exists($name, $constants); >$keys = array_map('strtolower', array_keys($constants)); return in_array(strtolower($name), $keys); > public static function isValidValue($value, $strict = true) < $values = array_values(self::getConstants()); return in_array($value, $values, $strict); >>
By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation:
abstract class DaysOfWeek extends BasicEnum < const Sunday = 0; const Monday = 1; const Tuesday = 2; const Wednesday = 3; const Thursday = 4; const Friday = 5; const Saturday = 6; >DaysOfWeek::isValidName('Humpday'); // false DaysOfWeek::isValidName('Monday'); // true DaysOfWeek::isValidName('monday'); // true DaysOfWeek::isValidName('monday', $strict = true); // false DaysOfWeek::isValidName(0); // false DaysOfWeek::isValidValue(0); // true DaysOfWeek::isValidValue(5); // true DaysOfWeek::isValidValue(7); // false DaysOfWeek::isValidValue('Friday'); // false
As a side note, any time I use reflection at least once on a static/const class where the data won’t change (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums).
Now that most people have finally upgraded to at least 5.3, and SplEnum is available, that is certainly a viable option as well—as long as you don’t mind the traditionally unintuitive notion of having actual enum instantiations throughout your codebase. In the above example, BasicEnum and DaysOfWeek cannot be instantiated at all, nor should they be.
Related Question
PHP Funda
This site allows users/developer to Learn Basic PHP,Get Basic PHP Functions,PHP Code,Advanced PHP Code freely without any cost or 0(zero) cost.
Hey, Would you like to work at Home ?? Just click here No need to pay, just register free and activate your account and get data Entry Work at your Home.
Wednesday, October 7, 2009
Flash image upload with PHP
System.security.allowDomain("www.tshirtsetc.co.uk"); import flash.net.FileReference; // The listener object listens for FileReference events. var listener:Object = new Object(); listener.onSelect = function(selectedFile:FileReference):Void < upWin._x = 200; selectedFile.upload("./upload.php"); >; // the file is starting to upload. listener.onOpen = function(selectedFile:FileReference):Void < _root.upWin.results_txt.text = String("Uploading " + selectedFile.name + "\n"); >; listener.onHTTPError = function(file:FileReference, httpError:Number):Void < _root.upWin.results_txt.text = String("HTTPError number: "+httpError +"\nFile: "+ file.name); >listener.onIOError = function(file:FileReference):Void < _root.upWin.results_txt.text = String("IOError: "+ file.name); >listener.onSecurityError = function(file:FileReference, errorString:String):Void < _root.upWin.results_txt.text = String("SecurityError: "+SecurityError+"\nFile: "+ file.name); >listener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void < upWin.loadBar._width = Number(bytesLoaded)/Number(bytesTotal)*300; >// the file has uploaded listener.onComplete = function(selectedFile:FileReference):Void < upWin.results_txt.text = String("Upload finished.\nNow downloading " + selectedFile.name + " to player\n"); if(position_txt.text == String("Front"))< attachMovie("trans", "transHolder", -16161, ); downloadImage1(selectedFile.name); >else< if(position_txt.text == String("Back"))< attachMovie("trans2", "transHolder2", -16162, ); downloadImage2(selectedFile.name); >else< if(position_txt.text == String("LSleeve"))< attachMovie("trans3", "transHolder3", -16163, ); downloadImage3(selectedFile.name); >else< if(position_txt.text == String("RSleeve"))< attachMovie("trans4", "transHolder4", -16164, ); downloadImage4(selectedFile.name); > > > > Itotal_txt.text = Number(3.00); _root.upWin._x = 2000; >; var imageFile:FileReference = new FileReference(); imageFile.addListener(listener); imageMovie.uploadBtn.onPress = uploadImage; imageMovie.uploadBtn2.onPress = uploadImage; imageMovie2.uploadBtn3.onPress = uploadImage; imageMovie2.uploadBtn4.onPress = uploadImage; // Call the uploadImage() function, opens a file browser dialog. function uploadImage(event:Object):Void < imageFile.browse([]); > // If the image does not download, the event object's total property // will equal -1. In that case, display am error message function imageDownloaded(event:Object):Void < if(event.total == -1) < _root.upWin.results_txt.text = String("error"); >> // show uploaded image in scrollPane function downloadImage1(file:Object):Void < transHolder.umbongo.loadMovie("./uploaded/" + file); >// show uploaded image in scrollPane function downloadImage2(file:Object):Void < transHolder2.umbongo2.loadMovie("./uploaded/" + file); >// show uploaded image in scrollPane function downloadImage3(file:Object):Void < transHolder3.umbongo3.loadMovie("./uploaded/" + file); >// show uploaded image in scrollPane function downloadImage4(file:Object):Void < var randomNum:Number = Math.round(Math.random()*(10000-0))+0; transHolder4.umbongo4.loadMovie("./uploaded/" + file); >
Server Side — PHP Code