No PUT post data being received - php

I am sending out a PUT request to my site via PHP using cURL:
$data = array("a" => 'hello');
$ch = curl_init('http://localhost/linetime/user/1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
var_dump($response);
I am then listening for this PUT request, but receiving no data with the request. Please can you tell me where I am going wrong?
$putData = '';
$fp = fopen('php://input', 'r');
while (!feof($fp)) {
$s = fread($fp, 64);
$putData .= $s;
}
fclose($fp);
echo $putData;
exit;

make sure to specify a content-length header and set post fields as a string
$data = array("a" => 'hello');
$fields = http_build_query($data)
$ch = curl_init('http://localhost/linetime/user/1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
//important
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);

Use an HTTP client class to help send the requests. There are several available, but I have created one (https://github.com/broshizzledizzle/Http-Client) that I can give you help with.
Making a PUT request:
<?php
require_once 'Http/Client.php';
require_once 'Http/Method.php';
require_once 'Http/PUT.php';
require_once 'Http/Request.php';
require_once 'Http/Response.php';
require_once 'Http/Uri.php';
use Http\Request;
use Http\Response;
header('Content-type:text/plain');
$client = new Http\Client();
//GET request
echo $client->send(
Request::create()
->setMethod(new Http\PUT())
->setUri(new Http\Uri('http://localhost/linetime/user/1'))
->setParameter('a', 'hello')
)->getBody();
?>
Processing a PUT request:
//simply print out what was sent:
switch($_SERVER['REQUEST_METHOD']) {
case 'PUT':
echo file_get_contents('php://input');
break;
}
Note that I have an autoloader on my projects that will load all those includes for me, but you may want to consider making a file that will include everything if you don't want to go down that route.
Library-less:
//initialization code goes here
$requestBody = http_build_query(
array('a'=> 'hello'),
'',
'&'
);
$fh = fopen('php://memory', 'rw');
fwrite($fh, $requestBody);
rewind($fh);
curl_setopt($this->curl, CURLOPT_INFILE, $fh);
curl_setopt($this->curl, CURLOPT_INFILESIZE, strlen($requestBody));
curl_setopt($this->curl, CURLOPT_PUT, true);
//send request here
fclose($fh);
Note that you use a stream to send the data.

Related

PHP POST API no file received

Our team is working on developing a web application for accessing a 3D printer remotely in PHP. We tried implementing the POST print_job part using the multipart/form-data but it doesn't work, which shows no file received. This API would check id and key. Here is the code. Any help is appreciated!
It's running on Apache 2.4.39, PHP 7.3.5, XAMPP Control Panel 3.2.2.
The details are:
<?php
function callAPI($method, $url, $data){
$curl = curl_init();
switch ($method){
case "POST":
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
$username = "";
$password = "";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// EXECUTE:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
return $result;
}
?>
<?php
include('api.php');
$_SESSION['ip'] = "";
$_SESSION['url'] = "http://".$_SESSION['ip']."/api/v1";
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
$filedata = $_FILES["file"]["tmp_name"];
echo $target_file;
$data_array = array(
"jobname" => "file",
"file" => "new \CURLFile(realpath($filedata))"
);
$_SESSION['size'] = $_FILES['file']['size'];
//$make_call = callAPI('POST', $_SESSION['url']."/print_job", $data_array);
$response = callAPI('POST', $_SESSION['url']."/print_job", $data_array);
$_SESSION['print'] = $response;
header('location: ../index.php');
?>
Ps: If I want to upload the file which was got from front-end to the remote API, I may have to store it locally. Then I tried it as the following code. It works.
file_put_contents("E:/xyz/test.gcode",file_get_contents("../uploads/".$_FILES["file"]["name"]));
$filedata='E:/xyz/test.gcode';
if(!is_readable(realpath($filedata))){throw new \RuntimeException("upload file not readable!");}
$data_array = array(
'jobname' => 'file',
'file' => new \CURLFile($filedata)
);
first off, don't set the Content-Type:multipart/form-data header manually because you'll corrupt the boundary if you do. the full header looks something like:
Content-Type: multipart/form-data; boundary=------------------------777d48028c332f50
so remove this:
$headers = array("Content-Type:multipart/form-data");
and let curl set it for you. (curl will automatically set that header, with the correct boundary, when setting CURLOPT_POSTFIELDS to array.)
second, you're not sending an actual file here, you're just sending the literal string
new \CURLFile(realpath($filedata))
.. if you want to send the file pointed to by $filedata , do
$data_array = array(
"jobname" => "test",
"file" => new \CURLFile(realpath($filedata))
);
instead.

How to upload file into target directory with curl?

There is a file "/home/test.mp4" in my local machine,
I want to upload it into /var/www/ok.mp4 (the name changed when uploaded it). All the source file and target file are in the local machine.
How to fix my partial code ,to add something or to change something ?
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_exec($ch);
?>
Think to Ram Sharma, the code was changed as the following:
<?php
$request = curl_init('http://127.0.0.1/');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'file' => '#' . realpath('/home/test.mp4')
));
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
// close the session
curl_close($request);
?>
An error message occur:
It works!
This is the default web page for this server.
The web server software is running but no content has been added, yet.
I have test with ftp_put,code1 works fine.
code1:
<?php
set_time_limit(0);
$host = 'xxxx';
$usr = 'yyyy';
$pwd = 'zzzz';
$src = 'd:/upload.sql';
$ftp_path = '/public_html/';
$des = 'upload_ftp_put.sql';
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
$upload = ftp_put($conn_id, $ftp_path.$des, $src, FTP_ASCII);
print($upload);
?>
The file d:/upload.sql in my local pc can be uploaded into my_ftp_ip/public_html/upload_ftp_put.sql with code1.
Now i rewite it with curl into code2.
code2:
<?php
set_time_limit(0);
$ch = curl_init();
$host = 'xxxx';
$usr = 'yyyy';
$pwd = 'zzzz';
$src = 'd:/upload.sql';
$ftp_path = '/public_html';
$dest = 'upload_curl.sql';
$fp = fopen($src, 'r');
curl_setopt($ch, CURLOPT_URL, 'ftp://user:pwd#host/'.$ftp_path .'/'. $dest);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($src));
curl_exec ($ch);
$error_no = curl_errno($ch);
print($error_no);
curl_close ($ch);
?>
The error info output is 6 .Why can't upload my local file into the ftp with curl?How to fix it?
Use copy():
copy('/home/test.mp4', '/var/www/ok.mp4');
It does not make sense to run the file through the network stack (which is what cURL does), on any protocol (HTTP, FTP, …), when the manipulation can be done locally, through the file system. Using network is more complicated and error-prone.
It is a low level error.
curl_setopt($ch, CURLOPT_URL, "ftp://$usr:$pwd#$host$ftp_path/$dest");
try something like this and I feel instead of server directory path it would be http url.
// initialise the curl request
$request = curl_init('http://example.com/');
// send a file
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'file' => '#' . realpath('test.txt')
));
// output the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
// close the session
curl_close($request);
This code might help you:
<?php
$rCURL = curl_init();
curl_setopt($rCURL, CURLOPT_URL, 'http://www.google.com/images/srpr/logo11w.png');
curl_setopt($rCURL, CURLOPT_HEADER, 0);
curl_setopt($rCURL, CURLOPT_RETURNTRANSFER, 1);
$aData = curl_exec($rCURL);
curl_close($rCURL);
file_put_contents('bla.jpeg', $aData);
// file_put_contents('my_folder/bla.jpeg', $aData); /*You can use this too*/
Try to specify the MIME type of the file sent like this
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'file' => '#' . realpath('/home/test.mp4') . ';type=video/mp4'
));
The code you posted is for the client side. If you want to upload a file using HTTP, you HTTP server must be able to handle this upload request and save the file where you want. The “error message” is probably the server’s default web page.
Sample server-side code in PHP, for your reference:
<?php
if ($_FILES) {
$filename = $_FILES['file']['name'];
$tmpname = $_FILES['file']['tmp_name'];
if (move_uploaded_file($tmpname,'/var/www/ok.mp4')) {
print_r('ok');
} else {
print_r('failure');
}
}
curl -X POST -F "image=#test.mp4" http://example.com/
You will also need a page that can process this request (POST)

PHP upload and send file with cURL

I'm attempting to upload a file to a WordPress installation and then send it, along with other data from other form fields, to Lever's API.
I can send data to the endpoint just fine, but not so much with the file uploading. The following does in fact upload to wp-content/uploads, but I think the problem lies either on the next line move_uploaded_file or where I'm passing it in the $data array.
<form enctype="multipart/form-data" method="post" action="<?php echo get_template_directory_uri(); ?>/jobForm.php">
<input type="file" name="resume">
<button type="submit">Submit</button>
</form>
<?php
// URL
$url = "https://api.lever.co/v0/postings/XXXX/XXXXXX";
$name = $_POST["name"];
$email = $_POST["email"];
$urls = $_POST["urls"];
$target = "/www/wp-content/uploads/" . basename($_FILES["resume"]["name"]);
move_uploaded_file($_FILES["resume"]["tmp_name"], $target);
// data
$data = array(
"name" => $name,
"email" => $email,
"urls" => $urls,
"resume" => #$_FILES["resume"]
);
// initiate curl instance, set options, and post
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); // url
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // full data to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return results as a string instead of outputting directly
echo $data["resume"];
// $output
$output = curl_exec($ch);
var_dump($output);
// close curl resource to free up system resources
curl_close($ch);
?>
I tried using the $target variable for the "resume" $data value, but that didn't seem to work either. As you can probably tell, I'm not exactly sure where this is going wrong (I'm a front-end developer out of my element :D).
Echoing $data["resume"] gives an Array, while echoing $target gives the location + name of the file, as expected. I guess I'm unsure what I need to be passing through in the $data array...Any ideas what I'm doing wrong here? If it helps, I get no error from Lever when submitting. In fact, it returns a 200 OK message and posts just fine, just without a resume field!
You can do that like this
$localFile = $_FILES[$fileKey]['tmp_name'];
$fp = fopen($localFile, 'r');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'someurl' . $strFileName); //$strFileName is obvious
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 86400);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'CURL_callback');
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localFile));
curl_exec ($ch);
if (curl_errno($ch)) {
$msg = curl_error($ch);
}
else {
$msg = 'File uploaded successfully.';
}
curl_close ($ch);
$return = array('msg' => $msg);
echo json_encode($return);

Symfony 1.4.2 no content in PHP cURL PUT request

Using PHP cURL and Symfony 1.4.2
I'm trying to do a PUT request including data (JSON) to modify an object in my REST web services, but can't catch the data on the server side.
It seems that the content is attached successfully when checking at my logs:
PUT to http://localhost:8080/apiapp_test.php/v1/reports/498 with post body content=%7B%22report%22%3A%7B%22title%22%3A%22The+title+has+been+updated%22%7D%7D
I attached the data like this:
$curl_opts = array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => http_build_query(array('content' => $post_data)),
);
And wanted to get the data using something like this
$payload = $request->getPostParameter('content');
It is not working and I've tried many ways to get this data in my actions file.
I've tried the following solutions:
parse_str(file_get_contents("php://input"), $post_vars);
$payload = $post_vars['content'];
// or
$data = $request->getContent(); // $request => sfWebRequest
$payload = $data['content'];
// or
$payload = $request->getPostParameter('content');
// then I'd like to do that
$json_array = json_decode($payload, true);
I just don't know how to get this data in my actions and it's frustrating, I've read many topics here about it but none is working for me.
Additional informations:
I have these setup for my cURL request:
curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, $http_method);
if ($http_method === sfRequest::PUT) {
curl_setopt($curl_request, CURLOPT_PUT, true);
$content_length = array_key_exists(CURLOPT_POSTFIELDS, $curl_options) ? strlen($curl_options[CURLOPT_POSTFIELDS]) : 0;
$curl_options[CURLOPT_HTTPHEADER][] = 'Content-Length: ' . $content_length;
}
curl_setopt($curl_request, CURLOPT_URL, $url);
curl_setopt($curl_request, CURLOPT_CONNECTTIMEOUT, 4);
curl_setopt($curl_request, CURLOPT_TIMEOUT, 4);
curl_setopt($curl_request, CURLOPT_DNS_CACHE_TIMEOUT, 0);
curl_setopt($curl_request, CURLOPT_NOSIGNAL, true);
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
In sfWebRequest.php, I've seen this:
case 'PUT':
$this->setMethod(self::PUT);
if ('application/x-www-form-urlencoded' === $this->getContentType())
{
parse_str($this->getContent(), $postParameters);
}
break;
So I tried to set the header's Content-Type to it but it doesn't do anything.
If you have any idea, please help!
According to an other question/answer, I've tested this solution and I got the correct result:
$body = 'the RAW data string I want to send';
/** use a max of 256KB of RAM before going to disk */
$fp = fopen('php://temp/maxmemory:256000', 'w');
if (!$fp) {
die('could not open temp memory data');
}
fwrite($fp, $body);
fseek($fp, 0);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_INFILE, $fp); // file pointer
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body));
$output = curl_exec($ch);
echo $output;
die();
And on the other side, you can retrieve the content using:
$content = $request->getContent();
If you var_dump it, you will retrieve:
the RAW data string I want to send

php - using curl to consume this web service

I saw this post on consuming a web service using CURL: Consume WebService with php
and I was trying to follow it, but haven't had luck. I uploaded a photo of the web service I'm trying to access. How would I formulate my request given the example below, assuming the URL was:
https://site.com/Spark/SparkService.asmx?op=InsertConsumer
I attempted this, but it just returns a blank page:
$url = 'https://xxx.com/Spark/SparkService.asmx?op=InsertConsumer?NameFirst=Joe&NameLast=Schmoe&PostalCode=55555&EmailAddress=joe#schmoe.com&SurveyQuestionId=76&SurveyQuestionResponseId=1139';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$xmlobj = simplexml_load_string($result);
print_r($xmlobj);
Really, you should probably look at the SOAP extension. If it is not available or for some reason you must use cURL, here is a basic framework:
<?php
// The URL to POST to
$url = "http://www.mysoapservice.com/";
// The value for the SOAPAction: header
$action = "My.Soap.Action";
// Get the SOAP data into a string, I am using HEREDOC syntax
// but how you do this is irrelevant, the point is just get the
// body of the request into a string
$mySOAP = <<<EOD
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope>
<!-- SOAP goes here, irrelevant so wont bother writing it out -->
</soap:Envelope>
EOD;
// The HTTP headers for the request (based on image above)
$headers = array(
'Content-Type: text/xml; charset=utf-8',
'Content-Length: '.strlen($mySOAP),
'SOAPAction: '.$action
);
// Build the cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $mySOAP);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Send the request and check the response
if (($result = curl_exec($ch)) === FALSE) {
die('cURL error: '.curl_error($ch)."<br />\n");
} else {
echo "Success!<br />\n";
}
curl_close($ch);
// Handle the response from a successful request
$xmlobj = simplexml_load_string($result);
var_dump($xmlobj);
?>
The service requires you to do a POST, and you're doing a GET (curl's default for HTTP urls) instead. Add this:
curl_setopt($ch, CURLOPT_POST);
and add some error handling:
$result = curl_exec($ch);
if ($result === false) {
die(curl_error($ch));
}
This is the best answer because using this once you need to login then
get some data from webservices(third party site data).
$tmp_fname = tempnam("/tmp", "COOKIE"); //create temporary cookie file
$post = array(
'username=abc#gmail.com',
'password=123456'
);
$post = implode('&', $post);
//login with username and password
$curl_handle = curl_init ("http://www.example.com/login");
//create cookie session
curl_setopt ($curl_handle, CURLOPT_COOKIEJAR, $tmp_fname);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $post);
$output = curl_exec ($curl_handle);
//Get events data after login
$curl_handle = curl_init ("http://www.example.com/events");
curl_setopt ($curl_handle, CURLOPT_COOKIEFILE, $tmp_fname);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($curl_handle);
//Convert json format to array
$data = json_decode($output);
echo "Output : <br> <pre>";
print_r($data);
echo "</pre>";

Categories