Sending a file via PHP CURL to remote server - php

I'm trying to send a file using PHP's CURL functions.
$postdata = curl_file_create(realpath($filename), 'text/csv', $filename);
and then
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
$result = curl_exec($ch);
$cinfo = curl_getinfo($ch);
$cerror = curl_error($ch);
var_dump($result);
var_dump($cinfo);
var_dump($cerror);
curl_close($ch);
This only dumps bool(false), so I'm not getting far with the debugging. Am I POSTing the filename as a string rather than the file contents? The php script and the file to be send are in the same directory. Do I need to specify the path in a certain format?
Update:
I added curl_error($ch) and figured out that the problem is a connection timeout. When running the script from my local machine it seems to be working, at least I get a 200 OK reply. Could my webhost somehow be blocking the connection?

Related

cUrl working fine on localhost but it's not working on server and only shows blank page

When I run the below code on server it only shows the blank page and suddenly stop further execution, I also checked the cUrl on server which is installed.
Here is my code.
$ftp_server = 'ftps://'.'server/Voorraadtonen link.csv';
$ch = curl_init(str_replace(" ","%20",$ftp_server));
curl_setopt($ch, CURLOPT_URL, $ftp_server);
curl_setopt($ch, CURLOPT_USERPWD,'username'.':'.'password');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);
curl_setopt($ch, CURLOPT_FTPSSLAUTH, CURLFTPAUTH_TLS);
//curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_PORT, 990);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($ch, CURLOPT_VERBOSE,true);
$output = curl_exec($ch);
$error_no = curl_errno($ch);
echo $output; exit;
Latest update!
You have more than 1 errors in your codes,
you are using FTPS in url which requires SSL verification, and its false in
your codes.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//Dont use try! you shouldnt use
curl_setopt($ch, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);
They should be true : SSL doesnt support true so they should be like following on #dharman warn in another answer.
But turning ssl true will require another setup like cacert file
etc. lik so
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
//and include cacert.pem
curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
Download cacert file here : https://curl.haxx.se/docs/caextract.html
2.Your url is not a true url $ftp_server = 'ftps://'.'server/Voorraadtonen link.csv';, this url will get nothing, but it should return an error atleast in error_log file, as you said all errors reporting are enabled
3.Your code should look like this
$curl = curl_init();
$file = fopen("link.csv", 'w');
curl_setopt($curl, CURLOPT_URL, "ftp://ftp.site.com/link.csv");
//Make sure for correct url
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
//Make sure for correct url
curl_setopt($curl, CURLOPT_FILE, $file);
curl_setopt($curl, CURLOPT_USERPWD, "$_FTP[username]:$_FTP[password]");
//Make sure for your ftp credentials
curl_setopt($curl, CURLOPT_TIMEOUT, 20); //20 seconds will be enough
curl_exec($curl);
echo curl_errno($ch);
echo curl_error($ch);
curl_close($curl);
fclose($file);
1 more thing left headers should not be required but in case its required.
curl_setopt($curl, CURLOPT_HEADER, false); //Or
curl_setopt($curl, CURLOPT_HEADER, true);
Now it should work without any problem
NOTE : Example code is a working example you can edit it to your requirements
UPDATE : After modification you said you did in your codes (Still not showing us), finaly we get an error. once again I am asking you to add modified code into your question.
Error_no 28 cURL error 28: Connection timed out
the cURL 28 error occurs when the cURL request isn’t completed in a certain amount of time.
This happens when the cURL timeout value is set too low or when a firewall is blocking the cURL request.
Another possibility is a security module, for example the Apache mod_security module.
To fix the cURL error 28 you can contact your hosting provider.
So basicaly!
Your server is blocking. your credentials not match to required
credentails. SSL is required by server, but you are not setting it up.
Your function runing max of your Server Memory Limits settings.
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "ftp.site.com/link.csv");
//make sure your path to file is correct
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERPWD, "$_FTP[username]:$_FTP[password]");
//make sure your login credentials correct
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
//Set timeout for connection
curl_exec($curl);
echo curl_errno($ch);
echo curl_error($ch);
//Get errors
curl_close($curl);
//Importand close curl connection.

How can I download the .zip of my private github repository using cURL on php?

I want to download the latest zip version of a private github repository I'm working on, and I want to do this using a PHP script. However, my current PHP script is just returning "Not Found" - I'm guessing I have an issue with my cURL user/pass setup, but I can't figure it out. My current code is as follows:
$username='XXX';
$password='XXX';
$URL='https://github.com/[user]/[reponame]/archive/master.zip';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result=curl_exec ($ch);
file_put_contents('master.zip', $result);
curl_close ($ch);
I was able to get it to work by separating the login page and the file download page into two requests. The following code worked for me:
$username='XXX';
$password='XXX';
$URL='https://github.com/[user]/[reponame]/archive/master.zip';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://github.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result=curl_exec ($ch);
curl_close ($ch);
file_put_contents('master.zip', $result);
I know that this question is a bit older, but it's worth noting that that GitHub allows for the generation of OAuth keys that allow you to download private repos. This allows you to not keep your username and password in your code.
For future seekers, below is working sample code utilising the OAuth access token generated.
The question was for zipball functionality, however the API allows for tarball as well.
$fp = fopen('/path/to/yourfile.zip', 'w+');
$giturl = 'https://api.github.com/repos/{username}/{reponame}/zipball/master?access_token={YourTokenHere}';
$ch = curl_init($giturl);
//set file to write to
curl_setopt($ch, CURLOPT_FILE, $fp);
//the API will not allow you to download without a user agent so CURLOPT_USERAGENT is important.
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP/'.phpversion('tidy'));
//The API URL redirects so the following line is very important
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$output = curl_exec($ch);
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
}
//Get the HTTP status code.
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//Close the cURL handler.
curl_close($ch);
//Output result
if($statusCode == 200){
echo 'Downloaded Successfully';
} else{
echo "Failed downloading - Status Code: " . $statusCode;
}
In addition to your answer I would suggest using the following if you want to download larger files to save memory.
$fp = fopen ('master.zip', 'w+');
curl_setopt($ch, CURLOPT_FILE, $fp);

Upload a file on my Owncloud server with PHP

Recently I created my owncloud server and I need to be able to upload a file from a php form which transfer an file from my pc to my owncloud server. So I tried to use Curl, like this :
<?php
$url = "5.25.9.14/remote.php/webdav/plus.png";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // -X PUT
curl_setopt($ch, CURLOPT_USERPWD, "root:root"); // --user
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE); // --data-binary
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'img/plus.png' => '#'.realpath('img/plus.png')
)
);
$output = curl_exec($ch);
curl_close($ch);
?>
I have been inspire by this post and this command :
curl -X PUT "http://server.com/owncloud/remote.php/webdav/file.zip" --data-binary #"/Users/Root/Downloads/file.zip"
The command line, he's working but not my php. I succeed to upload the file but the file is corrupted and I don't know why :/. Maybe I miss the MIME type ? Is it enough to get a corrupted file ?
Do you see where I am wrong ?
Best regards, Zed13
Edit : When I make an file of my uploaded file, it's of type data and not png, strange...
I was having an issue with an upload to owncloud as well. Had the same symptoms, the command line curl works, but not the PHP curl call.
Thanks to your post I was able to get it working. Here is what works for me
// upload backup
$file_path_str = '/tmp/' . date('Ymd') . '.tar.gz';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://server/remote.php/webdav/backups/' . basename($file_path_str));
curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
curl_setopt($ch, CURLOPT_PUT, 1);
$fh_res = fopen($file_path_str, 'r');
curl_setopt($ch, CURLOPT_INFILE, $fh_res);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file_path_str));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE); // --data-binary
$curl_response_res = curl_exec ($ch);
fclose($fh_res);
The differences are:
CURLOPT_PUT instead of CURLOPT_CUSTOMREQUEST
CURLOPT_INFILE and CURLOPT_INFILESIZE instead of CURLOPT_POSTFIELDS
Thanks for your help.
//

Php curl error Url not found on this server

I am working on core php.
I am requesting a URL by curl. This is working on my development server but same thing are not working on live server.
Below is my Code:
$url = "http://www.streamatemodels.com/login.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'submitted=1&g=&sausr='.urlencode('username').'&sapwd='.urlencode('password').'');
$result = curl_exec($ch);
$error = curl_errno($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
print_r($result);
Please help me if anyone have solution.
Update
I checked this with new username and password but same things happen. Its working on my development server but not working on live and local host.
The following line:
curl_setopt($ch, CURLOPT_POSTFIELDS, 'submitted=1&g=&sausr='.urlencode('username').'&sapwd='.urlencode('password').'');
should be changed to:
curl_setopt($ch, CURLOPT_POSTFIELDS, 'submitted=1&g=&sausr='.urlencode($username).'&sapwd='.urlencode($password).'');
If it still doesn't work try to create the query-string outside of curl_setopt:
$params = 'submitted=1&g=&sausr='.urlencode($username).'&sapwd='.urlencode($password).'';
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
Another advise: it's better practice to use http_build_query($params)
UPDATE
I had the time to check the code, and it works fine on my local host (meaning: check your username/password!):

curl login, session cookie in two passes

I try to login with curl to a SSL secured website but somehow I don't get it right.
The first curl connection retrieves the login form. An SSL issue in the beginning is resolved now. The fields used for authentication and all hidden fields are identified and used for the following POST. The cookie file is defined and the jar to read from as well. The cookie file is accessible and gets updated with each login attempt. A session cookie is successfully set by curl. The HTTPHEADER is removed to stop the request from hitting the 100 Continue wall. Curl is configured to follow up and to send a referer.
However, I still cannot find where the script gets stuck. Neither Curl nor PHP issue any error messages or warnings.
Here is the shortened script:
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); // remove Expect header to avoid 100 Continue situations
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla [abbreviated]');
curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__).'/cacert.pem');
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.hq.txt'); // write cookies
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.hq.txt'); // read cookies
curl_setopt($ch, CURLOPT_COOKIESESSION, 1);
curl_setopt($ch, CURLOPT_URL, 'https://the_url.jsp');
$data = curl_exec($ch);
$error= curl_error($ch);
if(!empty($error))
echo '<p>'.$error.'</p>';
else
echo '<p>ok</p>';
Now the script reads the form, fills in the credentials and POSTs it back using the same curl_init handle:
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $options);
$data = curl_exec($ch);
$error=curl_error($ch);
But all I get back is the same form again and the same session cookie or a new one depending on the CURLOPT_COOKIESESSION setting.
When I log in manually I notice that there are two more cookies set: LtpaToken and LtpaToken2 but I never see them appearing in the request headers printed by the script.
Manually submitting the form works even without Javascript aktivated. So there cannot be some JS magic modifying the form data under the hood before submitting it.
Obviously I am missing something here. Any ideas where I can look further?
Solved: Finally the issue was due to an encoding issue in the POST.
Initially the POST data was created from an array with http_build_query().
Now the POST data is simply concatenated and both keys and values are urlencoded separately:
$options.=urlencode($fieldName).'='.urlencode($element->getAttribute('value'));
Solved: Finally the issue was due to an encoding issue in the POST. Initially the POST data was created from an array with http_build_query(). Now the POST data is simply concatenated and both keys and values are urlencoded separately:
$options.=urlencode($fieldName).'='.urlencode($element->getAttribute('value'));
See below url:--
cURL login session
and try this:-
http://php.net/manual/en/function.curl-setopt.php
<?php
echo curl_grab_page("https://www.example.net/login.php", "https://www.example.net/", "username=foo&password=bar", "true", "null", "false");
// $url = page to POST data
// $ref_url = tell the server which page you came from (spoofing)
// $login = true will make a clean cookie-file.
// $proxy = proxy data
// $proxystatus = do you use a proxy ? true/false
function
curl_grab_page($url,$ref_url,$data,$login,$proxy,$proxystatus){
if($login == 'true') {
$fp = fopen("cookie.txt", "w");
fclose($fp);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if ($proxystatus == 'true') {
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $ref_url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
ob_start();
return curl_exec ($ch); // execute the curl command
ob_end_clean();
curl_close ($ch);
unset($ch);
}

Categories