1

for some reasons, i have to run a php function in python.

However, i realized that it's beyond my limit.

So, i'm asking for help here.

below is the code

function munja_send($mtype, $name, $phone, $msg, $callback, $contents) {
$host = "www.sendgo.co.kr";
$id = ""; // id
$pass = ""; // password
$param = "remote_id=".$id;
$param .= "&remote_pass=".$pass;
$param .= "&remote_name=".$name;
$param .= "&remote_phone=".$phone; //cellphone number
$param .= "&remote_callback=".$callback; // my cellphone number
$param .= "&remote_msg=".$msg; // message
$param .= "&remote_contents=".$contents; // image
if ($mtype == "lms") {
$path = "/Remote/RemoteMms.html";
} else {
$path = "/Remote/RemoteSms.html";
}
$fp = @fsockopen($host,80,$errno,$errstr,30);
$return = "";
if (!$fp) {
echo $errstr."(".$errno.")";
} else {
fputs($fp, "POST ".$path." HTTP/1.1\r\n");
9
fputs($fp, "Host: ".$host."\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($param)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $param."\r\n\r\n");
while(!feof($fp)) $return .= fgets($fp,4096);
}
fclose ($fp);
$_temp_array = explode("\r\n\r\n", $return);
$_temp_array2 = explode("\r\n", $_temp_array[1]);
if (sizeof($_temp_array2) > 1) {
$return_string = $_temp_array2[1];
} else {
$return_string = $_temp_array2[0];
}
return $return_string;
}

i would be glad if anyone can show me a way.

thank you.

3 Answers3

1

according to the internet, you can use subprocess and then execute the PHP script

import subprocess
    
    # if the script don't need output.
    subprocess.call("php /path/to/your/script.php")
    
    # if you want output
    proc = subprocess.Popen("php /path/to/your/script.php", shell=True, stdout=subprocess.PIPE)
    script_response = proc.stdout.read()
Tung12354
  • 11
  • 3
1

I don't know PHP, but based on my understanding, here should be a raw line-for-line translation of the code you provided, from PHP to python. I've preserved your existing comments, and added new ones for clarification in places where I was unsure or where you might want to change.

It should be pretty straightforward to follow - the difference is mostly in syntax (e.g. + for concatenation instead of .), and in converting str to bytes and vice versa.

import socket

def munja_send(mtype, name, phone, msg, callback, contents):
    host = "www.sendgo.co.kr"
    remote_id = ""  # id  (changed the variable name, since `id` is also a builtin function)
    password = ""  # password  (`pass` is a reserved keyword in python)
    param = "remote_id=" + remote_id
    param += "&remote_pass=" + password
    param += "&remote_name=" + name
    param += "&remote_phone=" + phone  # cellphone number
    param += "&remote_callback=" + callback  # my cellphone number
    param += "&remote_msg=" + msg  # message
    param += "&remote_contents=" + contents  # image
    if mtype == "lms"
        path = "/Remote/RemoteMms.html"
    else:
        path = "/Remote/RemoteSms.html"
    socket.settimeout(30)
    # change these parameters as necessary for your desired outcome
    fp = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
    errno = fp.connect_ex((host, 80))
    if errno != 0:
        # I'm not sure where errmsg comes from in php or how to get it in python
        # errno should be the same, though, as it refers to the same system call error code
        print("Error(" + errno + ")")
    else:
        returnstr = b""
        fp.send("POST " + path + "HTTP/1.1\r\n")
        fp.send("Host: " + host + "\r\n")
        fp.send("Content-type: application/x-www-form-urlencoded\r\n")
        # for accuracy, we convert param to bytes using utf-8 encoding
        # before checking its length. Change the encoding as necessary for accuracy
        fp.send("Content-length: " + str(len(bytes(param, 'utf-8'))) + "\r\n")
        fp.send("Connection: close\r\n\r\n")
        fp.send(param + "\r\n\r\n")
        while (data := fp.recv(4096)):
            # fp.recv() should return an empty string if eof has been hit
            returnstr += data
    fp.close()
    _temp_array = returnstr.split(b'\r\n\r\n')
    _temp_array2 = _temp_array[1].split(b'\r\n')
    if len(temp_array2) > 1:
        return_string = _temp_array2[1]
    else:
        return_string = _temp_array2[0]
    # here I'm converting the raw bytes to a python string, using encoding
    # utf-8 by default. Replace with your desired encoding  if necessary
    # or just remove the `.decode()` call if you're fine with returning a
    # bytestring instead of a regular string
    return return_string.decode('utf-8')  

If possible, you should probably use subprocess to execute your php code directly, as other answers suggest, as straight-up translating code is often error-prone and has slightly different behavior (case in point, the lack of errmsg and probably different error handling in general, and maybe encoding issues in the above snippet). But if that's not possible, then hopefully this will help.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
-1

PHP code can be executed in python using libraries subprocess or php.py based on the situation. Please refer this answer for further details.