I am trying to retrive data to my SL application from PHP, MySQL service which is hosted locally on Xampp.
I can see my php file running OK and deliver results via JSON (http://localhost/silverlight/data.php) but SL cannot receive it. I belive it has something to do with correct URl path but I cant figure it out. Also I've putted clientaccesspolicy.xml file to allow cross-domain access but with no avail:(
public partial class MainPage : UserControl
{
WebClient wc = new WebClient();
ObservableCollection<ToDoItem> myToDoList = new ObservableCollection<ToDoItem>();
string baseURI = "http://localhost/silverlight/";
public MainPage()
{
InitializeComponent();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri(baseURI + "data.php",UriKind.Absolute));
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null && e.Result!= "")
{ JsonValue completeResult = JsonPrimitive.Parse(e.Result);
string resultType = completeResult["returnType"].ToString().Replace("'", "").Trim();}
The clientaccesspolicy.xml file you use only allows cross-domain access for web service requests (as specified by http-request-headers="SOAPAction")
For WebClient to work the way you use it, you need to enable content requests as well.
Try specifying http-request-headers="*" or http-request-headers="SOAPAction,Content-Type".
Also, do check that the clientaccesspolicy.xml file is located at the root of the host, i.e. http://localhost/clientaccesspolicy.xml. Eventually when you decide to deploy your application, you'll have to make sure the file is placed in the root of the deployment host as well, e.g. http://example.org/clientaccesspolicy.xml
Related
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 have a domain using Php but I added asp.net code. And try to execute that it displayed asp.net code only. Whether it is possible to add asp.net code under php domain by using any plugin or some third party help. If yes means, give some idea.
You could use HttpWebRequest to get a result off a PHP page which might help you a bit. An example taken from: https://stackoverflow.com/a/9818700/4068558
string myRequest = "abc=1&pqr=2&lmn=3";
string myResponse="";
string myUrl = "Where you want to post data";
System.IO.StreamWriter myWriter = null;// it will open a http connection with provided url
System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(myUrl);//send data using objxmlhttp object
objRequest.Method = "GET";
objRequest.ContentLength = TranRequest.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type
myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
myWriter.Write(myRequest);//send data
myWriter.Close();//closed the myWriter object
System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();//receive the responce from objxmlhttp object
using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
{
myResponse= sr.ReadToEnd();
}
Otherwise, the problem is IIS will see a .php file and compile it with PHP. Vice versa with ASP. Although a work around for running PHP inside ASP.NET is phalanger.
I used couchdb's PHP lib to add a view:
public function addView() {
$design_doc = new stdClass();
$design_doc->_id = '_design/need';
$design_doc->language = 'javascript';
$design_doc->views = array( 'all' => array('map' => "function(doc) { if (doc.type == 'need') emit(doc.type, doc) }" ) );
$result = $this->client->storeDoc($design_doc);
return $result;
}
In my shell, I viewed its doc to confirm it was created:
curl -X GET mysite.com/bids/_design/need
{
"_id":"_design/need",
"_rev":"1-0ed4b41b839ade9ca36fb950cac1c39b",
"language":"javascript",
"views":
{
"all":
{
"map":"function(doc) { if (doc.type == 'need') emit(doc.type, doc) }"
}
}
}
Then when trying to actually execute the view, it throws eacces error:
curl -X GET mysite.com/bids/_design/need/_view/all
{
"error":"error","reason":"eacces"
}
Permissions: the instance is running as root.
Am I using the wrong syntax to execute the view query?
Could it be that there is an issue with the encoding of the string that was passed via PHP?
"eacces" suggests that it's a problem with the permissions or ownership on the directory your databases are stored in.
For each database, the database server will create a subdirectory called .<db_name>_design containing a file for each design document in that database. It's likely that the user your CouchDB instance is running as doesn't have permission to create that directory, or perhaps the file within it.
Check that the directory your databases are in, and everything thereunder, is owned by the user your CouchDB is running as, and that the directories and files have sensible permissions. It's /usr/local/var/lib/couchdb if you installed from source, but will probably be different if you used a package.
There was some issue with character encoding by php. Running the exact same query in curl was successful and the view was then able to run properly
I'm trying to deploy flash files embeded in html to the google app engine.
Flash(action script 2.0) uses "post" method to send hostname and get its ip address through php function gethostbyname().
In fact, I know google app engine does not support php.
So I tried to use another way to deploy ipPHP.php in other free web server and only flash file in google app engine.
But it does not work and I can not know why.
Can you give me a tip for this problem ?
--------------domaintoip.fla ---------------------
result_lv = new LoadVars();
result_lv.byname = _root.domainnm;
trace("Sending... " + result_lv.byname);
result_lv.onLoad = function (success)
{
if (success)
{
_root.ip = unescape(this.result);
trace("Return value from the PHP : " + unescape(this));
if(_root.ip.length==5){
_root.flag=1;
}
else{
var mystring=_root.ip;
arr=mystring.split(".");
_root.ipby1=arr[0];
_root.ipby2=arr[1];
_root.ipby3=arr[2];
if(arr[3].length==15)
{
_root.ipby4=arr[3].substr(0,3);
}
if(arr[3].length==14)
{
_root.ipby4=arr[3].substr(0,2);
}
if(arr[3].length==13)
{
_root.ipby4=arr[3].substr(0,1);
}
_root.flag=0;
}
}
else
{
trace("Cannot call the PHP file...");
_root.flag=1;
}
}
result_lv.sendAndLoad("http://anotherserver../ipPHP.php", result_lv, "POST");
-------------- ipPHP.php ---------------------
<?php
$Var1 = $_POST['byname'];
$rtnValue = gethostbyname(trim($Var1));
if(ip2long($rtnValue) == -1 || $rtnValue == $Var1 ) {
$rtnValue =0;
echo (result=$rtnValue");
}
else {
echo("result=$rtnValue");
}
?>
If your site is hosted on the app engine, you cannot make AJAX calls to a host other than the app engine due to the Same Origin Policy. This limitation is generally true, and is not specific to the app engine. To generalize, for any web page hosted at domain X, that web page cannot make AJAX requests to domain Y.
You actually are experiencing a much more fundamental problem: When the only tool you have is a hammer, every problem looks like a nail. In fact, you can trivially handle POST requests with the app engine using the doPost method, and you can very easily get the client's IP address in a very similar manner as your PHP script. There is absolutely no reason to use PHP here; you've set up a completely new server to call one built-in PHP function? That's insane; you can do the exact same thing with an app engine servlet.
Consider the following code:
public void doPost(HttpServletRequest request,HttpServletResponse response) {
/* get "byname" param, equivalent to $POST['byname'] */
String rtnValue = request.getParameter("byname");
/* TODO: your if statements and other logic */
/* print response to client, equivalent to your echo statement */
response.getWriter().print("result=" + rtnValue);
}