PHP - Accessing and sending data to process - php

I've been programming a small client-server-application and now I want to show the output of the server-process in a small server-webpage. Everytime, you press a key in the server-console, the current state is output. Assuming, the server is running and I want to show the current state of the server, how would you implement this in PHP?
My thoughts were to get the process and then send a key input. How could you implement this in PHP? The server is running on debian 6 with Apache and PHP 5.4.
Thanks in advance

Depend on how simple you want to go:
the simplest would be to just simulate a get call. for example, the client calls fopen('http://server.example.com/status.php?server=myserver&stats=uptime'); and at the server level, look at $_GET['server'] and $_GET['uptime'] . you can use that method and add authentication either by passing credentials as a variable. The output can be either plain html or json encoded
use xml rpc or soap

Related

php scrape dynamically loaded content via ajax using knockout.js

I need to scrape some data from a website which is being loaded via ajax using knockout.js (I don't know exactly on which technology it is working.)
Site is www.msc.com. Here I am searching for schedules like from Barcelona to Miami. So the result is loaded via ajax but doesn't show up in console or firebug.
I have tried too many times. Any help or suggestion will be appreciable.
Their script is located at: https://www.msc.com/CMSTemplates/CraftedCMS/WebServices/RouteFinder.svc/Routes
They prevent you from calling it directly in a browser tab/window, probably because what you're trying to do is against their policy. If they wanted people to scrape their DATA, they would not block direct requests to their API or they would provide another publicly documented API for you to use on your server.
With that said, you can see in your browser console that their web service returns JSON objects. You will have to hack (maybe illegally) your way by faking protocol variables in order to accomplish what you're aiming for. The first things to consider is that they only return results through that web service when:
a) The call is made through XMLHttpRequest as POST. (This you can fake it easily, but the next points, not so much...)
b) The call is made using a referer, in this precise case, the referer is: https://www.msc.com/routefinder?fromId=406&isCountryFrom=false&toId=83&isCountryTo=false
c) The call passes a cookie to the server, which is encrypted and signed, so each session is in their database and your key is probably unique, so good luck decrypting this: CMSPreferredCulture=fr-FR; ASP.NET_SessionId=gza5rfjrog2eb21ukrzma223; BIGipServerkentico.app~kentico_pool=439883018.20480.0000; bbbbbbbbbbbbbbb=LIKIGEACDJHDJPGPEOKGJBKODKDGOMHNKAEGEGKNODEDAEILEICBMLNLEFMAOIPPKMOIBBFAILFEEKJPIJDCBDDLFNBBMBPBGGKAIDOCMGHBEEIDMLPMIJJAMNFNIFMI; rxVisitor=1497537754979PTPODMSFNIR8BFVAKK353FS76M2D1KNN; dtPC=3$537845860_975h-vCQTABPJMGEOKDPDVNLHPCPDASGAPMCPCBA; rxvt=1497539656937|1497537754995; dtSa=-; dtLatC=8; _ga=GA1.2.1247106544.1497537756; _gid=GA1.2.879601947.1497537756; _gali=results; cookiePolicyApproved=true; MSCAgencyId=355840; _gat=1; _gat_local=1; dtCookie=3$B74DFC30736F7DBF485B79C31C55B167|www.msc.com|1

What are the options for passing data to PHP? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
With minimal "real" programming experience, I am working on a project that integrates a FileMaker Pro solution, which I have already built, with a native iOS application using FileMaker Server's PHP API. The iOS application is for iPhone and is written in Swift.
We are trying to understand the most efficient ways to approach some scenarios, particularly in writing data back to the server. Let's use the simple example of an address book. When a user navigates to a contact record, he/she can select a field, edit then save it's contents.
While we have already implemented a number of functions that write data to the server, they have all been relatively simple (like scanning a barcode, sending a php request that triggers a script in FM Server and then presenting the result to the client). It seems like, in the case of a contact record with many fields, that sending the value of each field as a variable, some of which may be paragraphs or photos, through a standard PHP URL inefficient and bulky.
For those unfamiliar with the FileMaker PHP API, below is some sample code to demonstrate the process of updating a specific contact record. The sample code does the following:
Sets parameters passed from the client as variables.
Defines the layout on which the code should be executed (FM PHP API works on layouts, not tables like SQL)
Finds a record and updates the fields.
Sample Code:
<?php
require_once 'Filemaker.php';
//connect to db
$fm = new FileMaker();
$fm->setProperty('database', 'fmDbName');
$fm->setProperty('hostspec', '123.45.67.89');
$fm->setProperty('username', 'user');
$fm->setProperty('password', 'password');
//define layout on which to process
$layout = 'php_contacts';
//define variables passed from client
$contactId = $_GET['contactId'];
$first = $_GET['firstName'];
$last = $_GET['lastName'];
$mobile = $_GET['mobile'];
$office = $_GET['office'];
$note = $_GET['note'];
//Find the contact which is being updated
$find = $fm->newFindCommand($layout);
$find->addFindCriterion('contactId', $contactId);
//execute the find
$results = $find->execute();
//check for error
if (FileMaker::isError($result)) {
echo " Error: ".$results." ";
exit;
}
//declare the record being updated
$record = $results->getFirstRecord();
//update the fields
$record->setField('firstName', $first);
$record->setField('lastName', $last);
$record->setField('mobile', $mobile);
$record->setField('office', $office);
$record->setField('note', $note);
?>
The challenge we are facing is not how to implement a particular approach, rather, the challenge is understanding what the options are in the first place and any best practices that go along with them.
For example, is sending the variables from the client to PHP as an array or dictionary a better practice than sending them as independent variables in the URL? What are some other options for neatly pushing data from multiple fields in a native application to the PHP server?
Thanks!
I'm pretty sure PHP basically works with HTTP requests, that is basically POST and GET.
The structures you send should be defined by what you need, there is no perfect solution.
You should check how HTTP requests work:
http://www.w3schools.com/tags/ref_httpmethods.asp
$_GET is much slower than $_POST from my understanding. You should send POST requests to the server from your application which will transfer strings. Sending raw images over the Internet can easily lead to distortion and missing data. In order to send images as strings you would use Base-64 encoding. That means you'll convert the image binary to an encoding scheme which returns a string. You can send this string to the server or the application for decoding. (Note: You can use Base-64 encoded images as URLs, which may come in handy.)
I don't believe there's a better way to send data between a server and client aside from using either a POST message or raw JSON if you can do that. Swift and Objective-C have a class named NSJSONSerialization which you can use to convert JSON returned from a PHP script for use later in your application.
From your server you can simply create an empty array in a variable at the beginning of the script for later use then append information to that array as it becomes available (If you have an image on your server you'll want to Base-64 encode it then append the string to the array only after the Base-64 encoding completes). At the end of the script -- when you have all of the data you want to send to the application appended to that array -- you can write echo json_encode($thatArray) to send the array back to the application as JSON. Of course, that means you'll want this to be an associative array from the beginning, because you'll have key and value pairs.
I'd rely on that method to fetch information from the server and flip it around (create a Dictionary in the Swift application then use NSJSONSerialization.JSONObjectWithData(data: NSData, options: NSJSONReadingOptions, error: NSErrorPointer) to convert the Dictionary to JSON. Then create a request which will send that JSON to the server via a POST request. Of course, your PHP script would use json_decode($_POST['thatJSONFromTheApplication'])) for the application to send JSON to the server.
That's what I've done to allow my application and server to work together. If you read this and you have a better idea, do share!
So there are a couple of things you could or should do.
Should do:
Move credentials out of the document
Move your database connection information out of your php code and into a configuration file stored outside of the server document root, i.e. if your doc root is at:
/var/www/myapp/public/
You could store your configuration file at:
/var/www/myapp/config/
That way if php somehow fails and returns as text vs php code, your credentials are not exposed. You could do this in many ways, but the easiest I've seen is to define them as constants. e.g.:
// File config.php
define('FM_DATABASE', 'fmdbname');
define('FM_HOSTSPEC', '123.45.67.89');
define('FM_USERNAME', 'user');
define('FM_PASSWORD', 'password);
and require the config file in your code and use the constants in your connection object:
$fm = new FileMaker(FM_DATABASE, FM_HOSTSPEC, FM_USERNAME, FM_PASSWORD);
Never dump the entire result if it's an error
You're not doing this in your code, but it's a good thing to know if you're dealing with the FileMaker PHP API. The Error Result object that is returned if your runs into a snag will contain your connection credentials. I have no idea why this is so, but it is. Never dump the entire object to the client because you'll be exposing those credentials as part of the dump.
FileMaker's Error object extends the Pear Error Object, so if you end up wanting to pass back information on an error that was encountered you can use any of the pear error methods.
Use the connection object to test for errors
The FileMaker API code is pretty out of date when it comes to php. the static method FileMaker::isError is actually not defined as static in the API code. This means unless you supress the deprecated messages on your web server you'll have the web server barking at you about it. The thing is, you've already created an instance of the FileMaker object so you can use it to check if your result is an error:
if($fm->isError($result)){ // this won't produce the deprecated warning.
...
That said, you'll probably see a bunch of other errors because of other deprecated code in the api :P
Could do:
Cache the record id in your client app
Right now you're performing a find for a record, updating it's fields, and committing it. This emulates the FileMaker experience, but because you're editing the data via the php interface you may be able to short cut it a bit.
If your client application (the swift app) knows the record id for the record that it's updating already then you could use the newEditCommand to update the record instead. The edit command uses the FileMaker internal record id (i.e. the id that FileMaker gives the record, not the id from your user-added primary key) to determine which record to update. Here's an example of how you'd use it:
$editQuery = $fm->newEditCommand('my_layout', $recordId);
$editQuery->setField('Status', $newStatus);
$editResult = $editQuery->execute();
The advantage of doing this is less processing time for FileMaker Server. You're not asking the server to find the record so you can edit it, you're telling it what record to edit.
Depending on how the business logic flows through your apps this may not be an option, but if you could store the record id on the client side it may help make the communication a bit snappier.
Handle the updates in batches
It looks like you're already doing this, but be sure to send the data in a batch vs one field at a time. I would agree with Arcrammer's comments about using POST instead of GET as POST is the intended method for sending data to the server.
Those are my suggestions on your code. I would also suggest digging around in the API code. I find that looking over the objects and there methods answered a lot of questions for me that the documentation and tutorials that FileMaker provides for the API did not.
Good luck!

PHP Get Cookie by Session ID (or otherwise pass data between two different connections)

Normally I try to format my question as a basic question and then explain my situation, but the solution I'm looking for might be the wrong one altogether, so here's the problem:
I'm building a catalog application for an auction website that has the ability to save individual lots. So far this has worked great by simply creating a cookie with a comma-separated list of IDs for those lots, via something like this:
$_COOKIE["MyLots_$AuctionId"] = implode(",",$arrayOfIds);
The problem I'm now hitting is that when I go to print the lots, I'm using wkhtmltopdf through the command-line to request the url of the printout I want, like this:
exec("wkhtmltopdf '$urlofmylots' filename.pdf");
The problem is that I can't pass a cookie to this call, because Apache sees an internal request, not the request of the user. I tried putting it in the get string, but once I have more than a pre-set limit for GET parameters, that value disappears from the $_GET array on the target url. I can't seem to find a way to send POST data between them. My next possible ideas are the following:
Maybe just pass the sessionID to the url, and see if there's a way that I can use PHP to dig through the cookies for that session and pull the right cookie, but that sounds like it'd be risky security-wise for a PHP server to allow (letting one session be aware of another). Example:
exec("wkhtmltopdf '$urlofmylots?sessionId=$sessionIdFromThisRequest' filename.pdf");
Possibly set a session variable and then pass that session Id, and see if I can use PHP to wade through that information instead (rather than using the cookie).
Would I be able to just create an array and somehow have that other script be aware of it, possibly by including it? That doesn't really solve the problem of wkhtmltopdf expecting a web-facing address as its first parameter.
(not really an idea, but some reasoning) In other instances of using this, I've just passed an ID to the script that generates the markup for wkhtmltopdf to parse, and the script uses that ID to get data from the database. I don't want to store this data in a file or the database for the simple purpose of transferring data from the caller to the callee in this case. Cookies and sessions seem cleaner since apache/php handle memory allocation for these sessions.
The ultimate problem here is that I'm trying to get my second script (referenced here by $urlofmylots) to be aware of data available to the calling script but it's being executed as if it were an external web request, not two php scripts being called from the web root.
Can anyone offer some insight here?
You might consider rendering whatever the output of $urlofmylots?lots=$lots_to_print would be to a temporary file and running wkhtmltopdf against that file.

How to check availability of an ID in same page?

To be specific, I want to make code like Yahoo's Registration (Yahoo ID - Check Availability) checking the availability. The problem here is I need to use PHP to connect, get, and search/verify if the entered value in the textbox is unique.
I tried passing a JavaScript value to a PHP variable, but based on my research, doing this isn't possible, so I need another possible solution to get the value of the textbox and set it to a PHP variable.
Thank you in advance.
The only way to get data from JavaScript to PHP (in a typical environment) is to deliver it over HTTP. Doing this without leaving the page is known as Ajax, and usually done using XMLHttpRequest.
There are no shortage of tutorials describing how to do this, nor any shortage of libraries that will help (plus, of course, all the large libraries such as YUI and jQuery).
You can use Ajax for manipulating this situation.. Have a look at following link.
http://www.digimantra.com/technology/javascript/check-username-availability-validation-ajaxphp/
You need to use AJAX for that.
AJAX is used to send and receive data from the server. So, on the server side, you can create a URL that checks whether a username (can be passed using get/post) is available or not & accordingly send a response. At the client side, depending on the response you receive from the server, you can alert the user.

Detecting and pushing a stream of events to a web browser (HTML5, PHP, PostgreSQL)?

My currently in-development website is written in PHP. As users are using the site, they'll be performing actions and I'd like to be able to push notifications of these actions to other users that they're connected to.
Now while I'm sure that using EventSource and a PHP document to server up the appropriate data: lines would work, I've got absolutely no idea how I should notify that PHP document when a new message actually needs to be sent.
What I essentially mean is that when an action takes place, there will be an entry into the PostgreSQL database with the message information (such as the action that was taken). However, it's not efficient to have each instance of the "messaging" PHP document (the one that EventSource is connected to) to continuously poll PostgreSQL for new messages. With 50 users active at once, that would be 50 instances polling PostgreSQL, and as you can probably see, not a very efficient use of resources.
So I'm wondering whether anyone has any suggestions as to software that might assist with this problem. Ideally I'd like to be able to call a function that indicates an action has been undertaken, which is then sent all the other instances of "messaging" PHP document so that they can interpret the message and see whether it's relevant and push it back to the client.
Essentially I need a way to notify running PHP instances (that were started via Apache) of a new message being created, by calling a function in another PHP instance with the message information. I don't need assistance with getting the messages to the client; I can do that with EventSource.
Does anyone have any suggestions as to how this task could be undertaken?
Conventional ways of solving the problem are using a java applet (which can open a socket back to the originating server) or using long polling (e.g. comet).
I've succeeded in doing this by using memcache with a messages-count key-value and a message-$i key-value where $i is an incrementing number. A PHP document is connected to via long polling and it continuously checks to see whether message-$(messages-count) exists, in which case it returns it.
There's a bit more to this since it will return multiple messages if they're created at once and also can load the initial checking number ($i) as a $_GET parameter, but this is essentially how it works. It's near instant and new messages can easily be added to memcache via PHP (each time you create a new message, you increment messages-count).
Take a look at php mem sharing

Categories