FLASH AS2 and PHP variables - php

My Flash movie reads and sends data to a PHP file in a free server. It seems ok for Flash to read variable values from a text file (which is managed by a PHP file) if they are wrote in this way: &variable = value&, I have no problem with that.
But my PHP file, pre-treated (by some mathematical functions) data sent by Flash and then, updates the values in the text file, that is my intention but I can't accomplish it.
Suppose I want to update a counter ( it counts how many times the data were updated):
in the text file I have &counter=0& (initial value) and if I put in the PHP file:
<?php
$fp = fopen("jose_stats.txt", "r");// I guess with it, I've read all the variables and values
// one of them is the variable &counter.
fclose($fp);
$toSave = "&counter=&counter+1&\n";
$fp = fopen("jose_stats.txt", "w");
if(fwrite($fp, "$toSave")) {
echo "&verify=success&"; //prints to screen &verify=success which flash will read
//and store as myVars.verify
} else { // simple if statement
echo "&verify=fail&"; //prints to screen &verify=fail which flash will read and
//store as myVars.verify
}
fclose($fp);
?>
but then, I check my text file and it has &counter=&counter+1& line :( and not the expected &counter =1&.
Please, give me and advise. Thank you.

Why not use JSON?
Just store the data in JSON format:
$count = 1;
$toWrite = array( 'count' => $count );//put other data into this array if you want
//encode it
$toWrite = json_encode( $toWrite );
//and now write the data
To decode it in flash, import the JSON class:
An example of JSON in as2 using the JSON.as class:
try {
var o:Object = JSON.parse(jsonStr);
var s:String = JSON.stringify(obj);
} catch(ex) {
trace(ex.name + ":" + ex.message + ":" + ex.at + ":" + ex.text);
}
So just import the class, and run JSON.parse( yourPhpResponse );.
Also, the reason for why you're seeing &counter=& in the text file is because you're storing it like that: $toSave = "&counter=&counter+1&\n";.

Related

How to generate csv file with ajax call in php

I am working with PHP AJAX DATATABLE (in drupal). I am making a function to generate csv file of the table record.
I create a button to click (in html) to access that link (or if i am calling it by url. )
I did it and my function(php Function) is working fine.
But how can i create a csv on depends on searched values ? I dont want to refresh my page and i think ajax call help me.
But how to handle my csv file creation function in ajax call.
My php function
/* testing the excel output */
function export_to_excel_page() {
//testing
$filename = "file_name.csv";
$row_array = db_query('SELECT recipient_name , year , title , sector , region , commitment_million_inr FROM {#######} ');
drupal_add_http_header('Content-Type', 'text/csv; utf-8');
drupal_add_http_header('Content-Disposition', 'attachment; filename=' . $filename);
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('recipient_name', 'year', 'title', 'sector','region','commitment_million_inr' ));
foreach($row_array as $key => $value) {
fputcsv($output, (array)$value);
}
}
If you are using an on click event you can use the JQuery $.get function to do what you want.
//change #button to whatever id or class name you are using in your html
$("#button").on("click",function(){//begin on click event
$.get("place path to the csv here",function(data){//begin function
//Use the data parameter passed in to the function to manipulate(parse)
//your data returned from your csv file here.
//if you want to see if there is a string inside of the data
//indexOf returns -1 if the item is not found
//Check to see if the searchterm is found or is not equal to -1
if(data.indexOf("searchterm") !== -1){//begin if then
//Do something if you find the searchterm string.
}//end if then
//if they are comma seperated values you can first
//turn the csv into an array
var csv = data.split(",");
//loop through the array do whatever you need to do
for(var i =0; i < csv.length; i++){//begin for loop
//if the array index equals the string something
if(csv[i] === "something"){//begin if then
//do something like turn the csv into an undordered list
}//end if then
}//end for loop
});//end function
});//end on click event

How to dump string variables to a text file [duplicate]

This question already has answers here:
How to write into a file in PHP?
(9 answers)
Closed 9 years ago.
I have a series of variables in my PHP script that are defined via POST.
For example:
$From = "";
if( isset($_POST['From']) )
{
$From = $_POST['From'];
}
How can I create a log file (not a database, just basic txt) to capture the POST values? This is part of a conferencing web app, so there is no way to display the content "on screen". I need to dump it to a file on the server.
JSON-encode your array using json_encode() and store it to a file:
$data = json_encode($_POST);
file_put_contents('file.txt', $data);
When you want to retrieve the contents, you can use file_get_contents() or similar and then use json_decode() to decode the JSON-string back into an array / object.
Using JSON makes the interchanging of data easier, and you don't need to parse the text file to retrieve information out of it. Just use json_decode() and be done with it. However, I suggest you use a database instead of a plain text file to store this information, as it gives you more control.
As #Wrikken noted in the comments below, you could use the FILE_APPEND flag - it allows you to append the data to the file instead of overwriting it.
file_put_contents('file.txt', $data, FILE_APPEND);
Try something like this
$post_dump = print_r($_POST, TRUE);
$log = fopen('log.txt', 'a');
fwrite($log, $post_dump);
fclose($log);
Something like this
$arr = array();
foreach($_POST as $key=>$value);
{
$arr[] = $key.'='.$value;
}
file_put_contents('log.txt', implode(',', $arr), FILE_APPEND);
try this...
<?php
$From = "";
if( isset($_POST['From']) ){
$file = fopen("test.txt","w");
fwrite($file,$From);
fclose($file);
}
?>

Is it possible to combine ImageNow with Javascript and php?

I currently have an internal site for my company where our customer support users will be uploading files from our clients. Originally, I had planned on using the help of mysql and a protected, shared network folder and used mysql to hold the filename and path. However, we also utilize ImageNow for other processes. Does anyone know if ImageNow works with javascript and php outside of the software itself? I'm new to ImageNow so any advice is appreciated.
logObArray = getDocLogobArray(workingDoc);
for (var i=0; i<logObArray.length; i++)
{
var docObj = logObArray[i];
var filePath = docObj.filePath;
var fileType = docObj.fileType;
var ftToCheck = fileType.toUpperCase();
var phsobID = docObj.phsobId;
//write OSM info to the file, you'll have to add the other code around this but premise is correct and tested
var outRow = filePath;
outRow = outRow + '\n';
if (Clib.fputs(outRow, outCsvFP) >= 0)
{
debug.log('DEBUG', 'Wrote OSM Path [%s] to file successfully.\n', filePath);
stats.inc('Wrote OSM Path to file');
}
}
Unfortunately, ImageNow doesn't let you get at the information it stores outside of Perceptive Software provided tools. Even if you dig directly into the SQL database and look at the filesystem where it is storing the files, you can't get the information out. ImageNow stores the files unencrypted on the filesystem, so that's fine, and it stores the metadata for those images in easy to search tables in the database. However, the path from the metadata to the filesystem it encrypts before it stores it in the database. So if you are trying to go from the metadata to the images, the farthest along you can get is to the encrypted path. Without the decryption key, you can't get to the images.
However, there is a way you can write code to use ImageNow data. You need the add-on Message Agent - which you need to purchase from Perceptive. That opens up interfaces for using web services and SOAP to get at the ImageNow data.
This is the complete solution for this. It gets the root file and subsequent pages. All other solutions I've found do not get anything other than the first page of the scanned document. Change your drawer to your own drawer name (btw). I hope this helps someone. Companies that lock down people's content really make me mad. Just use the intool.exe utility. It's located in the /bin folder of your installation. The call is: intool --cmd run-iscript --file yourfile.js
var curDocId = 0;
var more = true;
// printf("curDocId : %s\n", curDocId );
while (more) {
var rulestext = "[drawer] = 'AR' AND [docID] > '" + curDocId + "'";
var items = INDocManager.getDocumentsByVslQuery(rulestext, 1000, more, "DOCUMENT_ID");
var start = items[0];
var dataDesc = new Array();
var headerDelim = "\03"
var dataDelim = "\02";
for (var line=1; line <= start; line++) {
var temp = items[line].split(headerDelim);
dataDesc[temp[1].toUpperCase()] = new Object();
dataDesc[temp[1].toUpperCase()].idx = line - 1;
dataDesc[temp[1].toUpperCase()].name = temp[1];
dataDesc[temp[1].toUpperCase()].datatype = temp[2];
}
for ( ; line < items.length; line++) {
var doc = new INDocument(items[line].split(dataDelim)[dataDesc["DOCUMENT ID"].idx]);
doc.id = items[line].split(dataDelim)[dataDesc["DOCUMENT ID"].idx];
doc.getInfo();
var masterDocId = doc.id;
var itCounter = 150;
var i = 1;
for( ; i <= itCounter; i++)
{
doc.getInfo();
var logob = INLogicalObject( doc.id, -1, i );
logob.retrieveObject();
if(logob && logob.logobCount > 0)
{
var fp = Clib.fopen("c:\\inowoutput.txt", "a");
var line = masterDocId + ',' + logob.id + ',' + logob.workingName + ',' + logob.filePath + '\n';
Clib.fputs(line, fp);
Clib.fclose(fp);
}
else
{
break;
}
}
curDocId = doc.id;
}
//printf("curDocId : %s\n", curDocId );
}
ImageNow has a scripting language that lets you get past the encrypted file path in the database. The file path is available in an undocumented member of the INLogicalObject. Details below for accessing taken from the following blog article. Accessing the encrypted file path in ImageNow
A search of the ImageNow 6.x specific object documentation will find that the INLogicalObject provides information about the actual files stored in the file system. However, it does not contain any information about the file path. A little closer inspection under the hood of the object reveals that it does have a file path field and the value is not encrypted. It is a member of INLogicalObject. The following very simple example shows finding a single document and displaying its file type and unencrypted file path on the console.
// get a single document
var results = INDocManager.getDocumentsBySqlQuery( "", 1, var more );
if ( results )
{
var doc = results[0];
doc.getInfo();
// get a single page for the document
var logob = INLogicalObject( doc.id, -1, 1 );
logob.retrieveObject();
printf( "file type: %s\n", logob.filetype ); // this member is in the documentation
printf( "unencrypted file path: %s\n", logob.filepath ); // this member is not in the documentation
}
Check out External Messaging Agent (EMA) functionality in ImageNow. It's a free module that is available in every installation.
EMA allows you to receive data from outside the ImageNow system (e.g. from a PHP web form, for example).
To use EMA, you merely would need to have the PHP script insert into the IN_EXTERN_MSG and IN_EXTERN_MSG_PROP tables. One of the properties could be the location of the file that was uploaded via PHP.
You'd then need an iScript to parse the data from the EMA tables and create a document in ImageNow.
I've built a solution like this before, and it works pretty well.

PHP Write Posted Data to File

I'm relatively new to PHP and I'm trying to get a small script running. I have a VB .net program that posts data using the following function.
Public Sub PHPPost(ByVal User As String, ByVal Score As String)
Dim postData As String = "user=" & User & "&" & "score=" & Score
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("http://myphpscript"), HttpWebRequest)
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.ContentLength = byteData.Length
Dim postReqStream As Stream = postReq.GetRequestStream()
postReqStream.Write(byteData, 0, byteData.Length)
postReqStream.Close()
End Sub
Where "myphpscript" is acutally the full URL to the PHP script. Basically I'm trying to POST the "User" variable and the "Score" variable to the PHP script. The script I've tried is as follows:
<?php
$File = "scores.rtf";
$f = fopen($File,'a');
$name = $_POST["name"];
$score = $_POST["score"];
fwrite($f,"\n$name $score");
fclose($f);
?>
The "scores.rtf" does not change. Any help would be appreciated. Thanks ahead of time, I'm new to PHP.
Ensure that your script is receiving the POST variables.
http://php.net/manual/en/function.file-put-contents.php
You can try file_put_contents, it combines the use of fopen ,fwrite & fclose.
It could be wise to use something like isset/empty to check that there is something to write before writing.
<?php
$file = 'scores.rtf';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= print_r($_POST);
//Once confirmed remove the above line and use below
$current .= $_POST['name'] . ' ' . $_POST['score'] . "\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
Also, totally overlooked the RTF part, definitely look into what Mahan mentioned. I'd suggest the above if you have no need for that specific file type.
The "scores.rtf" does not change.
well RTF files is handled differently because its not really a pure text file it contains meta-data and tags that controls how text is displayed on the rtf file. please have a time to read to the following sources
http://www.webdev-tuts.com/generate-rtf-file-using-php.html
http://b-l-w.de/phprtf_en.php
http://paggard.com/projects/doc.generator/doc_generator_help.html
if in any case you want a normal text file you can use the code below, don't use fwrite(), please use file_put_contents()
file_put_contents("scores.txt", "\n$name $score");

python how to write data into a single file with different call

I have a python script and a PHP page on my website. I have to create a csv file and write the data onto it in following manner-
PHP processes the GET requests and calls the python script by shell_exec, passing the GET variables into it, is JSON format. The script here looks like-
...
$var_a = $_GET['a'];
$var_b = $_GET['b'];
$var_c = $_GET['c'];
$post_data = array('item' => 'get-list',
'var a' => "$var_a",
'var b' => "$var_b",
'var c' => "$var_c"
);
$json_data = json_encode($post_data);
$temp = shell_exec('python process_data.py "' . $json_data .'"');
echo $temp;
...
This script is quite straight forward, which does simply collects the GET variables and forms JSON object of it. Now this data is passed to process_data.py, which processes the data and saves the data into a csv file, the code for which is-
import sys, json, time, csv
json_data = json.dumps(sys.argv[1])
def scr(json_data):
json_data = json_data
count = 0
json_list = json_data.split(',')
for i in json_list:
count=count+1
if(count==5):
lati = json_list[0].strip('{')
longi = json_list[1]
datestmp = json_list[2]
timestmp = json_list[3]
out = open('file.csv', 'w')
out.write('%s;' % lati.split(':')[1])
out.write('\n')
out.write('%s;' % longi.split(':')[1])
out.write('\n')
out.write('%s;' % datestmp.split(':')[1])
out.write('\n')
out.write('%s;' % timestmp.split(':',1)[1])
out.write('\n')
out.close()
print 'Latitude: ',lati.split(':')[1],', Longitude: ',longi.split(':')[1],', Datestamp: ',datestmp.split(':')[1],', Time: ', timestmp.split(':',1)[1]
else:
print 'Wrong data received'
scr(json_data)
All the things are working well. The data is processed and saved. The PHP script also saves the current data into database. So PHP does two operations-
1. Saves the data into database
2. Pass the data to python script which saves the data into CSV file.
However, the GET data is coming at regular time-interval(say 1 or 2 seconds). So, the call to Python file gets regular for these intervals. It will have to open the CSV file every 1-2 seconds, write the data there. This will slow down the processing.
I want the CSV file to remain open till the data is coming, and close it when the GET request is not made for a long time. Is there any way to do so?

Categories