Some web services ask to upload or Post some files on server. In this post we will explain you How to send files via Form Post. We are using cURl to send files on server.
cURL is very powerful library, you can Get or Post data using cURL method.
PHP cURL code to Send File
First create a simple HTML form to upload a file.
Make sure that form use ‘multipart/form-data‘ enctype value. This will post data in URL encrypted form.
1 2 3 4 5 6 7 |
<form enctype="multipart/form-data" action="receiver.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" name="submit" value="Upload" /> </form> |
Now create a receiver.php file to handle this form post request.
In this file cURL send file to any web server. Check it out below code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php $target = "/home/jobsjqvi/public_html/codefixup.com/codefile/"; $target = $target.basename($_FILES['uploaded']['name']) ; $headers = array( 'Authorization: Bearer Token Value', 'Content-type: multipart/form-data' ); $url = "https://example.com/api/v1/import/uploadfile"; $csv_file = new CURLFile($target,'text/csv'); $post_data = array( "importfile" => $csv_file ); $curl = curl_init(); curl_setopt($curl, CURLOPT_VERBOSE, true); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($curl); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); ?> |
If you found that file is imported as empty or any other issue, must upload the file in target path.
Than try to upload file again using html form. This will work without any issue.