Ashish Shukla
Ashish Shukla

Reputation: 3

Unable to access Flask web app from php curl

I have a Flask app, with a basic function, where I have exposed app.run() to a public ip, so that it is accessible from an external server;[ using Flask - Externally Visible Dev Server ]

@app.route('/')
def hello_world():
   return 'Hello World!'

if __name__ == '__main__':
  app.run(host = '0.0.0.0', port = 8080)

The curl request I have written in my php code is:

$signed_url = "http://my-ip-address:8080/";
$ch = curl_init($signed_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data= curl_exec($ch);
echo $data;

I can do a curl request :

curl http://my-ip-address:8080/ 

from command line. However, when the curl request is embedded within my PHP code, it gives me an error "Connection refused".

Kindly help!

Upvotes: 0

Views: 1839

Answers (3)

user3150580
user3150580

Reputation: 1

I use this code for my work and worked :)

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://localhost:5000/spmi/api/1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"teks_analysis\":\"tidak ada skor nol\"}");
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);

the key is CURLOPT_POSTFIELDS

Upvotes: 0

tanaydin
tanaydin

Reputation: 5306

try to set your port with curl options like this:

curl_setopt($ch, CURLOPT_PORT, 8080);

so your signed url will be:

$signed_url = "http://my-ip-address";

Upvotes: 0

Martin Konecny
Martin Konecny

Reputation: 59681

If the PHP code is on another server, but your command line cURL request is on the same server, then you aren't comparing apples to apples.

Two things that might be wrong:

  1. Your Flask server has a firewall that doesn't allow external connections.
  2. You are connecting using an private network IP address rather than a public IP address.

For now your PHP code looks correct, so I would narrow down the problem a little bit. Ignore that PHP code and try to connect using cURL on the command line from the same server you are running your PHP code on.

Upvotes: 1

Related Questions