How to break down tuple from Python to PHP - php

I'm using HTTP post request from Codeigniter to python and return a tuple from MySQL to python
Codeigniter controller:
$data['email'] = $this->input->post("email");
$url = 'http://domain/path';
$data = array('email' => $data['email']);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
Python code:
elif self.path=="/forgotpass":
print "forgot password module"
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
self.send_response(200)
self.send_header('Content-type','text/html')
self.send_header("Access-Control-Allow-Origin","http://domain")
self.end_headers()
#print form['email'].value
email = str(form["email"].value)
sql = "SELECT email_address, personal_id from personal_info where email_address='"+email+"'"
result = validate(sql)
print result
#print email;
self.wfile.write(result)
def validate(sql):
try:
db = MySQLdb.connect("localhost","root","password","schema" )
cnn = db.cursor()
cnn.execute(sql)
return cnn.fetchone()
cnn.close()
except MySQLdb, e:
print "Error validate function"
The display is, I think this is now a string format.
string(36) "('jerahmeel.acebuche#smsgt.com', 2L)"
In a simple Codeigniter connecting to a model.
The result of an array from mysql is:
array (column => value) etc etc..
You could display that array using foreach and $item->data;
But this result came from python which is a tuple and returning it to PHP is a different approach.
How will I break this tuple in PHP? or should I break it on python and return it to PHP?

Related

CURL-less HTTP request (returning array)

I am new in PHP and I am trying to access file of another website of mine. So on my web #1 I am trying to send a POST request like this:
<?php
$url = 'http://localhost/modul_cms/admin/api.php'; //Web #2
$data = array(
"Action" => "getNewestRecipe",
"Secret" => "61cbe6797d18a2772176b0ce73c580d95f79500d77e45ef810035bc738aef99c3e13568993f735eeb0d3c9e73b22986c57da60a0b2d6413c5dc32b764cc5897a",
"User" => "joomla localhost",
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
if($result === FALSE){
echo "Not working connection :(";
}else{
echo "HOORAY!";
var_dump($result);
}
And on my web #2 I have some kind of receiver I made. Now I need to return after selecting stuff from my database array of data. So I have code like this on my web #2:
<?php
$action = isset( $_POST["action"] ) ? $_POST["action"] : "";
$secret = isset( $_POST["secret"] ) ? $_POST["secret"] : "";
$user = isset( $_POST["user"] ) ? $_POST["user"] : "";
if(!empty($secret)){
if(!empty($user)){
switch($action){
case 'getNewestRecipe':
getNewestRecipe();
break;
case '':
error();
break;
default:
error();
break;
}
}
}
/* *************** FUNCTIONS ************* */
function getNewestRecipe(){
return array("msg" => "Here is your message!");
}
The problem is everything I get on my web #1 from the response is actually the echo I have there for knowing that the HTTP request reached something (so I've got the message "HOORAY!") but the
var_dump($response)
has empty value (not NULL or something it's literally this):
C:\Program Files (x86)\Ampps\www\joomla30\templates\protostar\index.php:214:string '' (length=0)
Thank you for any help!
On web#1 you are sending "Secret","User","Action" in upper-case, but on web#2 you are accessing $_POST['secret'] (lower-case). Because of this your code never gets to the call of getNewestRecipe() nor to your error() call, thus there is no content / a blank page, but also no error.
Also, you need to output the array your function returns in some way.
An array cannot simply be echod, so you need to serialize it. I suggest using json_encode: echo json_encode(getNewestRecipe());

Sending JSON Array via PHP (Campaign Monitor)

I have a sample JSON Array labeled sample.txt that is sent from a sweepstakes form that captures a user's name and e-mail. I'm using WooBox so the JSON Array sends information over by each entry, so there are two entries here: http://pastebin.ca/3409546
On a previous question, I was told to break the ][ so that JSON_ENCODE can figure the separate entries. I would like to capture just the name and e-mail and import the array to my e-mail database (campaign monitor).
My question is: How do I add JSON variable labels to an array? If you see my code, I have tried to use the label $email. Is this the correct form or should it be email[0] with a for loop?
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$result = $wrap->add($json(
'EmailAddress' => $email,
'Name' => $custom_3_first,
'Resubscribe' => false
));
https://github.com/campaignmonitor/createsend-php/blob/master/samples/subscriber/add.php
This should have been fairly easy: if you have a JSON string and you call json_decode($string, true) on it, you get its equivalent in a PHP variable, plain and simple. From there, you can access it like you would any PHP array, object, etc.
The problem is, you don't have a proper JSON string. You have a string that looks like JSON, but isn't valid JSON. Run it through a linter and you'll see what I mean.
PHP doesn't know what to do with your supposed JSON, so you have to resort to manual parsing, which is not a path I would recommend. Still, you were almost there.
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array('api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}

file_get_contents for insertion in database

I have a two pages in my website, one is named "new_account.php" and the other is "visitor.php". The user can choose to create a new account for themselves or just go with a visitor account.
When the user picks "visitor" I make a request to "new_account.php" to create a temporary account with a random username and password, to be deleted later when the user is done. I'm using file_get_contents for the request, since the page returns the user hash which I use to automatically login the user.
This is "visitor.php":
$url = getBaseUrl().'new-account.php';
$data = array(
'name' => $tempName,
'character-name' => $tempCharacterName,
'gender' => $tempGender,
'age' => $tempAge,
'parent-email' => $tempParentEmail,
'password' => $tempPassword,
'password-confirmation' => $tempPassword,
'temporary' => TRUE
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
if($result != "error") {
User::loginUser($result, TRUE, $conn);
User::ifUserLoggedRedirect('game.php',$conn);
}
My problem is that, while the request is successful and a new random user is inserted in the database, when User::loginUser tries to query the user data using the hash returned by file_get_contents (such as the user icon or user name) I'm getting an empty result set.
User::loginUser is this:
public static function loginUser($userHash, $temporary, $conn) {
if(User::isAnyLogged($conn))
User::logout($conn);
User::safeSessionStart();
$result = $conn->prepare('SELECT p.screen_name, pi.url, p.id FROM player as p, player_icon as pi WHERE p.user_hash=? AND pi.id = p.player_icon_id');
$result->bind_param('s',$userHash);
$result->execute();
$res = $result->get_result();
if($res->num_rows == 0) {
die("Invalid user with hash ".$userHash);
}
$user_info = $res->fetch_assoc();
$_SESSION['user'] = new User($userHash, $temporary, $user_info['screen_name'], $user_info['url'], $user_info['id']);
setcookie('userHash',$userHash);
setcookie('temporary',$temporary ? '1' : '0' );
return $_SESSION['user'];
}
And the call always dies with an invalid hash, but if I query the user from phpmyadmin using the hash the user is actually there. Going through the normal registration by accessing "new_account.php" also works.
The first thing I tried was closing and reopenning the connection after getting the result from file_get_contents but that didn't work. Using mysqli::refresh also didn't work. I tried moving the login part of the code to the "new_account.php" but apparently I also can't set the $_SESSION from a request using file_get_contents.
I also could solve this by copying the new account code to the visitor page, but I would rather keep the account creation in a single page. Is there anything else I can try?
You should use require_once to include the new-account.PHP
This way, you can use the code of the included file as if it were in the file from where you include it.

array_key_exists() expects parameter 2 to be array, string when using pushWoosh Class

I am having some trouble implementing the pushwoosh class http://astutech.github.io/PushWooshPHPLibrary/index.html. I have everything set up but i am getting an error with the array from the class.
This is the code i provied to the class:
<?php
require '../core/init.php';
//get values from the clientside
$sendID = $_POST['sendID'];
$memID = $_POST['memID'];
//get sender name
$qry = $users->userdata($memID);
$sendName = $qry['name'];
//get receiving token
$qry2 = $users->getTokenForPush($sendID);
$deviceToken = $qry2['token'];
//i have testet that $deviceToken actually returns the $deviceToken so thats not the problem
//this is the array that the php class requires.
$pushArray = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$push->createMessage($pushArray, 'now', null);
?>
And this is the actually code for the createMessage() method
public function createMessage(array $pushes, $sendDate = 'now', $link = null,
$ios_badges = 1)
{
// Get the config settings
$config = $this->config;
// Store the message data
$data = array(
'application' => $config['application'],
'username' => $config['username'],
'password' => $config['password']
);
// Loop through each push and add them to the notifications array
foreach ($pushes as $push) {
$pushData = array(
'send_date' => $sendDate,
'content' => $push['content'],
'ios_badges' => $ios_badges
);
// If a list of devices is specified, add that to the push data
if (array_key_exists('devices', $push)) {
$pushData['devices'] = $push['devices'];
}
// If a link is specified, add that to the push data
if ($link) {
$pushData['link'] = $link;
}
$data['notifications'][] = $pushData;
}
// Send the message
$response = $this->pwCall('createMessage', $data);
// Return a value
return $response;
}
}
Is there a bright mind out there that can tell me whats wrong?
If I understand, your are trying to if your are currently reading the devices sub-array. You should try this:
foreach ($pushes as $key => $push) {
...
// If a list of devices is specified, add that to the push data
if ($key == 'devices') {
$pushData['devices'] = $push['devices'];
}
You iterate over $pushes, which is array('content' => ..., 'devices' => ...). You will first have $key = content, the $key = 'devices'.
It looks like the createMessage function expects an array of messages, but you are passing in one message directly. Try this instead:
$push->createMessage(array($pushArray), 'now', null);
The class is expecting an array of arrays; you are just providing an array.
You could do something like this
//this is the array that the php class requires.
$pushArrayData = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$pushArray[] = $pushArrayData
Will you ever want to handle multiple messages? It makes a difference in how I would do it.

Python script can retrieve value from memcache, but PHP script gets empty result

i run a python script whitch cache some data
self.cache.set('test', 'my sample data', 300)
data = self.cache.get('test')
self.p(data)
this program will result in print of 'my sample data' ... everything its good, but when i try to access this key from php
$data = $this->cache->get('test');
print_r($test);
i only get empty result
so i check the server stats
$list = array();
$allSlabs = $this->cache->getExtendedStats('slabs');
$items = $this->cache->getExtendedStats('items');
foreach($allSlabs as $server => $slabs) {
foreach($slabs AS $slabId => $slabMeta) {
$cdump = $this->cache->getExtendedStats('cachedump',(int)$slabId);
foreach($cdump AS $server => $entries) {
if($entries) {
foreach($entries AS $eName => $eData) {
$list[$eName] = array(
'key' => $eName,
'server' => $server,
'slabId' => $slabId,
'detail' => $eData,
'age' => $items[$server]['items'][$slabId]['age'],
);
}
}
}
}
}
ksort($list);
print_r($list);
and this key 'test' is there ... but i cannot access it
if i cache something in php i get the result everytime, but somehow this python + php cache wont work
if someone has an idea where could be a problem plese advice ... i try everything
Could it be that the hashes don't match between PHP and Python? A solution is here: http://www.ruturaj.net/python-php-memcache-hash
Add the following to your Python script to change how hashes are calculated...
import memcache
import binascii
m = memcache.Client(['192.168.28.7:11211', '192.168.28.8:11211
', '192.168.28.9:11211'])
def php_hash(key):
return (binascii.crc32(key) >> 16) & 0x7fff
for i in range(30):
key = 'key' + str(i)
a = m.get((php_hash(key), key))
print i, a

Categories