D
D
Denis Davidov2020-05-28 09:23:53
PHP
Denis Davidov, 2020-05-28 09:23:53

Convert from python to php 2 lines. But how?

Everything would be fine if it weren't so sad.
In general, in solving one painfully simple task, I came across what would be better and more convenient for me to write in php, but since I'm just starting the programming path, I don't understand how to rewrite this line in php.
With a post request, things are easier, but with a python dictionary, there are problems.

file = {'file1' : open('name.img', 'rb')}
ur = requests.post(upload_url, files=file).json()


Thank you for contributing to my becoming a little "backender" in this sad life.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nokimaro, 2020-05-28
@unkrt

<?php
$upload_url = "тут ваш upload_url";

$ch = curl_init($upload_url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file1' => '@name.img')); 
$result = curl_exec($ch);

$ur = json_decode($result);
//print_r($ur);

If you are looking for something close to Python requests, then for PHP this is the guzzle library, which in the simplest case implements a wrapper over curl and under the hood there will be approximately the same code that I gave above
docs.guzzlephp.org/en/latest/quickstart.html ?highl...

A
Artemy Karkusha, 2020-05-28
@artemiy_karkusha

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

$client = new Client();
$body = fopen('/path/to/file', 'r');
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);

An example using Guzzle.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question