How to upload file into target directory with curl? - php

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)

Related

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);

Need a help in image upload using php

I have two server and I have an browse button in server1 (ie input=file) from server 1 i need to upload images to server2. How can I do this?
Now I have done upload image to server1 and from there I am trying to move to server2. Here is the code which I have done so far
After uploading to server 1 I have written this code
$uploadedfile = $_FILES[$fileElementName]['tmp_name'] ;
$data = array('name' => $newname, 'file' => $uploadedfile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, 'http://server.xx/upload.php');
curl_exec($ch);
curl_close($ch);
and in server2 I have created one file upload.php
in that I have written
$content = $_POST['file'];
$imageString = file_get_contents("http://server.xx/temp/".$_POST['name']);
$save = file_put_contents("/dddd/".$_POST['name'],$imageString);
I think I have done wrong in upload.php file.. I don’t have any idea to do it.. please help me.
Do on server to Server 2:
$from = ''; //Absolute path to server 1 image
$to = ''; relative path to your server 2 place.
copy($from, $to);
<?PHP
$ch = curl_init('http://server.xx/upload.php');
$ch = curl_setopt($ch, CURLOPT_POST, true);
$ch = curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => $_FILES[$fileElementName]['tmp_name'] ));
$ch = curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
$result = curl_exec($ch);
if ($result === FALSE) {
die(curl_error($ch));
}
?>

PHP cURL error The URL was not properly formatted

I am trying to do a simple cURL file upload from one server to another. The problem is I get Error #3 from the cUrl error codes: The URL was not properly formatted.
I have copied the url into my browser and logged onto the ftp site without a problem. I have also verified the proper formatting and searched the web and this site for an answer without any success.
Here's the code:
$ch = curl_init();
$localfile = '/home/httpd/vhosts/homeserver.com/httpdocs/admin.php';
echo $localfile; //This reads back to proper path to the file
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, 'ftp://username:password#199.38.215.1xx/');
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
$error_no = curl_errno($ch);
curl_close ($ch);
if ($error_no == 0) {
$error = 'File uploaded succesfully.';
} else {
$error = 'Upload error:'.$error_no ;//Error codes explained here http://curl.haxx.se/libcurl/c/libcurl-errors.html';
}
echo $error;
I have also tried this:
curl_setopt($ch, CURLOPT_URL, 'ftp://199.38.215.1xx/');
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
I still get error #3.
Any ideas?
your remote URL needs to contain the path and name of the destination file, as shown in this example
<?php
// FTP upload to a remote site Written by Daniel Stenberg
// original found at http://curl.haxx.se/libcurl/php/examples/ftpupload.html
//
// A simple PHP/CURL FTP upload to a remote site
//
$localfile = "me-and-my-dog.jpg";
$ftpserver = "ftp.mysite.com";
$ftppath = "/path/to";
$ftpuser = "myname";
$ftppass = "mypass";
$remoteurl = "ftp://${ftpuser}:${ftppasswd}#${ftpserver}${ftppath}/${localfile}";
$ch = curl_init();
$fp = fopen($localfile, "rb");
// we upload a JPEG image
curl_setopt($ch, CURLOPT_URL, $remoteurl);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
// set size of the image, which isn't _mandatory_ but helps libcurl to do
// extra error checking on the upload.
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
$error = curl_exec($ch);
// check $error here to see if it did fine or not!
curl_close($ch);
?>

Download files from Megaupload with cURL PHP

I'm writing a script to download files from Megaupload onto my server. I'm using cURL on PHP, I have the login script which downloads the cookie file:
<?php
function login($username, $password){
$mega = curl_init();
curl_setopt($mega, CURLOPT_URL, "http://www.megaupload.com/?c=login");
curl_setopt($mega, CURLOPT_POST, true);
curl_setopt($mega, CURLOPT_POSTFIELDS, "login=1&redir=1&username=$username&password=$password");
curl_setopt($mega, CURLOPT_COOKIEFILE, dirname(__FILE__) . "/megaupload_cookie.txt");
curl_setopt($mega, CURLOPT_COOKIEJAR, dirname(__FILE__) . "/megaupload_cookie.txt");
curl_exec($mega);
curl_close($mega);
}
?>
and the downloading script:
<?php
include("megaupload_login.php");
login("username", "ps");
set_time_limit(0);
$url = "http://www.megaupload.com/?d=A428CAKH";
$fp = fopen("winch.zip", "w");
$dl = curl_init($url);
curl_setopt($dl, CURLOPT_COOKIEFILE, "megaupload_cookie.txt");
curl_setopt($dl, CURLOPT_FILE, $fp);
curl_exec($dl);
curl_close($dl);
fclose($fp);
?>
The problem is, the file doesn't download. All I get is a file named winch.zip with a size of 0 bytes. I think the program is actually downloading the login page, as when run the script the browser just shows the megaupload login page but the address is localhost. Any ideas on why this might not be working?
Try Following for your download part of code:
function download_file($link) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $link);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "/cookies/megaupload.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$filecontents = download_file("http://www.megaupload.com/?d=A428CAKH");
Hope it helps

File posting using cURL into a secured folder(https://)

The problem is to upload a txt file into a secured folder(https://www.mydomain.com/myfolder/) using cURL.
I have a relevant ftp details to connect that folder. here is my code, but it does not getting connected properly...
can any one please advise what mistake i did on this code. which returns error_no:7 while uploading file
<?
if (isset($_POST['Submit'])) {
if ($_FILES['upload']['name']!="")
{
$localfile = $_FILES['upload']['tmp_name'];
$newfile = $_FILES['upload']['name'];
$ch = curl_init();
$url = 'ftp://ftp_login:password#ftp.mydomain.com/myfolder/'.$newfile;
$fp = fopen ($localfile, "r");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_FTPASCII, 1);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $newfile);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($ch);
echo curl_error($ch);
echo $error_no = curl_errno($ch);
curl_close($ch);
//echo $result;
if ($error_no == 0)
{
$error = 'File uploaded succesfully.';
}
else
{
$error = 'File upload error.';
}
}
else
{
$error = 'Please select a file.';
}
}
?>
According to this list, error code 7 is
CURLE_COULDNT_CONNECT (7)
Failed to connect() to host or proxy.
Are you sure the server is reachable? Can you try manually?
Also, I'm not really getting what you are doing here. You are establishing a ftp connection but adding POST fields. Also, nothing of this has to do with https. What exactly are you trying to do?
I don't know why you have to use cURL but PHP has its own FTP functions that will make life a bit easier.

Categories