I have written code for file uploading and it is working fine on one server but not on local machine. Following is code:
<?php
ini_set("display_errors",1);
$api_url = 'https://content.dropboxapi.com/2/files/upload'; //dropbox api url
$token = 'fxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$headers = array('Authorization: Bearer ' . $token,
'Content-Type: application/octet-stream',
'Dropbox-API-Arg: ' .
json_encode(
array(
"path" => '/' . basename('image/1st.jpg'),
"mode" => "add",
"autorename" => true,
"mute" => false
)
),
'Content-Type: application/octet-stream'
);
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
$path = 'images/1st.jpg';
$fp = fopen($path, 'rb');
$filesize = filesize($path);
curl_setopt($ch, CURLOPT_POSTFIELDS, fread($fp, $filesize));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1); // debug
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "<pre>response === "; print_r($response); echo "</pre>";
echo "<pre>http_code === "; print_r($http_code); echo "</pre>";
?>
When i run this code on local, i got following output:
response ===
http_code === 0
On test server, it produce following output:
{"name": "1st.jpg", "path_lower": "/1st.jpg", "path_display": "/1st.jpg", "id": "id:UDbOKdE2bKXXXXXXECg", "client_modified": "2017-10-10T10:05:11Z", "server_modified": "2017-10-10T10:05:11Z", "rev": "4075316e33a", "size": 143578, "content_hash": "f30041XXXXXXXXXXX35ee3cXXXXXXe649afe8d"}
200
what can be possible reason for this issue?
Try to disable SSL veryfy host:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
Or more correct way is:
Download a file with the updated list of certificates from https://curl.haxx.se/ca/cacert.pem
Move the downloaded cacert.pem file to some safe location in your system
Update your php.ini file and configure the path to that file:
; Linux and macOS systems
curl.cainfo = "/path/to/cacert.pem"
; Windows systems
curl.cainfo = "C:\path\to\cacert.pem"
Following steps resolved issue for me:
1) Download the latest cacert.pem from https://curl.haxx.se/ca/cacert.pem
2) Add the following line to php.ini
Related
I know there are similar cases to my problem but my case is about uploading a file with the WorkDocs API in php.
I saw that this problem could be related to the file size but mine is only 1KB.
I also saw that it could be a cURL bug (source: https://github.com/aws/aws-sdk-php/issues/29).
I call the initiateDocumentVersionUpload service and get the upload url:
$result = $client->initiateDocumentVersionUpload([
"Name" => "test-file.txt",
"ParentFolderId" => "***"
]);
$content = $result->get('UploadMetadata');
$url = $content['UploadUrl'];
And my curl request:
// The full path to the file that you want to upload
$filePath = 'C:/wamp64/www/test_aws/test-file.txt';
// Initiate cURL
$curl = curl_init($url);
// Set the URL
curl_setopt($curl, CURLOPT_URL, $url);
// Set the HTTP request to POST
curl_setopt($curl, CURLOPT_PUT, true);
//Tell cURL to return the output as a string.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//Open the file using fopen.
$fileHandle = fopen($filePath, 'r');
//Pass the file handle resorce to CURLOPT_INFILE
curl_setopt($curl, CURLOPT_INFILE, $fileHandle);
//Set the CURLOPT_INFILESIZE option.
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($filePath));
$headers = array(
"Content-Type: application/octet-stream",
"x-amz-server-side-encryption: AES256"
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$data = "PUT request data";
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);
And so I get the error: Your socket connection to the server was not read from or written to within the timeout period. Idle connections will be closed.
Do you know how I can fix this problem and upload my file ? Thanks in advance !
I've found another solution that works perfectly.
I've add the attribut 'verify' => false to the httpClient instance to avoid SSL issue.
$filePath = 'C:/wamp64/www/test_aws/test-file.txt';
$body = fopen($filePath, 'r');
$guzzle = new httpClient(['verify' => false]);
$upload = $guzzle->put($uploadUrl, [
'headers' => [
"Content-Type" => "application/octet-stream",
"x-amz-server-side-encryption" => "AES256"
],
'body' => $body
]);
Found the solution here: https://docs.aws.amazon.com/code-samples/latest/catalog/php-workdocs-UploadDocument.php.html
I run an Apache webserver with mod_dav/mod_dav_fs on a windows server.
Users can edit certain files via WebDAV.
WebDAV is set up and running correctly so far...
The question is, how can I find out if and which files are currently opened via WebDAV?
Apache writes this info into its "DavLockDB".
Is there a way to read that file or to find out which files are currently locked?
I already tried it with via php:
$fp = fopen($file, 'c');
if (!flock($fp, LOCK_EX|LOCK_NB, $wouldblock)) {
// lock not obtained
echo 'file maybe open';
}
else {
// lock obtained
echo 'file is free';
}
This gives me a correct result if the file is opened locally on the server, but not if the file is opened via WebDAV.
Has anyone ever had a similar problem?
Kind regards
Thomas
I've been tied to and frustrated by WebDAV for some years, and I often had a need to be able to identify locked files and occasionally unlock them. I recently wrote a small tool in PHP to achieve this that you can see on Github.
Most of my answers were found in the RFC document & on the webdav.org site.I didn't encounter a solution using the DavLockDB and went the official route sending cURL requests to the DAV server as a real application would with HTTP verbs to get the info that I needed about files or directories.
In short you choose a file or directory as an endpoint and send PROPFIND request. If the endpoint is a directory you'll get a list of resources (files/directories) & their properties that are in that directory (and possibly under it depending on your DEPTH setting). If the endpoint is a file you'll get the file properties. In both cases the information is returned as XML and if any resource is locked the properties will include a LockToken.
Here's a PHP function that you could use based on a method in the repository noted above:
function propfind() {
$location = 'https://example.com:8000' // ROUTE TO SERVER
$endpoint = '/webdav/'; // FINAL DESTINATION
$auth = 'user:pass'; // BASE64 ENCODED USERNAME:PASSWORD
$url = $location.$endpoint;
$host = parse_url($location, PHP_URL_HOST);
$ch = curl_init();
// FIX LOCALHOST SSL CERTIFICATE ISSUES
if ($_SERVER['SERVER_NAME'] == 'localhost') curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+'); // CREATE A STREAM TO SAVE THE VERBOSE CONNECTION DATA
curl_setopt($ch, CURLOPT_STDERR, $verbose);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PROPFIND');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml; charset="utf-8"',
'Host: '.$host,
'Authorization: Basic '.$auth,
'Depth: 1',
));
/*
// OPTIONALLY LIMIT THE RESPONSE TO SPECIFIC PROPERTIES
$xml = '<?xml version="1.0" encoding="utf-8" ?><D:propfind xmlns:D="DAV:"><D:prop><D:creationdate/><D:getlastmodified/><D:getcontentlength/></D:prop></D:propfind>';
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
*/
$response = curl_exec($ch);
$curlInfo = curl_getinfo($ch);
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
if(curl_error($ch)) {
return array('error'=>curl_errno($ch).': '.curl_error($ch), 'response'=>print_r($curlInfo,1), 'verbose'=>$verboseLog);
}
curl_close($ch);
return array($response, $verboseLog);
}
A sample response might be:
<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:">
<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">
<D:href>/webdav/test.xlsx</D:href>
<D:propstat>
<D:prop>
<lp1:resourcetype/>
<lp1:creationdate>2020-04-11T20:30:58Z</lp1:creationdate>
<lp1:getcontentlength>9853</lp1:getcontentlength>
<lp1:getlastmodified>Thu, 06 Aug 2020 16:17:05 GMT</lp1:getlastmodified>
<lp1:getetag>"123456-789b-ab12345cd67e89"</lp1:getetag>
<lp2:executable>T</lp2:executable>
<D:supportedlock>
<D:lockentry>
<D:lockscope><D:exclusive/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
<D:lockentry>
<D:lockscope><D:shared/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
</D:supportedlock>
<D:lockdiscovery>
<D:activelock>
<D:locktype><D:write/></D:locktype>
<D:lockscope><D:exclusive/></D:lockscope>
<D:depth>infinity</D:depth>
<ns0:owner xmlns:ns0="DAV:"><ns0:href>Username</ns0:href></ns0:owner>
<D:timeout>Second-896</D:timeout>
<D:locktoken>
<D:href>opaquelocktoken:a12bc34d-567e-8901-23d4-5ab6cd7e8f90</D:href>
</D:locktoken>
</D:activelock>
</D:lockdiscovery>
<D:getcontenttype>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</D:getcontenttype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
Note the <D:locktoken> entry which indicates that the file is locked. In theory you could use the function recursively to map out the whole resource and highlight any locked files.
To unlock a file you need the credentials of the user that created the lock. Then send the request using UNLOCK as the HTTP verb:
function unlock () {
$lockToken = 'opaquelocktoken:a12bc34d-567e-8901-23d4-5ab6cd7e8f90';
$location = 'https://example.com:8000' // ROUTE TO SERVER
$endpoint = '/webdav/'; // FINAL DESTINATION
$auth = 'user:pass'; // BASE64 ENCODED USERNAME:PASSWORD
$url = $location.$endpoint;
$host = parse_url($location, PHP_URL_HOST);
$ch = curl_init();
// FIX LOCALHOST SSL CERTIFICATE ISSUES
if ($_SERVER['SERVER_NAME'] == 'localhost') curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'UNLOCK');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Host: '.$host,
'Authorization: Basic '.$auth,
'Lock-Token: <'.$lockToken.'>',
));
$response = curl_exec($ch);
$curlInfo = curl_getinfo($ch);
if(curl_error($ch)) {
$unlockStatus = 'ERROR: '.curl_error($ch).print_r($curlInfo,1);
}
else {
$unlockStatus = array(
'status' => ($curlInfo['http_code'] == '204' ? 'ok' : 'Fail'),
'response' => htmlentities($response),
'curlInfo' => $curlInfo,
);
}
curl_close($ch);
return $unlockStatus;
}
NB: In a more manual way you can get properties and unlock files from the command line with 2 cURL commands:
// GET RESOURCE PROPERTIES
curl -X PROPFIND '{path-to-resource}' -H 'Authorization:Basic {base64 encoded username:password}' -H 'Depth:1'
// UNLOCK A LOCKED FILE
curl -X UNLOCK '{path-to-resource}' -H 'Authorization: Basic {base64 encoded username:password}' -H 'Lock-Token: <{lock-token-from-first-request}>'
I am using PHP to get my object from AWS S3 and then turn around and upload it into Dropbox. I can successfully get the object from AWS, but when I try and upload the file into Dropbox I just an empty Json reponse with no error or anything. I know that my $dbToken (Dropbox token) is working right because I can use the same key to get my folder structure and list files.
When I try and upload a file it just goes blank. I think it has to do with the AWS presigned URL. Do I need to make a Curl request to get the contents of that url ($secureUrl in my case). Not sure how to write that and how to get this file into Dropbox. Thanks for your help.
# ============================================
# Connect to AWS and get the Object
# This works fine...
# ============================================
$s3 = new S3Client([
'credentials'=>[
'key'=>xxxxxxx,
'secret'=>xxxxxxx,
],
'region'=>'us-west-2',
'version'=>'2006-03-01',
]);
$cmd = $s3->getCommand('GetObject', [
'Bucket' => xxxxxxx,
'Key' => xxxxxxx,
]);
$request = $s3->createPresignedRequest($cmd, '+60 seconds');
$secureUrl = (string) $request->getUri(); // get signed uri...
# echo $secureUrl; // if I echo this on the page, I can see the url, copy it and paste it into the browser and all works well...
# ============================================
# Connect To DropBox and Upload File...
# This is returning nothing in my output...
# ============================================
$dbToken = 'xxxxxxx';
$headers = [
"Authorization: Bearer ". $dbToken,
'Dropbox-API-Arg: {"path": "'.$secureUrl.'", "mode": "add", "autorename": true, "mute":false }',
"Content-Type: application/octet-stream"
];
$url = 'https://content.dropboxapi.com/2/files/upload';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
$path = $secureUrl;
$fp = fopen($path, 'rb');
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$result = curl_exec($ch);
$data = json_decode(trim($result), TRUE);
echo '<pre>';
print_r($data); // the json response is empty...
echo '</pre>';
Hy Everyone,
I am using this code to download file from Dropbox Version 2 Php Api.But I don't get success yet in File downloading.Lets have a look on the script which i am using
function dbx_get_file($token, $in_filepath, $out_filepath)
{
$out_fp = fopen($out_filepath, 'w+');
if ($out_fp === FALSE)
{
echo "fopen error; can't open $out_filepath\n";
return (NULL);
}
$url = 'https://content.dropboxapi.com/2/files/download';
$header_array = array(
'Authorization: Bearer ' . $token,
'Content-Type:',
'Dropbox-API-Arg: {"path":"' . $in_filepath . '"}'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
curl_setopt($ch, CURLOPT_FILE, $out_fp);
$metadata = null;
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, $header) use (&$metadata)
{
$prefix = 'dropbox-api-result:';
if (strtolower(substr($header, 0, strlen($prefix))) === $prefix)
{
$metadata = json_decode(substr($header, strlen($prefix)), true);
}
return strlen($header);
}
);
$output = curl_exec($ch);
if ($output === FALSE)
{
echo "curl error: " . curl_error($ch);
}
curl_close($ch);
fclose($out_fp);
return($metadata);
} // dbx_get_file()
Calling this Function Here.
dbx_get_file("<Access-token>", '/Screenshot_1.png', 'Screenshot_1.png');
I also replaced this "Access-token" with my Dropbox O-auth 2 Access Token.
Please suggest me the answer what i am doing wrong?Or is there any other way to download File from Dropbox using DropBox Version 2 PHP Api.
Thanks
I have done it using Requests Library https://github.com/rmccue/Requests/
Here is my Code
include('Requests-master/library/Requests.php');
Requests::register_autoloader();
$token="Your Access Token is here";
$response =
Requests::post("https://content.dropboxapi.com/2/files/download", array(
'Authorization' => "Bearer ".$token,
'Dropbox-Api-Arg' => json_encode(array('path' => '/Screenshot_1.png')),
));
$fileContent = $response->body;
/*Download the file using file_put_contents method*/
file_put_contents("Screenshot_1.png",$fileContent);
$metadata = json_decode($response->headers['Dropbox-Api-Result'], true);
echo "File " . $metadata["name"] . " has the rev " . $metadata["rev"] . ".\n";
File is downloading Successfully... :)
What I'm trying to achieve:
Get request to an API Endpoint, retrieving an XML and subsequently parse the results.
I am sending a file_get_contents request to achieve this.
Issues:
`file_get_Contents` fails, error:
Warning: file_get_contents(https://api.twitter.com/1.1/statuses/mentions_timeline.json):
failed to open stream:
A connection attempt failed because the connected party did not properly
respond after a period of time, or established connection failed because
connected host has failed to respond.
Update 17/08
To consolidate my current understanding:
1. PHP FAILS:
1.a it fails via php (timeout)
1.b it fails via command line (curl -G http://api.eve-central.com/api/quicklook?typeid=34)
1.c file_get_contents
1.d file_get_contents w/ create_stream_context
2. What WORKS:
2.a Pasting the url in a chrome tab
2.b via postman
What has been attempted:
- Check Headers in Postman ,and try to replicate them via php
Postman Headers sent back by eve-central:
Access-Control-Allow-Origin → *
Connection → Keep-Alive
Content-Encoding → gzip
Content-Type → text/xml; charset=UTF-8
Date → Wed, 17 Aug 2016 10:40:24 GMT
Proxy-Connection → Keep-Alive
Server → nginx
Transfer-Encoding → chunked
Vary → Accept-Encoding
Via → HTTP/1.1 proxy10014
Corresponding Code:
$headers = array(
'method' => 'GET',
'header' => 'Connection: Keep-Alive',
'header' => 'Content-Encoding: gzip',
'header' => 'Content-Type: text/xml',
'header' => 'Proxy-Connection: Keep-Alive',
'header' => 'Server: nginx',
'header' => 'Transfer-Encoding: chunked',
'header' => 'Vary: Accept-Encoding',
'header' => 'Via: HTTP/1.1 proxy10014');
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt($curl, CURLOPT_PORT , 8080); // Attempt at changing port in the event it was blocked.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_POST, false );
curl_setopt($curl, CURLOPT_URL, $url );
$resp = curl_exec($curl);
if(curl_error($curl))
{
echo 'error:' . curl_error($curl);
}
Use Wireshark to capture the GET request to see if changing the port helped
Run cUrl via command line
I'm out of ideas and option.
So the questions are:
If it works in a browser, and in Postman, why does it not work via PHP ?
How can I modify my code so that it mimics what Postman does? ?
Previous Attempts
What I have tried:
Various cURL options from other threads, such as
function curl_get_contents($url) {
$ch = curl_init();
if (!$ch)
{
die("Couldn't initialize a cURL handle");
} else
echo "Curl Handle initialized ";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$data = curl_exec($ch);
// Check if any error occurred
if (!curl_errno($ch))
{
$info = curl_getinfo($ch);
echo 'Took ', $info['total_time'], ' seconds to send a request to ', $info['url'], "";
displayData($info);
} else
echo "Failed Curl, reason: ".curl_error($ch)." ";
curl_close($ch);
return $data;
}
result: nothing, no data returned.
- Checked php.ini options:
- allow_fopen is On
- allow_url_include = on
- relevant ssl extensions are enabled
- Raised the timeout window
- both via php.ini
- also via explicit declaration within the php file.
- Tried with a different url
- same error, so it doesn't really depends on my particular endpoint
- for example, both twitter/wikipedia/google return the specific error
- tried with:
- file_get_contents on a local xml file (https://msdn.microsoft.com/en-us/library/ms762271(v=vs.85).aspx) --> works
- file_get_contents on a remote xml file (http://www.xmlfiles.com/examples/note.xml) --> fails same error
- Overall, the following is true, so far:
- Curl fails, timeout
- file_get_Contents fails, timeout
- Open XML file url in a browser works
- Make a GET request via Postman, works
Obviously, in all cases where the file_get_contents fails via php, I can easily access the file via any browser.
Tried to work around the issue.
Attempt 1:
Use nitrous.io, create a LAMP stack, perform the deed via the platform
results: file_get_contents works, however, due to the large number of xml files to be retrieved, the operation times-out.
Tentative solution:
- Download XML files from source
- Zip them
- Download xml_file
- Locally parse said xml files
Later on, write a small php scripts that, when invoked, performs the bits above, sends the data to the local directory, which then unpacks it and performs additional work on it.
Another attempt would be to use Google Sheets, with a user function that pulls the data into the sheet, and just dump the excel file / values into mysql.
For my purposes, while an awfully ignorant solution, it does the trick.
Code used for avoiding timeout issue on shared host:
function downloadUrlToFile2($url, $outFileName)
{
//file_put_contents($xmlFileName, fopen($link, 'r'));
//copy($link, $xmlFileName); // download xml file
;
echo "Passing $url into $outFileName ";
// $outFileName = touch();
$fp = fopen($outFileName, "w");
if(is_file($url))
{
copy($url, $outFileName); // download xml file
} else
{
$ch = curl_init();
$options = array(
CURLOPT_TIMEOUT => 28800, // set this to 8 hours so we dont timeout on big files
CURLOPT_URL => $url
);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt_array($ch, $options);
$contents = curl_exec($ch);
fwrite($fp, $contents);
curl_close($ch);
}
}
I have also added this on top of the ini script:
ignore_user_abort(true);
set_time_limit(0);
ini_set('memory_limit', '2048M');
I see some issue with HTTPS url request, for fix issue you have to add below lines in your CURL request
function curl_get_contents($url) {
$ch = curl_init();
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$header[] = "Cache-Control: max-age=0";
$header[] = "Connection: keep-alive";
$header[] = "Keep-Alive: 300";
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Pragma: ";
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
// I have added below two lines
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}