php - need help converting a python command to php code - php

I'm using the python hashlib to get a condensed md5 value using the following command, can someone help me out with a compatible function?
hashlib.md5('my string').hexdigest()

$string = 'my string'
$encoded_string = md5($string);

echo md5('apple');
// => 1f3870be274f6c49b3e31a0c6728957f
produces the same result as
require 'digest/md5';
print Digest::MD5.hexdigest('apple');
# => 1f3870be274f6c49b3e31a0c6728957f

Related

how to get return value from python in php? it doesn't work

please help me... I have no idea.
This is part of my php code.
$result;
$resultD;
$arg= $ord." ".$time2_int;
$result=shell_exec('python3 decemberlist.py '.$arg);
$resultD=json_decode($result,true);
echo $resultD['song'];
And This is part of my python code.
import sys
import json
msg=''
def songName(a, b):
global msg
//
return msg
ret=songName(sys.argv[1], sys.argv[2])
rett={'song':ret}
print(rett)
print(json.dumps(rett, ensure_ascii=False))
php code print nothing. How can I solve this problem?
from here, shell_exec is disabled when PHP is running in safe mode.
but you can try this,
<?php
$result;
$resultD;
$arg= $ord." ".$time2_int;
$command = escapeshellcmd('python3 path/to/python_file/decemberlist.py '.$arg);
$result= shell_exec($command);
$resultD=json_decode($result,true);
echo $resultD['song'];
?>

PHP password_verify() vs Python bcrypt.hashpw()

So, right to it.
I have setup a [simple] PHP REST API where I am receiving a hashed password via the X-API-KEY header key. This works great when interfacing with another PHP script and the phrase is hashed via PHP's password_hash() method. However, when i try to interface with the API via Python and the Requests library, the key is rejected. Here are some samples:
PHP:
<?php
$usrid = '123456';
$dt = new DateTime();
$secret = "secret{$usrid}{$dt->format('Ymd')}";
$hashed = password_hash($secret, PASSWORD_BCRYPT);
echo $secret."\n";
echo $hashed."\n";
echo(phpversion());
?>
Python:
#!/usr/bin/python
import bcrypt, datetime, sys
usrid = '123456' # user id
t = datetime.datetime.now().strftime('%Y%m%d')
secret = "secret{usrid}{t}".format(usrid=usrid,t=t)
hashed = bcrypt.hashpw(secret, bcrypt.gensalt())
print secret
print hashed
print '%d.%d.%d' % (sys.version_info[:3])
The output of each of these is as follows:
PHP:
secret12345620161116
$2y$10$/WUBS2RkTlfcgPxvmqYRI.EkBD/CPgnpE9rYvOqweERgSwFeENUDO
5.6.24
Python:
secret12345620161116
$2b$11$9v/l6KglHiNgOybw1Y8jWeCFHiAfv.cguO1Qmc7Noe4azSluoBeHO
2.7.11
Now, obviously they are different, that is the point, but when you pass the Python output to the PHP password_verify() function, it returns False. The PHP output verifies just fine.
There has to be something I'm missing here but, for the life of me, I cant find it. I have tried using different salt options with no success. What am I missing? Are the two just not compatible? That seems silly, if it's true.
Thank you in advanced, you intelligent internet peoples.
UPDATE
[I have updated the scripts with the following 2 lines for the tests]
PHP: $hashed = password_hash($secret, PASSWORD_BCRYPT, ['cost'=>11]);
Python: hashed = bcrypt.hashpw(secret, bcrypt.gensalt(11))
And I have used this [PHP] to verify the above:
<?php
$secret = 'secret12345620161116';
$php = '$2y$11$rMqK7PhWtYd3E6yqqor0K.p2XEOJqbxJSrknLLWfhqZKsbYRa1YRa'; // output from php script
$python = '$2b$11$yWzCNB4dfIIVH2FLWWEQ/efSmN/KlVmLq.MGJ54plgedE1OSQgvPu'; // putput from python script
$php_needs_rehash = password_needs_rehash($php, PASSWORD_BCRYPT);
$python_needs_rehash = password_needs_rehash($python, PASSWORD_BCRYPT);
echo 'php_needs_rehash: '.$php_needs_rehash."\n";
echo 'python_needs_rehash: '.$python_needs_rehash."\n";
echo "\n";
echo "php_info:\n";
print_r(password_get_info($php));
echo "\n";
echo "python_info:\n";
print_r(password_get_info($python));
echo "\n";
echo "php_verified: ".password_verify($secret, $php)."\n";
echo "python_verified: ".password_verify($secret, $python)."\n";
echo "\n";
?>
With the following output:
php_needs_rehash: 1
python_needs_rehash: 1
php_info:
Array
(
[algo] => 1
[algoName] => bcrypt
[options] => Array
(
[cost] => 11
)
)
python_info:
Array
(
[algo] => 0
[algoName] => unknown
[options] => Array
(
)
)
php_verified: 1
python_verified: 1
So, now I'm really confused as the server still doesn't recognize my python hashed key, if I don't replace the "$2b" with "$2y" as suggested by richardhsu in the comments, that is.
Technically they are both different versions of bcrypt or crypt-blowfish
in php the prefix is $2y$10$
in python the prefix is $2b$11$
This means the cost factors are slightly different 10 vs 11 respectively
in your update you have fixed the cost factors to both be 11
The other part of the prefix indicates php is using the CRYPT_BLOWFISH hashing where python is using bcrypt which is based on the Blowfish cipher.
Because of those differences the 2 passwords are not interchangeable.
I found passlib and works perfectly
you need install
pip install passlib
pip install bcrypt
a sample code
from passlib.hash import bcrypt
php_hashed='$2y$10$/WUBS2RkTlfcgPxvmqYRI.EkBD/CPgnpE9rYvOqweERgSwFeENUDO'
plain_secret='secret12345620161116'
bcrypt.verify(plain_secret,php_hashed)
#output True

Calling Python script from PHP does not pan out

I am trying to extract major keywords from a text or sentence using python. I am using python's RAKE module. The following python code works well in the console. But, when I am trying to call the python script from PHP, the script does not parse any new text or sentence which I stored in a php variable, and instead outputs the old text/sentence even though I commented out it within the python script and replaces it with sys.argv[1] argument. In various ways, within PHP I tried to solve this problem using PHP's exec and passthru commands without any luck and so I finally decided to post my problem here.
PHP script
$var1 = 'The extra sleep will help your body wash out stress hormones.';
Technique(1)
$output = exec("python rake_tutorial.py .$var1");
Technique(2)
$output = exec('python rake_tutorial.py ' .$var1, $result);
Technique(3)
$command = 'python rake_tutorial.py ' . $var1;
$output = passthru($command);
Technique(4)
$output = exec("python rake_tutorial.py $var1", $result);
echo '<pre>' . print_r($result, true);
Here is my Python code
__author__ = 'a_medelyan'
import rake
import operator
import sys
# EXAMPLE ONE - SIMPLE
stoppath = "SmartStoplist.txt"
# EXAMPLE TWO - BEHIND THE SCENES (from https://github.com/aneesha/RAKE/rake.py)
# 1. initialize RAKE by providing a path to a stopwords file
rake_object = rake.Rake(stoppath)
# text = "What you use depends on your baby's age and physical development."
# 1. Split text into sentences
sentenceList = rake.split_sentences(text)
# generate candidate keywords
stopwordpattern = rake.build_stop_word_regex(stoppath)
phraseList = rake.generate_candidate_keywords(sentenceList, stopwordpattern)
print "Phrases:", phraseList
# calculate individual word scores
wordscores = rake.calculate_word_scores(phraseList)
# generate candidate keyword scores
keywordcandidates = rake.generate_candidate_keyword_scores(phraseList, wordscores)
for candidate in keywordcandidates.keys():
print "Candidate: ", candidate, ", score: ", keywordcandidates.get(candidate)
# sort candidates by score to determine top-scoring keywords
sortedKeywords = sorted(keywordcandidates.iteritems(), key=operator.itemgetter(1), reverse=True)
totalKeywords = len(sortedKeywords)
# for example, you could just take the top third as the final keywords
for keyword in sortedKeywords[0:(totalKeywords / 3)]:
print "Keyword: ", keyword[0], ", score: ", keyword[1]
print rake_object.run(sys.argv[1])
sys.stdout.flush()
# print rake_object.run(text)
Looks like your exec command is going wrong.Try the following command:
$var1 = 'The extra sleep will help your body wash out stress hormones.';
$output = exec("python rake.py '".$var1."'");
Hope this helps!
Just thought I'd mention that there is a RAKE implementation in php https://github.com/artofzen/RAKE-PHP

php extension in-out parameter

I'm writing a php extension using c++. The c++ function signature is:
bool validateAndNormalizeStr (string& str)
Here 'str' is a in-out parameter. It's value would be updated in the function.
I hope the php function has the same signature. Here is a use case:
$str = " zh-hans-cn";
$ret = validateAndNormalizeStr($str);
if($ret)
{
echo $str;
}
I hope the output is: "zh-Hans-CN".
The problem is I haven't found any document about in-out parameter handling in writing php extension. Help!!!
Thanks

json_decode returns NULL after webservice call [duplicate]

This question already has answers here:
PHP json_decode() returns NULL with seemingly valid JSON?
(29 answers)
Closed 4 months ago.
There is a strange behaviour with json_encode and json_decode and I can't find a solution:
My php application calls a php web service. The webservice returns json that looks like this:
var_dump($foo):
string(62) "{"action":"set","user":"123123123123","status":"OK"}"
now I like to decode the json in my application:
$data = json_decode($foo, true)
but it returns NULL:
var_dump($data):
NULL
I use php5.
The Content-Type of the response from the webservice: "text/html; charset=utf-8" (also tried to use "application/json; charset=utf-8")
What could be the reason?
Well, i had a similar issue and the problems was the PHP magic quotes in the server... here is my solution:
if(get_magic_quotes_gpc()){
$param = stripslashes($_POST['param']);
}else{
$param = $_POST['param'];
}
$param = json_decode($param,true);
EDIT:
Just did some quick inspection of the string provided by the OP. The small "character" in front of the curly brace is a UTF-8 B(yte) O(rder) M(ark) 0xEF 0xBB 0xBF. I don't know why this byte sequence is displayed as  here.
Essentially the system you aquire the data from sends it encoded in UTF-8 with a BOM preceding the data. You should remove the first three bytes from the string before you throw it into json_decode() (a substr($string, 3) will do).
string(62) "{"action":"set","user":"123123123123","status":"OK"}"
^
|
This is the UTF-8 BOM
As Kuroki Kaze discovered, this character surely is the reason why json_decode fails. The string in its given form is not correctly a JSON formated structure (see RFC 4627)
Print the last json error when debugging.
json_decode( $so, true, 9 );
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
Also use the json.stringify() function to double check your JSON syntax.
None of the solutions above worked for me, but html_entity_decode($json_string) did the trick
Try this
$foo = utf8_encode($foo);
$data = json_decode($foo, true);
make sure that if you sent the data by POST / GET, the server has not escape the quotes
$my_array = json_decode(str_replace ('\"','"', $json_string), true);
"{"action":"set","user":"123123123123","status":"OK"}"
This little apostrophe in the beginning - what is it? First symbol after the doublequote.
I had the similar problem in a live site. In my local site it was working fine. For fixing the same I Just have added the below code
json_decode(stripslashes($_GET['arr']));
I just put this
$result = mb_convert_encoding($result,'UTF-8','UTF-8');
$result = json_decode($result);
and it's working
Yesterday I spent 2 hours on checking and fixing that error finally I found that in JSON string that I wanted to decode were '\' slashes. So the logical thing to do is to use stripslashes function or something similiar to different PL.
Of course the best way is sill to print this var out and see what it becomes after json_decode, if it is null you can also use json_last_error() function to determine the error it will return integer but here are those int described:
0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8
In my case I got output of json_last_error() as number 4 so it is JSON_ERROR_SYNTAX. Then I went and take a look into the string it self which I wanted to convert and it had in last line:
'\'title\' error ...'
After that is really just an easy fix.
$json = json_decode(stripslashes($response));
if (json_last_error() == 0) { // you've got an object in $json}
I had such problem with storage json-string in MySQL.
Don't really know why, but using htmlspecialchars_decode berofe json_decode resolved problem.
Non of these solutions worked for me.
What DID eventually work was checking the string encoding by saving it to a local file and opening with Notepad++.
I found out it was 'UTF-16', so I was able to convert it this way:
$str = mb_convert_encoding($str,'UTF-8','UTF-16');
Maybe you use thing as $ ${: these chars should be quoted.
I was having this problem, when I was calling a soap method to obtain my data, and then return a json string, when I tried to do json_decode I just keep getting null.
Since I was using nusoap to do the soap call I tried to just return json string and now I could do a json_decode, since I really neaded to get my data with a SOAP call, what I did was add ob_start() before include nusoap, id did my call genereate json string, and then before returning my json string I did ob_end_clean(), and GOT MY PROBLEM FIXED :)
EXAMPLE
//HRT - SIGNED
//20130116
//verifica se um num assoc deco é valido
ob_start();
require('/nusoap.php');
$aResponse['SimpleIsMemberResult']['IsMember'] = FALSE;
if(!empty($iNumAssociadoTmp))
{
try
{
$client = new soapclientNusoap(PartnerService.svc?wsdl',
array(
// OPTS
'trace' => 0,
'exceptions' => false,
'cache_wsdl' => WSDL_CACHE_NONE
)
);
//MENSAGEM A ENVIAR
$sMensagem1 = '
<SimpleIsMember>
<request>
<CheckDigit>'.$iCheckDigitAssociado.'</CheckDigit>
<Country>Portugal</Country>
<MemberNumber">'.$iNumAssociadoDeco.'</MemberNumber>
</request>
</SimpleIsMember>';
$aResponse = $client->call('SimpleIsMember',$sMensagem1);
$aData = array('dados'=>$aResponse->xpto, 'success'=>$aResponse->example);
}
}
ob_end_clean();
return json_encode($aData);
I don't know Why?
But this work:
$out = curl_exec($curl);
$out = utf8_encode($out);
$out = str_replace("?", "", $out);
if (substr($out,1,1)!='{'){
$out = substr($out,3);
}
$arResult["questions"] = json_decode($out,true);
without utf8_encode() - Don't work
Check the encoding of your file. I was using netbeans and had to use iso windows 1252 encoding for an old project and netbeans was using this encoding since then for every new file. json_decode will then return NULL. Saving the file again with UTF-8 encoding solved the problem for me.
In Notepad++, select Encoding (from the top menu) and then ensure that "Encode in UTF-8" is selected.
This will display any characters that shouldn't be in your json that would cause json_decode to fail.
Try using json_encode on the string prior to using json_decode... idk if will work for you but it did for me... I'm using laravel 4 ajaxing through a route param.
$username = "{username: john}";
public function getAjaxSearchName($username)
{
$username = json_encode($username);
die(var_dump(json_decode($username, true)));
}
You should try out json_last_error_msg(). It will give you the error message and tell you what is wrong. It was introduced in PHP 5.5.
$foo = "{"action":"set","user":"123123123123","status":"OK"}";
$data = json_decode($foo, true);
if($data == null) {
throw new Exception('Decoding JSON failed with the following message: '
. json_last_error_msg());
}
// ... JSON decode was good => Let's use the data
Before applying PHP related solutions, validate your JSON format. That may be the problem. Try below online JSON format validator. If your JSON format is invalid, correct it first, because PHP doesn't decode invalid JSON strings.
https://jsonformatter.org/
Laravel specific answer:
I got the same issue in Laravel. And this did the trick for me
$result = json_decode($result->getContent(), true);
In my case, when I was printing to the screen, json was fine and I copied and decode with json_deocode() function. It was working fine. But, when I was trying to put jsonString directly in the function, it was returning null because quotes were coming like these ". So I used htmlspecialchars_decode() function and now it is working fine.
I am new here, so if I am making any mistakes in writing answer then sorry for that. I hope it'll help somebody.
Sometimes the problem is generated when the content is compressed, so adding the Accept-Encoding: identity header can solve the problem without having to wrangle with the response.
$opts = array(
'http' =>
array(
'header' =>
array(
'Accept-Encoding: identity',
),
),
);
$context = stream_context_create($opts);
$contents = file_get_contents('URL', false, $context);
i had a similar problem, got it to work after adding '' (single quotes) around the json_encode string. Following from my js file:
var myJsVar = <?php echo json_encode($var); ?> ; -------> NOT WORKING
var myJsVar = '<?php echo json_encode($var); ?>' ; -------> WORKING
just thought of posting it in case someone stumbles upon this post like me :)

Categories