I am working on a project involving a PHP connection, the UI is developed using flash builder, I have Combo Box and Text Input for users to pick some items and at the same time users can input their details on the Text Input. The app is not generating anything up till now. I need to send data to PHP for PHP to look up into its folder containing some images. I used folder instead of database, the output should be sent back to Flex for it to be saved into another folder and I also want a copy to be saved inside another folder in PHP. Please is there anyone that could be of help?
These are some of the codes used:
public function Drop2_disabled(event:Event):void{
love=="orange"&&"pawpaw"&&"maize"; hate=="rice"&&"maize"&&"starch";
if((Drop2.selectedItem=="orange"||"pawpaw"||"maize")&&
(Drop3.selectedItem=="rice"||"maize"||"starch"))
ValueCommit="{foodVO.love}"
}
was now used under the ComboBox to bind foodVO to variable love, this was repeated for the text Input also. My foodVO is an action script file. foodVO was then mapped to my foodVO.Php using Zend server.
The PHP will then use the data sent from the remote object to look up into his own folder to read the images and then send it back to flex.
(services-config.xml)
These are some of the PHP script
<?php
class foodVO
{
public $maize;
public $rice;
public $pawpaw;
public $starch;
public $orange;
public function _construct()
{
$maize = $_GET["maize"];
$rice = $_GET["rice"];
$orange = $_GET["orange"];
$pawpaw = $_GET["pawpaw"];
$this->maize = "";
$this->orange = "";
$this->pawpaw = "";
$this->starch = "";
}
}
?><?php
include 'Zend/Amf/Server.php';
include './food.php/services/foodService.php';
// Initialize AMF Server
$server = new Zend_Amf_Server();
$server->setClass("foodService");
$server->setProduction($amf->production);
$server->setClassMap('foodVO', 'foodVO');
// Handle request
echo $server->handle();
?>
The foodservice.php contains my Imagick operations.
Please I need help?
Thanks.
I don't know how you achieved the connection but in order to send data back and forward between PHP and Flex there is the ActionScript Message Format extension. There are also libraries that you can use such as AmfPHP. Zend also has classes for this - Zend Amf.
Related
Am creating a REST api with laravel that allows a user to select an image file from their android device, then upload it to the server. The mage is converted to base64 before it's sent to the server alongside other parameters. I want to convert this base64 to a file and store it on the server then generate a link that can be used to access it. here is what i have tried so far and it doesnt work: I have already created a symlink to storage
public function create(Request $request)
{
$location = new Location();
$location->name = $request->location_name;
$location->latitude = $request->latitude;
$location->longitude = $request->longitude;
$location->saveOrFail();
$provider = new Provider();
$provider->name = $request->provider_name;
$provider->location_id = $location->id;
$provider->category_id = $request->category_id;
$provider->description = $request->description;
$provider->image = request()->file(base64_decode($request->encoded_image))->store('public/uploads');
$provider->saveOrFail();
return json_encode(array('status'=>'success', 'message'=>'Provider created successfully'));
}
As already commented by Amando, you can use the Intervention/Image package, having used it for many years I can say it will do what you want and very well.
What I would also add though, is you may also want to consider, whether you indeed need to store it as a file at all.
Depending on what it will be used for, and the size etc, you could consider storing it in the DB itself, along with any other information. This removes the dependency on a file server, and will make your application much more flexible with regards to infrastructure requirements.
At the end of the day, files are just data, if you will always get the file when you get the other data, reduce the steps and keep related data together.
Either way, hope you get it sorted :)
I am working on a web project that involves connecting to SharePoint Online via PHP and accessing the files stored on it. But I am extremely new to all this, and have hit a wall.
I have the URL of the file I'm trying to access
Using the phpSPO library, I am authenticated and connected to SharePoint.
The question is: how do I actually access the URL? If I follow the link directly, it redirects me to the login page for SharePoint. But we want the login to happen "behind the scenes" - and apparently the authentication step doesn't quite do that.
The company we are working with told us that we would need to request an anonymous link for the URL by calling a function. Problem is, the function they told us to use works in ASPX, but doesn't appear to be available in PHP.
This is the code they pointed us to:
Uri siteUri = new Uri(siteUrl);
Web web = context.Web;
SecureString passWord = new Secure String();
foreach (char c in "password".ToCharArray())
passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("userid", passWord);
WebDocs.Parameter1 = "123456"
WebDocs.Parameter2 = "Test"
context.Web.CreateAnonymousLinkForDocument(WebDocs.Parameter1, WebDocs.Parameter2, ExternalSharingDocumentOption.View);
But how can I translate that into PHP? Can I even do that?
And if not, is there another way that I can access the file to display it to my user?
// this says the function CreateAnonymousLinkForDocument doesn't exist
function getLink(ClientContext $ctx) {
$anonymousLink = $ctx->getWeb()->CreateAnonymousLinkForDocument();
$ctx->load($anonymousLink);
$ctx->executeQuery();
}
Well, after hours and hours of searching the Internet....
The answer was right in front of my nose.
Started browsing through the examples/SharePoint/file_examples.php that came with the phpSPO library, and discovered 2 functions (either one works).
One is called downloadFile, and the other is downloadFileAsStream.
function downloadFile(ClientRuntimeContext $ctx, $fileUrl, $targetFilePath){
$fileContent =
Office365\PHP\Client\SharePoint\File::openBinary($ctx,$fileUrl);
file_put_contents($targetFilePath, $fileContent);
print "File {$fileUrl} has been downloaded successfully\r\n";
}
function downloadFileAsStream(ClientRuntimeContext $ctx, $fileUrl,
$targetFilePath) {
$fileUrl = rawurlencode($fileUrl);
$fp = fopen($targetFilePath, 'w+');
$url = $ctx->getServiceRootUrl() . "web/getfilebyserverrelativeurl('$fileUrl')/\$value";
$options = new \Office365\PHP\Client\Runtime\Utilities\RequestOptions($url);
$options->StreamHandle = $fp;
$ctx->executeQueryDirect($options);
fclose($fp);
print "File {$fileUrl} has been downloaded successfully\r\n";
}
Since I was trying to download a PDF, I just set these functions to create a PDF on our own server.... and it works beautifully!!!!!
I've got a Flash app that calls an online php file in order to read some values of my SQL table.
So I've got a line like this in my AS3 code:
var urlReq:URLRequest = new URLRequest ("http://www.****.com/sql_result.php");
And this in my php :
$connection = mysql_connect("mysql***.perso", "test", "password") or die ("Couldn't connect to the server.");
Problem : if the user is offline he can't access the values.
Is there way to download the SQL table with AS3 code (when the user have internet) in order to access it offline.
Like :
function onConnection(e:Event = null):void{
if(monitor.available)
{
trace("You are connected to the internet");
read_php_online();
}
else
{
trace("You are not connected to the internet");
read_php_offline();
}
monitor.stop();
}
function read_php_offline():void{
var urlReq:URLRequest = new URLRequest ("local/sql_result_offline.php");
..
..
}
And what should have sql_result_offline.php in order to access an offline SQL Table ?
$connection = mysql_connect("LOCAL", "user", "password");
Thank you,
For FLASH :
To save data locally with flash, you can use one of 3 manners : the Flash Player cache, a SharedObject, or a FileReference object. And for your local file, forget PHP and MySQL because we are speaking only about the data that you got ( json, xml, txt, ... ).
- Flash Player cache :
You should know that by default, flash player put a local copy of your file in its cache. You can use this local copy as an offline source of your data, but here don't forget that flash player didn't save the last version of your remote file but the first one and that http://www.example.com/data.php is different from http://www.example.com/data.php?123 even if it's the same file ! For more details about that, take a look on my answer of this question.
- SharedObject :
I don't know the size of your loaded data, but as Adobe said about SharedObject :
... is used to read and store limited amounts of data on a user's computer ...
I think that is not used for large files and it's not recommended to store files but some simple data. Of course, as a cookie for the browser, SharedOject needs user's authorization to write data to the hard drive, and user can delete it at any time.
- FileReference :
I think this is the best manner to do what you are looking for. You should know that to save a file using FileReference, your user is invited to select a file for saving data and reading it in a second time. So if you don't want any user's interaction with your application, forget this manner.
FileReference using example :
var local_file_name:String = 'local.data',
file:FileReference = new FileReference(),
local_file_filter:FileFilter = new FileFilter('local data file', '*.data'),
remote_data_url:String = 'http://www.example.com/data.php',
url_request:URLRequest,
url_loader:URLLoader,
connected:Boolean = true;
if(connected){
get_remote_data();
} else {
get_local_data();
}
function get_remote_data(): void {
//we use a param to be sure that we have always the last version of our file
url_request = new URLRequest(remote_data_url + ('?' + new Date().getTime()));
url_loader = new URLLoader();
url_loader.addEventListener(Event.COMPLETE, on_data_loaded);
url_loader.load(url_request);
}
function get_local_data(): void {
// show the select dialog to the user to select the local data file
file.browse([local_file_filter]);
file.addEventListener(Event.SELECT, on_file_selected);
}
function on_data_loaded(e:Event): void {
var data:String = e.target.data;
// if the remote data is successfully loaded, save it on a local file
if(connected){
// show the save dialog and save data to a local file
file.save(data, local_file_name);
}
// use your loaded data
trace(data);
}
function on_file_selected(e:Event): void {
file.addEventListener(Event.COMPLETE, on_data_loaded);
file.load();
}
This code will show every time a save dialog to the user, of course, it's just a sample, you have to adapt it to your needs ...
EDIT
For AIR :
With AIR we don't need a FileReference object, instead we use File and a FileStream object to save data :
// for example, our local file will be saved in the same dir of our AIR app
var file:File = new File( File.applicationDirectory.resolvePath('local.data').nativePath ),
remote_data_url:String = 'http://www.example.com/data.php',
data_url:String = remote_data_url,
url_request:URLRequest,
url_loader:URLLoader,
connected:Boolean = true;
if(!connected){
// if we are not connected, we use the path of the local file
data_url = file.nativePath;
}
load_data();
function load_data(): void {
url_request = new URLRequest(data_url);
url_loader = new URLLoader();
url_loader.addEventListener(Event.COMPLETE, on_data_loaded);
url_loader.load(url_request);
}
function on_data_loaded(e:Event): void {
var data:String = e.target.data;
if(connected){
// save data to the local file
var file_stream:FileStream = new FileStream();
file_stream.open(file, FileMode.WRITE);
file_stream.writeUTFBytes(data);
file_stream.close();
}
trace(data);
}
Hope that can help.
you have a flash swf, mobile app or air app?
Storing local data
you can use file as database (like csv), for mobile and air you can use local SQLite database.
if you have native desktop app - it is possible to use mysql, via native process or native extension but it is not so easy..
edit:
Working with local SQL databases in AIR [+] you can keep your data safe- with encryption, a password at startup and etc. [-] it will require a lot more of code (create database after install, sync regularly, get data from local database if no internet conn.) mysql and sqlite have some differences also (like "insert or update" statement for sqlite)
I am currently doing a tutorial which was found on TutsPlus.
This tutorial was to save information from AS3 to MySQL via PHP and then retrieve this information.
So far, it works. I Can enter a username and score, which saves to the database. There is one problem though, I would like to be able to display ALL the names and scores in a table, instead of having to search for a name and then finding the score for that specific user.
The code in which the information is saved (which works), is below.
package {
import flash.display.*;
import flash.events.*;
import flash.net.*;
public class register extends MovieClip {
public function register ():void {
register_button.buttonMode = true;
register_button.addEventListener(MouseEvent.MOUSE_DOWN, checkForm);
username_text.text = "";
userbio_text.text = "";
}
public function checkForm (e:MouseEvent):void {
if (username_text.text != "" && userbio_text.text != "") {
sendForm();
} else {
result_text.text = "PLEASE ENTER A NAME";
}
}
public function sendForm ():void {
/*
we use the URLVariables class to store our php variables
*/
var phpVars:URLVariables = new URLVariables();
phpVars.username = username_text.text;
phpVars.userbio = userbio_text.text;
/*
we use the URLRequest method to get the address of our php file and attach the php vars.
*/
var urlRequest:URLRequest = new URLRequest("localhost/php/register.php");
/*
the POST method is used here so we can use php's $_POST function in order to recieve our php variables.
*/
urlRequest.method = URLRequestMethod.POST;
/*
this attaches our php variables to the url request
*/
urlRequest.data = phpVars;
/*
we use the URLLoader class to send the request URLVariables to the php file
*/
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
/*
runs the function once the php file has spoken to flash
*/
urlLoader.addEventListener(Event.COMPLETE, showResult);
/*
we send the request to the php file
*/
urlLoader.load(urlRequest);
}
/*
function to show result
*/
public function showResult (e:Event):void {
result_text.text = "" + e.target.data.result_message;
}
}
}
From here, I can go to another application and search the users name, and then displays that users score. Code below:
package actions {
import flash.display.MovieClip;
import flash.events.*;
import flash.net.*;
import flash.text.*;
public class main extends MovieClip {
public function main ():void {
submit_button.buttonMode = true;
submit_button.addEventListener(MouseEvent.MOUSE_DOWN, checkLogin);
username.text = "";
}
public function checkLogin (e:MouseEvent):void {
if (username.text == "") {
username.text = "Enter your username";
}
else {
processLogin();
}
}
public function processLogin ():void {
var phpVars:URLVariables = new URLVariables();
var phpFileRequest:URLRequest = new URLRequest("http://xx.xx.xx.uk/~bf93fv/Source%202/php/controlpanel.php");
phpFileRequest.method = URLRequestMethod.POST;
phpFileRequest.data = phpVars;
var phpLoader:URLLoader = new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
phpLoader.addEventListener(Event.COMPLETE, showResult);
phpVars.systemCall = "checkLogin";
phpVars.username = username.text;
phpLoader.load(phpFileRequest);
}
public function showResult (event:Event):void {
result_text.autoSize = TextFieldAutoSize.LEFT;
result_text.text = "" + event.target.data.systemResult;
}
}
}
The controlpanel.php file, which displays the username and score individually is below:
<?php
include_once "connect.php";
$username = $_POST['username'];
if ($_POST['systemCall'] == "checkLogin") {
$sql = "SELECT * FROM users WHERE username='$username'";
$query = mysql_query($sql);
$login_counter = mysql_num_rows($query);
if ($login_counter > 0) {
while ($data = mysql_fetch_array($query)) {
$userbio = $data["user_bio"];
print "systemResult=$username Scored $userbio";
}
}
else {
print "systemResult=The login details dont match our records.";
}
}
?>
Does anybody know any easy way in order to view ALL the information from the database into a table?
There are few things you might want to improve in your PHP code (your AS3 is better).
Use PDO instead of the functions that work with particular DBMS. The reason to this is that it is portable (to an extend). Say, if you wanted to ever move the database from MySQL to Postgres, you'd had to rewrite less of your code, then you would have to otherwise. PDO also provides some means of sanitizing the input. It's not bullet proof - still better then nothing. PDO is considered the "good practice", so you would learn to write the good code right away instead of making that journey from writing newby-style code at first and then discovering how to actually do it properly. It might be just a little bit more verbose if you are thinking about a very primitive task such as a single select, but as soon as your task becomes just a little bit more complex it becomes all worth the time.
In your SQL queries make a general rule never to use select *, unless for testing / debugging. That's sort of laziness that in the end will cost you a lot of problems. By doing so you will make it very difficult to maintain your code later, effectively transforming it into "write once - run away" kind of thing. Again, as a simple proof of concept it is OK, - long-term solution - bad. If you are still blur on what I'm trying to say: list all column names explicitly.
Using include / require and their _once family is a bad idea as a long-term solution. Again, OK for a simple test - bad in the long run. Good programs are written in functions / classes and use __autoload() or a framework that uses the ability to load classes automatically. This makes larger applications more manageable, easier to navigate and understand then the web of includes.
You must sanitize input from the user of your web application, that is don't do $_POST['key']. At least write the function that will both check that the key exists and that it is of an expected format.
Now, your actual problem, sending the data.
You can just send the raw SQL output you get in PHP - will spare your server the problem of re-encoding all of it. Works in the very simple cases, but it becomes more complex with more complex tasks. This is also uncommon to do, so you will find that people will not know how to handle that. (No technical restriction, it is just really a historical artefact).
There are a bunch of popular formats that can be digested by variety of applications, not necessary Flash. Those include XML, JSON, Protobuf. There are also some more particular to PHP like the one produced from serialize(). I'd urge you to stick to JSON if you go down this route. XML might be a more mature technology, but JSON has a benefit of the basic type system built in (while in XML it is yet another layer on top of it, which is, beside other things is not implemented in Flash - I'm talking about XSL).
There's AMF (ActionScript Message Format) - it is ideal for Flash. PHP also knows very well how to produce it (there are several popular implementations out there). This format is a lot more compact compared to JSON or XML. It has more expressive power (can describe circular dependencies, many-to-many relationships, has a procedure for introducing custom types, custom [de]serialization routines). It is also self-describing, unless you used custom serialization routine. This is the best option if you aren't planning on moving your application to JavaScript later, because JavaScript has problems consuming binary data. Parsing this format would not be possible there.
Protobuf is a viable option too. This is a data exchange format designed by Google. It is similar in spirit to AMF, however it may not be self-describing. It relies on the application to know how to produced custom objects from it. It has, however, a form, that can be parsed in JavaScript (although you'd lose the the compactness benefit).
Your ActionScript code: If you opt for AMF, you'd need to look into NetConnection class. I'd advise you to take a look in AMFPHP project - it also has examples. Alternatively, Zend Framework has Zend_Amf library to be used for that purpose. But using the entire framework may be overwhelming at start.
If you go with XML - then there's a built-in XML class, there are millions of examples on the web on how to use it.
If you go with JSON, then since not so long ago there's a built-in class for that too. But before there was one, there were several libraries to parse it.
There used to be a project on GoogleCode for Protobuf support in Flash, but it required quite a bit of acquittance and manual labour to get going.
Finally, index of things mentioned here:
http://php.net/manual/en/book.pdo.php - PDO
http://php.net/manual/en/function.json-encode.php - JSON in PHP
http://php.net/manual/en/book.dom.php - XML in PHP (There is no agreement on which XML library is better if PHP is considered. I'd probably stick to this, but ymmv).
http://www.silexlabs.org/amfphp/ - AMF in PHP
http://framework.zend.com/manual/1.12/en/zend.amf.html Zend_Amf library
http://code.google.com/p/protobuf-actionscript3/ Protobuf in ActionScript
https://github.com/drslump/Protobuf-PHP PHP Protobuf (sorry, never used this one, but looks fine)
http://www.blooddy.by/en/crypto/ for older versions of Flash player - this library has the best JSON decoder I know of.
The best way is (I think) to use XML.
On the PHP side, the script output an XML document with all the users :
$sql = "SELECT * FROM users "; // add order statement if needed
$query = mysql_query($sql);
$login_counter = mysql_num_rows($query);
$xml = array('<?xml version="1.0" encoding="UTF-8"?><users>');
if ($login_counter > 0) {
while ($data = mysql_fetch_array($query)) {
$xml[] = '<user name="'.$data['username'].'" bio="'.$data["user_bio"].'" />';
}
}
else {
// do nothing
// you will handle it on the flash side by checking the length of user nodes list
}
$xml[] = '</users>';
header('Content-Type:text/xml');
die(implode('', $xml));
This will output an XML document :
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user name="..." bio="..." />
<user name="..." bio="..." />
[...]
</users>
(There are class on PHP like SimpleXML to deal with XML in a cleaner way)
AS Side :
You can easily browse / display the data on the flash side with the help of the XML / XMLList class
Just adapt the URLLoaderDataFormat to TEXT and convert the data to XML in the complete event handler :
var xml:XML = new XML(event.target.data);
Then iterate the user elements to display them :
var users:XMLList = xml.user;
var user:XML;
for (user in users) {
trace('name->' + user.attribute('name') );
trace('bio->' + user.attribute('bio') );
}
I am Using Flex 3 and apache with PHP 5.2.
I am searching for simple as possible way to fill my mx:List with data using POST URLRequest.
In Flex builder I am using the next code
public var variables_se:URLVariables = new URLVariables();
public var varSend_se:URLRequest = new URLRequest("DataProvider.php");
public var varLoader_se:URLLoader = new URLLoader;
public function starter():void
{
varSend_se.method = URLRequestMethod.POST;
varSend_se.data = variables_se;
varLoader_se.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader_se.addEventListener(Event.COMPLETE, completeHandler_se);
variables_se.CountOflistItemsIWant = 30;
varLoader_se.load(varSend_se);
}
public function completeHandler_se(event:Event):void
{
textFild.text += " " + String(event.target.data) + ";"; // any result will apear in some textFild
// How to make result appear as list lines, how to form PHP answer and AS3 code for it?
}
How to make result appear as list lines, how to form PHP answer and AS3 code for it (If for example I want to return random numbers from PHP in desired in CountOflistItemsIWant cuatety)?
Maybe you could make your php script echo json encoded array like so:
<?php
echo json_encode(array('first', 'second', 'foo', 'bar'));
and in flex get it, decode it and use it as argument for array data provider for your mx:List
You can find information about communicating between php and flex with use of json here: http://www.adobe.com/devnet/flex/articles/flex_php_json.html
IMHO this is a larger architectural question. Here are the options:
Create a RESTful web service and have it output data in some text format (XML or JSON). You can use the HttpService objects in Flex to make request to your PHP restful web service and set result and fault handlers accordingly. Here's the quick start: http://www.adobe.com/devnet/flex/quickstart/httpservice/
If you need to remote objects directly between Flex and PHP, AMFPHP can be used: http://www.amfphp.org/
You can create a SOAP web service in PHP, some references...
http://developer.apple.com/internet/webservices/soapphp.html
http://php.net/manual/en/book.soap.php
... and use the Flex WebService object to make calls:
http://livedocs.adobe.com/flex/3/html/data_access_3.html