Propagating Variables in PHP - 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.

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);
?>

PHP script called from within AngularJS service does not work

I've made a simple PHP script to update a mysql database. When I run this script as a standalone script, it works as expected. However when I call this script from within an AngularJS Service it does not do the job.
This is my script:
<?php
include('../connection/connection.php');
$data = json_decode(file_get_contents("php://input"));
date_default_timezone_set('CET');
$cursist_id = $data->cursist_id;
$id_ggv = $data->id_ggv;
$cursist_id = intval($cursist_id+1);
$id_ggv = intval($id_ggv+1);
try {
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = " UPDATE crskrt_ggv
SET cursist_id = '$cursist_id'
WHERE id_ggv ='$id_ggv' ";
$db->exec($q);
//echo json_encode($id);
}
catch(PDOException $e)
{
echo $q . '</br>' . $e->getMessage();
}
echo "cursist_id: ". $cursist_id;
echo "id_ggv: " . $id_ggv;
echo $q;
When I check the network tab in the developers console, I can see that the right variables are returned. However, the database is not updated.
Anyone have any idea?

Passing JSON to PHP not working

I've been trying to get my python code to transfer SQL query data from client running python to web server running PHP, then input that data into a MySQL database.
The below is the python test code simulating a single row:
#!/usr/bin/python
import requests
import json
url = 'http://192.168.240.182/insert_from_json.php'
payload = {"device":"gabriel","data_type":"data","zone":1,"sample":5,"count":0,"time_stamp":"00:00"}
headers = {'content-type': 'application/json'}
response = requests.post(url, data=dict(payload=json.dumps(payload)), headers=headers)
print response
The below is the PHP script on the server side:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";
$payload_dump = $_POST['payload']
//$payload = '{"device":"gabriel","data_type":"data","zone":1,"sample":4,"count":0,"time_stamp":"00:00"}';
$payload_array = json_decode($payload_dump,true);
//get the data_payload details
$device = $payload_array['device'];
$type = $payload_array['data_type'];
$zone = $payload_array['zone'];
$sample = $payload_array['sample'];
$count = $payload_array['count'];
$time = $payload_array['time_stamp'];
$sql = "INSERT INTO data(device, data_type, zone, sample, count, time_stamp) VALUES('$device', '$type', '$zone', '$sample', '$count', '$time')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
If I comment out $payload_dump and instead use $payload and run the script the row is added correctly. But when I call the python script on the client I get a "response 200" but the record was not added. Something either my JSON string in python isn't formatted correctly or I am not passing the value correctly.
1) What is the syntax/procedure on the python code that would allow me to see what has actually been received by the PHP code. (i.e. convert the "$payload_dump" variable contents to a string and send back to the python script?
2) How do I resolve the above code?
Your first problem is using json headers which you shouldn't use since you aren't sending a raw json:
your data look like
{payload = {'key1': 'value1',
'key2': 'value2' }
}
and a raw json data should be in the form:
{'key1': 'value1',
'key2': 'value2'}
So you need to remove the headers from the request
response = requests.post(url, data=dict(payload=json.dumps(payload)))
Second you need to fix that missing semicolon
$payload_dump = $_POST['payload']
to
$payload_dump = $_POST['payload'];
Better solution
You can send the json data directly using requests
response = requests.post(url, json=payload)
then grab it in php with
$payload_array = json_decode(file_get_contents('php://input'), true);

How can I prevent this script from being freely accessed?

I am trying to create a simple PHP/MySQL message system. The following code is a section of the page that displays the messages a user has received, messages.php. The user's messages have been fetched from MySQL and stored in the variable $messages.
foreach($messages as $message) {
// formatting, printing the text, etc.
echo 'Remove';
}
And here is the file msg_del.php:
<?php
$id = $_GET['id'];
// Connect to the database
require("../info/dbinfo.php");
$db_user = constant("DB_USER");
$db_pass = constant("DB_PASS");
$db_name = constant("DB_NAME");
$db_server = constant("DB_SERVER");
try {
$conn = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("DELETE FROM messages WHERE id = " . $conn->quote($id) . ";");
$stmt->execute();
}
catch(PDOException $e) {
echo "Error connecting to database!";
exit();
}
// Redirect to messages page
header("Location: messages.php");
exit();
?>
The code is fully functional, but the problem is that anyone can type msg_del.php?id=SOMEID into a browser and delete messages. How can I secure this to where messages can only be deleted from the links on messages.php?
You're going to need some sort of token in your request to validate that this is indeed a valid request from your system.
One method would be to append a nonce to your request. This ensures that the request came from a form you control, and someone isn't using an old form to spoof a new request.
There are many nonce libraries for PHP you can choose from.
The script needs to know if the current user has permission to do the action. One simple way to do that is with the $_SESSION variable.
Something like:
session_start();
if (!isset($_SESSION['user_id']) && /*permission logic here*/) {
//display an error message
die();
}
// database query here

Sending ByteArray through as3 to 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.

Categories