PHP cURL error The URL was not properly formatted - php

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

Related

Download image from website that requires authentication/credentials using php

The $source is the url link of an image from a website that requires authentication/login. I was able to download the image but the downloaded image can't be opened. I knew the image is not downloaded properly as it is asking for credentials. I use CURL to download the image and now, I have no idea what's wrong with the code, what else should i add to it??
<?php
$username = $_SESSION["username"];
$password = $_SESSION["password"];
$source = 'https://example.com/sequence.png';
$fp = fopen('C:/image/'.basename($source), 'w');
$ch = curl_init($source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");// to use for connection
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 1);// content type
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_exec($ch);
fclose($fp);
?>
If your authentication is not basic, you need some library like Guzzle.
You can do the login process and then download the image

Upload image with curl put request from url

I was trying to upload image using curl put request, And was able to upload image if the image is stored in local directory. but the problem is that i have to upload image from another image url.
could anyone help me.
$localfile = "testing.jpg";
// echo filesize($localfile); die;
$url = API_URL . "pages/343/files/=".$localfile."?description=testing";
$fp = fopen ($localfile, "r");
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_USERPWD, API_USERNAME . ":" . API_PASSWORD);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
$http_result = curl_exec($ch);
$error = curl_error($ch);
$http_code = curl_getinfo($ch ,CURLINFO_HTTP_CODE);
// $jsonOutput = json_decode($http_result, true);
curl_close($ch);
fclose($fp);
i have tried to change $localfile to
$localfile = "https://someurl/someimage.png";
but it gave me following error.
Warning: curl_setopt(): cannot represent a stream of type tcp_socket/ssl as a STDIO FILE* in C:\xampp\htdocs\newPutMedia.php on line 29
Warning: filesize(): stat failed for https://help.optimizely.com/hc/en-us/article_attachments/200205465/1._Site-Wide_Addition_gmc_BEFORE.png in C:\xampp\htdocs\newPutMedia.php on line 30
Apparently this is a bug in PHP cURL. You can use the bug fix as mentioned here or you can do this :
Copy the file from URL to your local directory :
file_put_contents(__DIR_\_ . "/testing.jpg", file_get_contents($url));
Use the new file stored in your server for cURL PUT request :
$localfile = __DIR_\_ . "/testing.jpg";
Since the bug does not exist for file reading from your server, the bug won't cause errors and this would perfectly work.

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

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