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

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.

Related

Using PHP curl to run a PUT command on a zip file on PHP 5.3.8

Hi I need to perform this PUT command in PHP using curl but I'm having issues getting it to run. The file that needs to be transferred is a zip file. This is the curl command:
curl -X PUT -H "Content-Type:application/zip" --data-binary #yZip.zip http://183.262.144.266:1211/y-validation/repository/HELLO
This is the code I have so far
$ch = curl_init();
$filepath = 'yZip.zip';
curl_setopt($ch, CURLOPT_URL, 'http://183.262.144.266:1211/y-validation/repository/HELLO');
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
$fh_res = fopen($filePath, 'r');
curl_setopt($ch, CURLOPT_INFILE, $fh_res);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($filePath));
curl_setopt($ch, CURLOPT_TIMEOUT, 86400); // 1 Day Timeout
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
$curl_response = curl_exec ($ch);
print_r($curl_response);
I've taken this code from various websites but I keep getting errors and not sure what to do next any ideas?
UPDATED: Fixed the errors and I am linking the REST API successfully but the zip file is not being uploaded correctly.
UPDATED 2: Updated with code changes I've made since to try and solve problem but the zip is still not being PUT correctly. Also I'm working on PHP 5.3.8 so can't use the CurlFile class. Can anyone help with this?
UPDATED 3: Still having problems with this, trying to implement headers but thats not working either can anyone help me out?
I try this code and make work it for me...
<?php
set_time_limit(600);
$ch = curl_init();
$filePath = 'file.zip';
curl_setopt($ch, CURLOPT_URL, 'http://site/reciver_script_name/uploading/path/name');
curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_UPLOAD, 1);
$fh_res = fopen($filePath, 'r');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/zip'));
curl_setopt($ch, CURLOPT_INFILE, $fh_res);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($filePath));
curl_setopt($ch, CURLOPT_TIMEOUT, 86400); // 1 Day Timeout
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
$curl_response = curl_exec ($ch);
print_r($curl_response);
?>
And receiver side:
some path tips...
$path = $_SERVER['SCRIPT_NAME'];
if (substr($path, 0, strlen($prefix)) != $prefix) {
exit_not_found();
}
$path = substr($path, strlen($prefix));
$parts = explode('/', $path);
if (!is_array($parts) || count($parts) != 3) {
exit_not_found();
}
and main part...
if (!$error) {
$file_stream = fopen($file, 'w');
if ($file_stream === false) {
$error = 'fopen failed';
}
}
if (!$error) {
$copy_result = stream_copy_to_stream(fopen('php://input', 'r'), $file_stream);
fclose($file_stream);
if (!$copy_result) {
$error = 'stream_copy_to_stream failed';
}
}

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)

How to upload file with curl on sftp server

This code
$user = 'user';
$pass = 'password';
$filename = 'text.txt';
error_reporting(E_ALL);
ini_set('display_errors', 1);
$ch = curl_init();
$localfile = 'text.txt';
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, 'sftp://$user:$pass#myserver.com/upload/$filename');
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
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 = 'File upload error.';
}
echo $error.' '.$error_no;
gives me this error:
File upload error. 7 ( Failed to write file to disk )
My requirement is simple, I just need to upload text.txt file on live server using curl.
So for diagnosing SSH / SFTP problems I think phpseclib, a pure PHP SFTP implementation, is the best approach. Here's how:
<?php
include('Net/SFTP.php');
define('NET_SFTP_LOGGING', NET_SFTP_LOG_COMPLEX);
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
$sftp->put('text.txt', 'text.txt', NET_SFTP_LOCAL_FILE);
echo $sftp->getSFTPLog();
?>
In particular, what's useful about phpseclib is it's ability to create log files so you can see what's going on.
I think it's easier to use, too, lol, but that's up to you.
Answers to this question helped me today.
I just want to point out that your vars in 'sftp://$user:$pass#myserver.com/upload/$filename' will never get interpreted since you're using single quotes. You should either use double quotes or concatenate your vars to single quoted strings.
Maybe this link can help you,
There are some examples of different ways to upload files using CURL.
or try this
$localfile = 'sample.txt';
$user = 'user';
$password = 'pass';
$host = 'ftp.remote.com';
$ch = curl_init();
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, "sftp://{$user}:{$password}#{$host}/{$localfile}");
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
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 = 'File upload error.';
}
I also had the problem that your script, that I used as starting point, didn`t work. So I just set the CURLOPT_VERBOSE and added curl_error result to the output. This way, I realized, that curl had no ssh support enabled in my case, which I could solve by re-emerging (=re-building on other systems, I am on gentoo) with ssh support. Also the single-quotes in your code prevent correct variable substitution.
After solving those problems, and few typos, my result with your function, using my test-credentials and host, looks like this now :
Trying ...
TCP_NODELAY set
Connected to () port 22 (#0)
SSH MD5 fingerprint: 4dbea14faf74ee128d5874017332f4ef
SSH authentication methods available: publickey,keyboard-interactive
Using SSH private key file '/root/.ssh/id_rsa'
SSH public key authentication failed: Username/PublicKey combination invalid
Failure connecting to agent
Initialized keyboard interactive authentication
Authentication complete
We are completely uploaded and fine
Connection #0 to host left intact
Closing connection 0
File uploaded successfully. 0
I do not know if you ever got yours working but I used some of your code to get mine working.
I found I needed to use CURLOPT_USERPWD and take user and password out of the url. But in my search for an answer I also found someone that need to do the opposite, get rid of the CURLOPT_USERPWD, and put them in the url. That may be server dependent.
If I were at the point of your post I would add the curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);.Then when I got it working I would remove it if you feel an absolute need for the finger print.
The last 4 curl_setopt's are only for trouble shooting.
This code has been tested on two different SFTP servers.
Once is a GoDaddy VPS, CentOS 7 box, the other a GoAnywhere server.
$host = 'xx.xxx.xxx.xxx/server/public_html';
$username = 'username';
$password = 'password';
$localfile = "/home/server/public_html/xxx/resultTest.txt";
$fp = fopen($localfile, 'r');
$url = "sftp://#$host";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT,2);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($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);
?>

curl_exec succeeds but the output file is empty

I wrote the PHP function below to download files and it works as expected.
However, when I try to download this file:
$url = 'http://javadl.sun.com/webapps/download/GetFile/1.7.0_02-b13/windows-i586/jre-7u2-windows-i586-iftw.exe';
download($url);
... no content is written to the file. And I can't figure out why. The file is created, the call to curl_exec returns true, but the output file remains empty. The file can be downloaded in the browser just fine and the function successfully downloads other files. It's just this file (host?) that I'm having problem with.
Any help is appreciated.
function download($url)
{
$outdir = 'C:/web/www/download/';
// open file for writing in binary mode
if (!file_exists($outdir)) {
if (!mkdir($outdir)) {
echo "Could not create download directory: $outdir.\n";
return false;
}
}
$outfile = $outdir . basename($url);
$fp = fopen($outfile, 'wb');
if ($fp == false) {
echo "Could not open file: $outfile.\n";
return false;
}
// create a new cURL resource
$ch = curl_init();
// The URL to fetch
curl_setopt($ch, CURLOPT_URL, $url);
// The file that the transfer should be written to
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, false);
$header = array(
'Connection: keep-alive',
'User-Agent: Mozilla/5.0',
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// downloading...
$downloaded = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
fclose($fp);
if (!$downloaded) {
echo "Download failed: $error\n";
return false;
} else {
echo "File successfully downloaded\n";
return $outfile;
}
}
That url redirects to another. You need to set CURLOPT_FOLLOWLOCATION to 1 for that to work.
Try Adding;
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
//then after curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
Check some sample: http://www.php.net/manual/en/function.curl-exec.php#84774

Categories