How to connect these 3 programming languages? - php

How to pass information in this flow:
Flash(AS3) -> PHP, using XML -> Database(mysql)
Can anyone write a simple code for that?
Thanks.

http://www.kirupa.com/developer/actionscript/flashphpxml_integration.htm
This will tell you most of what you need to know to get started.

If you're not already tied to using XML, you might want to look into using AMF. There's a number of OSS implementations of AMF for PHP, from the obviously named amfphp to an implementation in the Zend Framework. Hopefully somebody with experience here will come along and provide a better answer.

What about WebService SOAP/WSDL?
So you can provide web service on php and send information from Flex/AS3/Flash by calling some webservice method and then store it into mysql db.
Flex has class WebService, so on client side to call server method is as easy as:
var webService:WebService = new WebService();
webService.wsdl = "http://yoursite.com/webservice.wsdl";
webService.loadWSDL();
webService.this_is_method_from_php_server(your_object_serialized_as_xml);
On PHP side I'm sure there are dozen libraries to provide SOAP/WSDL.

I would recommend using amfPHP to get information from a MySQL database passed to Flash through php. It is simpler, faster and easier to use than using php to output the database result in xml. Basically what you do with amfPHP is that you can call php functions directly from flash using the LocalConnection class.
I'll simplify some code to illustrate how it works:
//PHP code
//Here's you main php class which all the sql commands will be called
class Main{
public function saveUser($username, $password){
//I'll send in the username and password to insert it into the users column
$this->db->query("INSERT INTO users VALUES ($username, $password)");
//I'm using the MDB2 library for sql queries,
//you write less code when doing queries.
}
}
//Actionscript 3 code
//To pass parameters to my php function I have to make an array.
var amfParameters:Array = [];
amfParameters['username'] = "richard";
amfParameters['password'] = "123123";
//Then create a localconnection which will connect to amfphp.
var localConnection:LocalConnection = new LocalConnection();
localConnection.connect(gatewayURL); //gatewayURL is the url to the gateway amfphp file
localConnection.call("testproject.Main.saveUser", loaderResponder, amfParameters);
//testproject.Main.saveUser is the path for our Main.php file and saveUser is the function
//loaderResponder is a Responder class which handles the callback from amfphp.
So basically you will call the php function in flash, and you can also return data to flash aswell.
This is just to illustrate a little bit of how amfphp works. It's not meant to be a complete code sample. Just to give a brief idea.
Think about it and if you think it looks interesting go and download amfphp and try it out! You won't be dissappointed.

Related

PHP - how to find the meta information of an internal/built-in method programmatically?

Is it possible to find the data about a built in method in PHP via code?
For example, we have array_key_exists() which is an internal method.
I want to find out the parameters in this function programatically. The reason is, there is an up coming interview, and I will have to write code on Notepad. There will not be any internet connection to see PHP documentation.
If I can get the information about built in methods via code, it will be really helpful.
Is it at all possible to print meta data of a function? I am not asking about user defined functions, but about PHP's built in functions.
Thanks a lot.
You are looking for Reflection i think:
$refFunc = new ReflectionFunction('preg_replace');
foreach( $refFunc->getParameters() as $param ){
print $param;
}
http://php.net/manual/de/class.reflectionfunction.php

Posting Data to REST API using JSON and PHP

I've been looking around at similar topics on REST APIs but I am still having some confusion in my project, mostly with the PHP side of things.
USPS provides a REST API with functions that can be called via URL like this: https://epfws.usps.gov/ws/resources/epf/login
To make any call successfully, I have been told that a JSON object must be created and passed as a "POST parameter" with the expected values.
This is the JSON object that needs to be passed in this case:
obj=
{
"login":"loginExample",
"pword":"passwordExample"
}
I have also been given a PHP class that is supposed to manage these calls. This is the login function:
public function login ()
{
// Set up the parameters for a login attempt
$jsonData = array(
'login' => $this->loginUser,
'pword' => $this->loginPass,
);
// Make a login request
$jsonResponse = $this->pullResource
('/epf/login', 'POST', $jsonData);
return $jsonResponse;
}
So I have a few questions regarding this:
The document they sent says
"To make the request calls, a JSON object will need to be created and passed as a POST form parameter obj={jsonObject} for security reasons using content-type “application/x-www-form-urlencoded”."
I know that the login function contains the correct input values that USPS' REST API is wanting, but I'm not sure how to pass them as "obj", or how to apply the "content-type".
I have a "constant" defined at the top of my PHP script that looks like this:
const EPF_BASE_URL = 'https://epfws.usps.gov/ws/resources';
And I noticed in the actual functions that this part of the link is left out and they simply reference '/epf/login' as you can see above. Since "$this" contains lots of different values I'm wondering how it supposedly finds EPF_BASE_URL as needed. Is it similar to how 'using' directives work in C#?
What is the easiest way to call this function and display the result? This is my biggest question. Would I use a separate PHP class with an HTML form? I understand the concept of what it should do but I'm completely lost setting up a development environment for it.
I've been trying all of this with MAMP but would love to know if I'm on the right track or not.
That really depends on their API. Hopefully you get a string back that can be decoded to a JSON object (http://au.php.net/manual/en/function.json-decode.php). Some API might give a simple string that says 'SUCCESS' or 'FAIL'. You've got the code, so take a look at what $this->pullResponse() gives you.
If you've been given a PHP class that is supposed to support the API (hopefully from USPS), then it should already take care of putting the data in the form content, and ensuring is it submitted with the appropriate content-type.
A PHP const is more like a C# static string. It is very likely that the library will use the constant to create the end URL (i.e. EPF_BASE_URL . $resource). If you needed to run against a sand box environment, you could change that constant without having to change all the other code.
That's a very big question, because it depends on how you are programming your application. Procedural, MVC, existing frameworks, etc.
At the very least, you would set the loginUser and loginPass on the instantiated object, and call the login method`. You could then inspect the results, assuming the result is a JSON object, or use your favourite debugging method to see the contents.
I'm having a guess as the USPS API class name.
$uspsApi = new UspsApi();
$uspsApi->loginUser = 'username';
$uspsApi->loginPass = 'password';
$result = $uspsApi->login();
echo print_r($result, true);

I want to send requests from a UE4 c++ game to my php script, so that it interacts with a mysql database

i'm searching the inet for around 3 days now and i'm stuck at this.
I got a MySQL Database and a php Script, as well as a Game made in UE4.
UE4 uses c++.
So now i want to send requests from the c++ game to the php script and that shall interact with the database.
For example create an account or login. I also want to pass the mysql query result of the php script to my c++ class.
I tried using HttpRequest, but i can't get data from php to c++ with that.
Maybe you can, but i don't understand it at all.
What i accomplished by now is that you can send a POST request from the game to the php script and pass variables so that the script uses them to perform the mysql query.
But how can i pass data from the php file to c++ now? The response i get is always the whole site (head and body) and i don't know where i could save the query result to pass it to the c++ code.
I'm a full beginner here, so go easy on me. I read so many different posts and blogs that my brain hurts like hell ): I hope someone can tell me how to do this easily or at least give me a hint on what i have to google and what i could use. I don't need a full tutorial, just a name of a library better than the Http.h (if simple HttpRequest cant manage this) would be enough. ): I'm really frustrated...
eXi
The PHP script should retun a HTTP response reduced to a bare minimum. It doesn't even need to be a HTML document:
<?php
// file: api.php
$param = $_POST['myparam'];
$foo = bar($param); // $foo contains e.g. "1,ab,C"
echo $foo; // if you opened http://myhost.com/api.php in a browser
// all you would see is "1,ab,C"
// (which is not a valid HTML document, but who cares)
?>
Then parse this HTTP response (a plain string, that is) from your game. You can use your own data format, or use a well-known format of your choice (XML or JSON are good candidates).
The json object in unreal is pretty good, so I would recommend outputting json from your php script. Json in php is a pretty natural workflow.
<?php
$obj['userid'] = 5476;
$obj['foo'] = 'bar';
echo json_encode($obj);
php?>
That will echo out
{"userid":5476,"foo":"bar"}
If that's all you output in your script then it's pretty straightforward to treat that as a string and populate an unreal json object with it.
FString TheStuffIGotFromTheServer;
TSharedPtr<FJsonObject> ParsedJson;
TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(TheStuffIGotFromTheServer);
if (FJsonSerializer::Deserialize(JsonReader, ParsedJson))
{
FString foo = ParsedJson.GetStringField("foo");
double UserId = ParsedJson.GetNumberField("userid");
}
Check out the unreal json docs to get a feel for what you can do with it.

How Do I expose CFPropertyList for IPhone application from CodeIgniter

Is there any possibility to expose CFPropertyList for IPhone application from CodeIgniter website.
I googled the examples and tutorials but I did not find any relevant information.
Simply I want to do the following.
I will call a URL from my Iphone application of the Codeigniter website by passing some query strings
and my php page will fetch the data from my MySql database.
finally it would echo the result in Plist for Iphone application
Thanks for your help!!
Maybe this can help:
The PHP implementation of Apple's
PropertyList can handle XML
PropertyLists as well as binary
PropertyLists. It offers functionality
to easily convert data between worlds,
e.g. recalculating timestamps from
unix epoch to apple epoch and vice
versa. A feature to automagically
create (guess) the plist structure
from a normal PHP data structure will
help you dump your data to plist in no
time.
https://github.com/rodneyrehm/CFPropertyList
I Haven't actually used this.
I use CFPropertyList all the time in my CI apps. The trick is to not use the CI library load method.It will always throw an error because CodeIgniter does not yet support Namespaces (likely why so many people are moving to Laravel), and the CFPropertyList library uses Namespaces.
Here is a example showing how to use CFPropertyList within a CI function:
public function getRecord($id){
require_once(__DIR__.'/../libraries/CFPropertyList/CFPropertyList.php');
$plistfile = ASSET_ROOT . 'uploads/fashion/FasionItems.plist';
$content = file_get_contents($plistfile);
/* notice use of the \ character */
$plist = new CFPropertyList\CFPropertyList();
$plist->parse($content);
$plistarray = $plist->toArray();
foreach($plistarray['Episodes'] AS $key => $record){
if($record['ItemId'] == $id){
return $record;
break;
}
}
return FALSE;
}

Scraping Library for PHP - phpQuery?

I'm looking for a PHP library that allows me to scrap webpages and takes care about all the cookies and prefilling the forms with the default values, that's what annoys me the most.
I'm tired of having to match every single input element with xpath and I would love if something better existed. I've come across phpQuery but the manual isn't much clear and I can't find out how to make POST requests.
Can someone help me? Thanks.
#Jonathan Fingland:
In the example provided by the manual for browserGet() we have:
require_once('phpQuery/phpQuery.php');
phpQuery::browserGet('http://google.com/', 'success1');
function success1($browser)
{
$browser->WebBrowser('success2')
->find('input[name=q]')->val('search phrase')
->parents('form')
->submit();
}
function success2($browser)
{
echo $browser;
}
I suppose all the other fields are scrapped and send back in the GET request, I want to do the same with the phpQuery::browserPost() method but I don't know how to do it. The form I'm trying to scrape has a input token and I would love if phpQuery could be smart enough to scrape the token and just let me change the other fields (in this case username and password), submiting via POST everything.
PS: Rest assured, this is not going to be used for spamming.
See http://code.google.com/p/phpquery/wiki/Ajax and in particular:
phpQuery::post($url, $data, $callback, $type)
and
# data Object, String which defines the data parameter as being either an Object or a String. POST requests should be possible using query string format, e.g.:
$data = "username=Jon&password=123456";
$url = "http://www.mysite.com/login.php";
phpQuery::post($url, $data, $callback, $type)
as phpQuery is a jQuery port the method signature is the same (the docs link directly to the jquery site -- http://docs.jquery.com/Ajax/jQuery.post)
Edit
Two things:
There is also a phpQuery::browserPost function which might meet your needs better.
However, also note that the success2 callback is only called on the submit() or click() methods so you can fill in all of the form fields prior to that.
e.g.
require_once('phpQuery/phpQuery.php');
phpQuery::browserGet('http://www.mysite.com/login.php', 'success1');
function success1($browser) {
$handle = $browser
->WebBrowser('success2');
$handle
->find('input[name=username]')
->val('Jon');
$handle
->find('input[name=password]')
->val('123456');
->parents('form')
->submit();
}
function success2($browser) {
print $browser;
}
(Note that this has not been tested, but should work)
I've used SimpleTest's ScriptableBrowser for such stuff in the past. It's part of the SimpleTest testing framework, but you can use it stand-alone.
I would use a dedicated library for parsing HTML files and a dedicated library for processing HTTP requests. Using the same library for both seems like a bad idea, IMO.
For processing HTTP requests, check out eg. Httpful, Unirest, Requests or Guzzle. Guzzle is especially popular these days, but in the end, whichever library works best for you is still a matter of personal taste.
For parsing HTML files I would recommend a library that I wrote myself : DOM-Query. It allows you to (1) load an HTML file and then (2) select or change parts of your HTML pretty much the same way you'd do it if you'd be using jQuery in a frontend app.

Categories