Sending ByteArray through as3 to PHP - php

The BLOB field (pic) is turning out as 0 Bytes when trying to send ByteArray through as3 to PHP, so i assume the PHP script or the HTTP_RAW_POST_DATA isn't working.
I think the Flash part is working, I have set a trace() to see if the bitmapdata is coming through and it seems it is, so I'm assuming its my php side. I'll post both parts of the code in hope someone here can fix it for me. Thanks.
AS3
private function export():void
{
var bmd:BitmapData = new BitmapData(600, 290);
bmd.draw(board);
var ba:ByteArray = PNGEncoder.encode(bmd);
trace(ba);
var _request:URLRequest = new URLRequest ("http://site.com/readimage.php");
var loader: URLLoader = new URLLoader();
_request.contentType = "application/octet-stream";
_request.method = URLRequestMethod.POST;
_request.data = ba;
loader.load(_request);
}
PHP
<?php
$username = "images";
$password = "password";
$host = "localhost";
$database = "images";
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db ($database);
$query ="INSERT INTO main (pic) VALUES ('".$GLOBALS["HTTP_RAW_POST_DATA"]."')" or die(mysql_error());
$results = mysql_query($query, $link);
?>

$blob = file_get_contents('php://input');
This should work for you. This accesses PHP's raw input stream. It's more likely to work in some cases, apparently:
php://input allows you to read raw data from the request body. In case of POST requests, it preferrable to $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data.
You'll also want to ensure that you properly escape this data when placing it in the database:
$query = "INSERT INTO main (pic) VALUES ('" . mysql_real_escape_string($blob) . "')";
(It is also possible that $HTTP_RAW_POST_DATA's magic only works when you reference it directly instead of through the $GLOBALS array.)

Try breaking apart your whole process - if it's not working, start stripping away things before you get as far the sql insert...
First off, open up firebug or chrome/safari console and log your data being passed to your php page - then perhaps just start seeing what's being passed:
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}
If you have the console open, it should log the echo's to that.

Related

NuSOAP PHP web service and sending large string

again i am seeking for you help! I am new to NuSOAP, so please bear with me. I am trying to send multiple records, with multiple columns to my service, split this into records and writting them into my sql table.
For example, i have a batch that updates my variable like so (records are separated with ";", columns inside records are separated with "¤")
Name1¤Surname1¤Date1¤number1;Name2¤Surname2¤Date2¤number2;Name3¤Surname3¤Date3¤number3 ...
I have a simple function which accepts this variable. (1st of all i dont know if sending a string is optimal ... I read that i should be sending an xml document ...)
So if i declare a new variable inside my script and past the exact value that my program sets up, execute the script, everything works! Records are written in a table without any problem. I wrote up to 500 records. The problem is when i call my webservice ... In that case i get an error:
"SOAP Fault: error in msg parsing: XML error parsing SOAP payload on line 1: Invalid character:"
I think i am sending a to many chars in my variable ... Again i am new to NuSOAP and i am trying to figure this out based on an example i found online ...
When i was sending just text with only 1 delimeter, i was able to sent and write 500 records. The variable was setup like so:
TEST001;TEST002;TEST003; ...;TEST500
And the web service recieved the variable and wrote all 500 records to the table. Can someone please help me out or tell me the correct way of doing this?
Regards,
HEki
<?php
require 'lib/nusoap.php';
$server = new nusoap_server();
$server->configureWSDL("test"."urn:test");
$server->register(
"service",
array("variable_text"=>'xsd:string'),
array("return"=>"xsd:string")
);
function service($variable_text)
{
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "root";
$mysql_database = "service";
$today = date("Y-m-d");
$response='START';
// Connect to database server
$con = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);
if (mysqli_connect_errno()) {
echo "ERROR: " . mysqli_connect_error();
}
$token = strtok($variable_text, ";");
while ($token !== false)
{
$data = explode('¤', $token);
$data0 = $data[0];
$data1 = $data[1];
$data2 = $data[2];
$data3 = (int)$data[3];
$strSQL = "INSERT INTO test (column1,column2,column3,column4) VALUES ('".$data0."','".$data1."','".$data2."', '".$data3."')";
mysqli_query($con,$strSQL);
$response='NEW';
$token = strtok(";");
}
// Close the database connection
mysqli_close($con);
return $response;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>

How to secure DB configurations in php

I have a php api endpoint as below.
I need to make changes something like:
need to include all the configurations in the seperate file
validate API request using a server token to ensure to accept only genuine requests
Capture all the error logs in a seperate file, instead of showing in the browser
This is my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$data = json_decode(file_get_contents('php://input'), true);
if(!empty($data)):
header('Content-Type:text/plain');
/*MYSQL CREDENTIALS*/
$hostname = 'localhost';
$username = 'root';
$password = '';
$dbname = 'mydb';
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$arraykey=array_keys($data);
$array=$data[$arraykey[0]];
try
{
foreach($data as $array)
{
//MYSQL execute
$count = $dbh->exec("INSERT INTO gmr(version,visitorId,dwellTime,poiId,srId,zoneId,poiProximityConfidence,zoneProximityConfidence,poiPresenceConfidence,zonePresenceConfidence,normalizedTime) VALUES ('" . implode("', '", $array) . "')" ) or die(print_r($dbh->errorInfo(), true));
echo count($data);
echo 'Data Successfully inserted!!<br />';
}
//echo $data;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
endif;
?>
For point 1) I have put all the configs in a seperate file like:
<?php
define (DB_USER, "root");
define (DB_PASSWORD, "");
define (DB_DATABASE, "mydb");
define (DB_HOST, "localhost");
?>
Need clarity on the better way to include this config file in my main file.
Since im sharing the API endpoint to client, the main file should be able to read my db config files.
So which is suggested to use:
require ("configuration.php");
OR
$config = parse_ini_file('../config.ini');
Suggestion required for other 2 points
Here are suggestion for another two points:
validate API request using a server token to ensure to accept only
genuine requests
For this you can use CSRF Token to check for valid request. you can find here important use of this.
List item Capture all the error logs in a separate file, instead of showing in the browser
By default PHP log everything in server side. in Ubuntu you can find /var/log/apache/error.log
Just you need to check your apache configuration is properly set for error logs
Read here for more info : Where does PHP store the error log? (php5, apache, fastcgi, cpanel)
if you don't want to show your error in browser then you can set error_reporting(0);
Hope this is what you need !!

What's wrong with my PHP connection to MySql Database?

Here's the PHP code:
<?php
$servername = "***";
$username = "*****";
$password = "*****";
$database = "*****";
try {
$conn = new PDO('mysql:host='.$servername.';dbname='.$database, $username, $password);
console.log('yes!');
}
catch(PDOException $e) {
print "Error!:" . $e->getMessage(). "<br/>";
die();
}
if (isset($_POST['submit']))
{
//$name = $_POST['name'];
//$day = $_POST['day'];
//$acctName = $_POST['acctName'];
//$acctType = $_POST['acctType'];
//$location = $_POST['location'];
//$prospect = $_POST['prospect'];
//$notes = $_POST['notes'];
$name = 'sally sue';
$day = 'monday';
$acctName = 'Account Uno';
$acctType = 'Cold Call';
$location = 'Location';
$prospect = 'Prospect';
$notes = 'These are notes! Notey notey notes';
$order = "INSERT INTO `schedule`(`id`, `name`, `day`, `acctName`, `acctType`, `location`, `prospect`, `notes`) VALUES ('$name', '$day', '$acctName', '$acctType', '$location', '$prospect', '$notes')";
$stmt = $conn->prepare($order);
$stmt->execute();
}
?>
Here's the deal. I have an HTML form that I use jQuery to grab the variables, and AJAX to post the form to this PHP file. I feel confident that everything is fine up to the point where it gets to the PHP file.
I commented out the POST variables and hard-coded my own to make it a little simpler. I'm not getting a 500 Internal Server Error. I've ran my code through a PHP syntax validator (and fixed a billion errors haha). Obviously I'm still doing something wrong, but I cannot find it for the life of me. I'm hoping that someone here has some insight?
EDIT: Also, the username, password, database, and table name are ALL correct. I've double checked them several times. The only thing I'm not sure of is the server name, which is 'localhost' since the DB is on the same server as this web page.
EDIT 2: I've changed the MySql insert statement back to the original, which had the back ticks. I copied it straight from phpMyAdmin console on the server which it resides. It was that way originally, but I changed it due to desperation. It still is not updating my database. Any further ideas?
Thanks in advance!

Getting odd results through AJAX

Related to: Query Database through Javascript / PHP
This question is related to my above question. I fixed the PHP script to the one as mentioned in one of my answers; I attempted to use $.getJSON to no avail. So I stuck with my original method of getting a response from the server:
function getDatabaseRows()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "myDomain.com/subDirectory/getRowCounts.php", true);
xmlHttp.send(null);
}
When the alert runs, it acts as if it is a text file, and gets the entire contents of my PHP script. It doesn't run the script, it merely grabs a text-copy of it off of the server. My script (which is linked in the earlier question) is:
$rowCounts = array();
$dbhost = 'host';
$dbuser = 'host';
$dbpass = 'host';
$dbase = 'host';
$fields = array(
'MaxTID' => array('tab' => 'TransData', 'col' => 'TID'),
'MaxSID' => array('tab' => 'FullData', 'col' => 'SID'),
'MaxFID' => array('tab' => 'SalamanderData', 'col' => 'FID'),
'MaxOID' => array('tab' => 'OthersData', 'col' => 'OID')
);
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
mysql_select_db($dbase, $con) or die(mysql_error());
foreach ($fields as $id => $info) {
$sql = "SELECT MAX({$info['col']}) FROM {$info['tab']}";
$result = mysql_query($sql, $con);
if (!$result) die('Could not query:' . mysql_error());
$rowCounts[$id] = mysql_result($result, 0);
}
echo json_encode($rowCounts);
mysql_close($con);
Any clue as to why my AJAX script returns a text-copy of the PHP script on the server; and not the JSON results I am looking for?
EDIT:
Pointing my browser to the PHP script returns:
{"MaxTID":"1","MaxFID":null,"MaxSID":"3","MaxOID":"1"}
$.getJSON is jQuery, so you would need to include it in your page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$.getJSON('http://myDomain.com/subDirectory/getRowCounts.php', function(response) {
console.log(response);
});
</script>
Javascript is going to pull down whatever the http server gives it. So if the http server is not configured correctly to process your server-side script I.E. php, then you're going to get the contents of the file instead of the processed html output from running the php script. Contact your server admin to get it fixed, and verify that you are using a .php extension on your file and not .txt.
Found the solution.
The problem arrises from the fact that I was working on a network share drive ....which also happened to be living on the web server.
So whenever I went to test the script, it would fetch my file like so:
file:////mySubDomain.myDomain.com/getRowCounts.php ... Which obviously can't work, considering it isn't being served by the server.
Fixed by changing file://// to http://

Propagating Variables in PHP

My current task now is propagating variables from script to script. Basically, I have coded a capability into my website to insert 4 variables into a database via a form get method.
Now, I have input coming from a Android app that posts information to my website using JSON. After decoding the JSON array and turning them into 4 variables, how do I take those four variables and propagate them to the same script that inserts them into the database?
Here is the code for the mobile php script server side.
<?php
session_start();
$json = $_SERVER['HTTP_JSON'];
$data = json_decode($json);
$Latitude = $data->Latitude;
$Longitude = $data->Longitude;
$Bldg = $data->Bldg;
$Room = $data->Room;
echo "Data Received. Thanks bruh!";
?>
And here is the script I want to send it to.
<?php
session_start();
$bld =$_POST["bld"];
$rnum =$_POST["rnum"];
$lat = $_POST["lati"];
$lon = $_POST["longi"];
//LOG ON AND ENTER INFORMATION INTO DATABASE
require_once('logconf.php');
try {
$dbh = new PDO($driver, $user, $pass, $attr);
} catch (Exception $e) {
echo 'Exception : ' . $e->getMessage() . "\n";
die();
}
.......
first, why don't you join those two files?
second, you can use a function like this to send those data to your db script.

Categories