Wrapping a file on my web server - php

I'm currently researching this as we speak. Putting this question here hoping to see some awesome insights. Here's my question:
I am developing an android application that downloads files from my web server to be displayed in the app, and available for offline use.
If my app goes to https://www.mydomain.com/abc/xyz.png to download the file, how can I make that same url not publicly available? i.e. if you type https://www.mydomain.com/abc/xyz.png into your browser address bar, you will be taken somewhere other than the png file.
I think I need some kind of wrapper here, but I'm new to all of this and trying to learn fast.
Any help is appreciated.
For what it's worth, I will be using a mySql database with either workbench 6.0 or phpMyAdmin.
EDIT
In response to the first two responses:
So my code here in my android app where I download the file and save it to internal storage that looks like this (where base path gets me to the web directory of the file):
url = new URL(basePath + fileName);
URLConnection connection = url.openConnection();
int lenghtOfFile = connection.getContentLength();
inputStream = new BufferedInputStream(url.openStream());
outFile = new File(context.getFilesDir() + "/" + fileName);
fileStream = new FileOutputStream(outFile);
outputStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
would change to say:
url = new URL(basePath + "download_file.php" + "?key=hardcodedkey&file=" + fileName);
URLConnection connection = url.openConnection();
int lenghtOfFile = connection.getContentLength();
inputStream = new BufferedInputStream(url.openStream());
outFile = new File(context.getFilesDir() + "/" + fileName);
fileStream = new FileOutputStream(outFile);
outputStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);

You have a few options here.
1.) Not great-> .htaccess to restrict certain referrers, all but Android for example.
2.) Greater -> Use a PHP file to output the image if GET var is the same as the pass. e.g.
if (isset($_GET["pass"]) && $_GET["pass"]=="8h932mgks984jsolm9sjt4ms") {
header('Content-type:image/png');
include('/path/to/thePngFile.png');
} else die("nothing to see here..");

A simple way might be calling a php script with a certain key as secret parameter and the image or file you want to download.
www.myweb.com/myfunction.php?pass=secretPassword&file=image.png
This key will be harcoded in the call from your application.
Then you could just check if the password is the one you expect with something like:
//hardcoded hashed pass with sha1, for example.
$myHashedPass = '40bd001563085fc35165329ea1ff5c5ecbdbbeef';
if(sha1($_GET['pass']) != $myHashedPass){
die();
}
//download of file...
Inside the PHP application you can start the download or not depending on the password.

Related

I'm looking for a way to load data from PHP in Android as PHP echoes the data

Right now, I'm using an ASYNC task to load data. In current case, php echoes the complete JSON, and then android reads the whole string and display it. Problem that I'm facing here is that, php takes time to echo the full data.Php does echo one entry in 2 sec. What I want is that, for my android device to read the response as it is coming, dont wait for the JSON to complete but read it as it is coming and display. Here is what the current code looks like
PHP:
<?php
while(entry!=0){
data[] = processentry(entry);//will take 1-2 secs to process a single entry
entry--;
}
echo json_encode(data);
?>
Android side:
URLConnection con = new URL("someURL").openConnection();
con.setDoOutput(true);
OutputWriter out = new OutputWriter(con.getOutputSream());
out.write(/* post params */);
out.close();
BufferedReader br = new BufferedReader(new InputReader(con.getInputStream));
while( (tmp = br.readline()) != null)
decodedStr += tmp;
decodedStr contained the complete json which can then be read by android device
I want PHP to echo in the while loop itself and let the android read as the data is recieved.
Any suggestions?
You have to set timeout once php finish it task you have to set timeout on android side
int ConnectTimeout=15000;
int ReadTimeout=15000;
con.setReadTimeout(ReadTimeout);
con.setConnectTimeout(ConnectTimeout);

Download or Access to SharePoint Online Documents using PHP / XML / SOAP

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!!!!!

download values of sql table for offline reuse

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)

Can I run asp.net code on a PHP server?

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.

Getting a HeartBeat from a C# Application and Posting it To Website

I've got a Minecraft Software written in C# that I want to send a heartbeat to my site. I've got the way to send the beat already written.
if (Server.Uri == null) return;
string uri = "http://GemsCraft.comli.com/Heartbeat.php";
// create a request
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
// turn request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(string.Format("ServerName={0}&Url={1}&Players={2}&MaxPlayers={3}&Uptime={4}",
Uri.EscapeDataString(ConfigKey.ServerName.GetString()),
Server.Uri,
Server.Players.Length,
ConfigKey.MaxPlayers.GetInt(),
DateTime.UtcNow.Subtract(Server.StartTime).TotalMinutes));
request.ContentType = "application/x-www-form-urlencoded";
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
request.ContentLength = postBytes.Length;
request.Timeout = 5000;
Stream requestStream = request.GetRequestStream();
// send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Flush();
requestStream.Close();
/* try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Logger.LogToConsole(new StreamReader(response.GetResponseStream()).ReadToEnd());
Logger.LogToConsole(response.StatusCode + "\n");
}
catch (Exception ex)
{
Logger.LogToConsole("" + ex);
}*/
}
Now, I want to be able to retrieve the heartbeat in PHP, upload it to the SQL database, and then display each user's server in a table that will be displayed on the webpage
How do I do this?
portforwardpodcast's answer isn't very well-suited for your purposes, here's a process for you to ponder
Server accesses the following page: heartbeat.php?port=25565&maxplayers=25&players=2&name=Cheese_Pizza_Palace
Your PHP script will then do the following...
Go through each value, making sure they're all the types you want them to be (integers/strings)
Connect to the database
Update the server in the database if it already exists, create it if it doesn't
Return some value so the server knows that it completed successfully.
And to display the servers
Fetch all 'active' servers
Loop through them and display each one.
Things you'll need to figure out:
How to determine uptime
How to determine "active" servers
How to update/create MySQL entries
How to (properly) connect to a database. I would suggest using PDO since you're using PHP. It's a bit difficult to learn, but it's much more secure than writing the queries directly.
How to loop through all the GET variables.
Good hunting!
I would create a simple php page accept a get variable. something like www.site.com/beat.php?lasttime=123456&serverid=1 where the number us the unix timestamp. Then you need to re-work your c# to do a simple get request on a website. Finally your php should insert into a mysql table with a column for id, timestamp, server_id etc.
First you need to pull the data from the request. The $_REQUEST variable in php is nice because it works for both GET and POST:
http://php.net/manual/en/reserved.variables.request.php
Start out by var_dump or echo the fields you want. Once you can get the needed data into variables you are done with the first part. For the next part you need to create a database and table in MySQL. The best tool for this is phpmyadmin. If you have a host like godaddy (or some others) you can get at this from the control panel. If not you may need to install upload the phpmyadmin files yourself. It's a pretty simple tool to use:
http://www.youtube.com/watch?v=xxQSFHADUIY
Once your database has the correct columns, you need to insert the data from your php file. This page should help:
http://www.w3schools.com/php/php_mysql_insert.asp

Categories