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}>'
Related
I'm having trouble with the OpenAI API, Basically what I'm trying to do is stream each data node that is streamed back from the openai API response and output each data node one at a time as it streams in from the API call, but I have no clue how this is done, I researched for hours and can not find any information on how this can be achieved with PHP.
How can I get my code to output each data node in real time as the API streams in the data?
The Following is the best I can come up with, it outputs all the data at once after the call is complete, but It does not stream in the data.
function openAI(){
$OPENAI_API_KEY="API_KEY_GOES_HERE";
$user_id="1"; // users id optional
$prompt="tell me what you can do for me.";
$temperature=0.5; // 1 adds complete randomness 0 no randomness 0.0
$max_tokens=30;
$data = array('model'=>'text-davinci-002',
'prompt'=>$prompt,
'temperature'=>$temperature,
'max_tokens'=>$max_tokens,
'top_p'=>1.0,
'stream'=>TRUE,// stream back response
'frequency_penalty'=>0.0,
'presence_penalty'=>0.0,
'user' => $user_id);
$post_json= json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
$headers = array();
$headers[] = 'Content-Type: application/json';
// $headers[] = 'Content-Type: text/event-stream';
$headers[] = "Authorization: Bearer $OPENAI_API_KEY";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
return $result;
curl_close($ch);
}
echo openAI();
I ended up solving my problem. Hopefully my answer will help someone in the future.
I made the following additions to my code. This simple logic makes what I inquired about work.
// This should be at the very top, alternatively can be set in you php.ini file
#ini_set('zlib.output_compression',0);
#ini_set('implicit_flush',1);
// This function discards the contents of the topmost output buffer and turns off this output buffering.
#ob_end_clean();
The following curl_setopt should also be added. I personally added it on the line after CURLOPT_POSTFIELDS
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) {
# str_repeat(' ',1024*8) is needed to fill the buffer and will make streaming the data possible
echo $data.str_repeat(' ',1024*8);
return strlen($data);
});
Alternatively instead of adding str_repeat(' ',1024*8) you can shut off buffering in your web servers config file, e.g.(nginx.conf)
gzip off;
proxy_buffering off;
I am trying to download a file from an API that I am successfully talking to, however, when I hit the file, it outputs just a bunch of crazy characters. I believe it is the .zip stream, and I just need to get the .csv file that should be in there.
From the API documentation:
curl -XGET -H 'X-API-TOKEN: <API TokenZ' -H 'Content-Type: application/json' https://co1.qualtrics.com/API/v3/surveys/SV_50EhstBgHEG2voV/export-responses/2671b6ec-66e0-4e7b-90bc-77174363763d/file -o responses.zip
Here is what I have:
$file = 'https://co1.qualtrics.com/API/v3/surveys/'.$qualtrics_id.'/export-responses/'.$file_json['result']['fileId'].'/file';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
echo $result;
curl_close ($ch);
And this is what it gives me:
PKr�JOTest survey.csv�Wmo�����¸�w���W��"��i��M6�m�˂�h����T���3�$+�}{-ĶD93�<3~tܸ+�Dt� ���qW����eQam����� wR+��T̊\����$���(�;��B�]��jeō�[)�{ϭ��o�a�'i���7\V���F��N��*�{�{�����7��:�\I�\�4�cɕU�� �u��"�MS|��It;�ng��<�͢�$�'�g���C$�d9��~���b-T왗�~������mwsu�l�9H�w<�:ڒ������>����J��i�3� �J�~���+�xr��J���W�m�ѰR�V��*X��lYk���Tc9Wl)FRS��B�]��%7����R�zYU��tۭP�T�Y��_��-����v8��VP�K��R� *n�2�ƈu�&����-V� ��y%��� Kh�,���o��e���Y�w���K�.#x�c;]����6��!��уһJƗ�vl+���T��-���A�DTa:P����x�JK��h�y� �t �܈BRLA0K+*� �}�-�AX�\`%`�]+����d,�n�g�R��[Y��]� 3�R)��x�?�ۭFjH%��]Ǥ�7����߄p���B"���#p�[����0d�+L���!�������?��x�JoV�Iz"�J���h%��lM�z��ZU![�x�40��$�0hY�0�xST��U�^��G"XT �;�ʞk�����sr�#��� ��F��,4D�v(T6r"w#QI���T;d7㊪^��bW6��pT�B��Q\~`�V�R�/�� ,q�R���\�U�B0ԇ6 ��>ռ�oT�֪|ߖ� � gߍ�x��ĩ����k4$�D�Z�Y���o+�Ƿٞ��d ��K:��r*��O�PXIYB�T�������E5-��������p����S��n�ڳ��$Ptʱ_��8��9�S�6��J`��'Q?هJ+X�,� ��#�C�)N���%�����[J`�y���J�"b�?�,� |�JT��ߔ��V���9���c�+��!7��X��}��V�P�nC�9fjվP�|E�0�A��`�}������'��r��H1o��8���ҕ�{�B4� �0>罐i���<�תFp��~��O���L:jEP�N#݈\�#T�4����� ��D����!�_�I<�� ��X��r�SK��MyDG*�h�>�8JM��F���=+��8���8!��e�3�5��K)X|`��3v�� oR���z�}�6������5����gu��5��j��W�I���#b,z���sH�yӜ�c�1����D�uA�:U��b���e�x!�Me>��fH���me�Vn�#d%u�ǔD6C���ynT`a�_��MyG ���ҹ��͛�n7�HK��e��8�W�E�|״�~���& }�G��T���Jd�!i�^�]�4�n�Uc����#�R#��[\��NDDx�� �.4�����i{�:��чw�;��ժۘh`�o��{_y�nE�7���M^Nu����zd*t��h�!}#�9p�����v����_�-�����m��e#��X᧾���� [�����9�m.d����-��l�\�NϮ�+��Yӻ�nO��U7��|~���Xw�����6��Es���dw�<-Z�Ͽ!��8�#��&Z��]�OK��\�����3��3ӳ3��3�3�ٙ$>?�������:?s�����8�fq6�N��$�J�=�C]���F���� �FLY�.F�b��w���Y����״��~���ۏ����g6�/�%�E<^��ы�q���a2M��?3o����w_q���;y����_��J��h<�b��eI���$�&i2��G���&Ϭ�.������d���I�'���E���t�ݦ�b�_���8ɲy�%q�$x��l����,�������PK��{pnZPKr�JO��{pnZTest survey.csvPK=�
I am not sure what to do with this, I would like to at least be able to download the zip file with the .csv files in there, however, it would be more than ideal to simply get the "Test survey.csv" file, but I haven't been able to do either, I have tried many different things such as:
// header('Content-Type: application/zip');
// readfile($result);
// $z = new ZipArchive();
// $h = $z->getStream( $result );
// stream_get_contents($result);
All with no luck, any help is appreciated. Thank you.
with the CURLOPT_RETURNTRANSFER option is set curl_exec will return downloaded content in the result. So, your variable $result actually contains the content of the file (PKr�... is a ZIP-header)
So, all you need, just to save the content of the variable in a file, instead of echoing it into the browser.
For example.
...
$result = curl_exec($ch);
file_put_contents('downloaded.zip', $result); // save the string to a file
curl_close ($ch);
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;
}
I have read and tried thousands of solutions in different posts and none of them seems to work with me. This three are example of that.
cURL is unable to use client certificate , in local server
php openssl_get_publickey() and curl - unable to use client certificate (no key found or wrong pass phrase?)
Getting (58) unable to use client certificate (no key found or wrong pass phrase?) from curl
I received a .p12 certificate which I converted to .pem file in https://www.sslshopper.com/ssl-converter.html
The password is correct otherwise it wouldn't convert it.
$xml = 'my xml here';
$url = 'https://qly.mbway.pt/Merchant/requestFinancialOperationWS';
$headers = array(
'Content-Type: text/xml; charset="utf-8"',
'Content-Length: ' . strlen($xml),
'Accept: text/xml',
'Cache-Control: no-cache',
'Pragma: no-cache'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSLCERT, base_url() . 'public/cert.pem');
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, 'my password here');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
$data = curl_exec($ch);
if(!$data)
print_r('ERROR: ' . curl_error($ch));
else
print_r('SUCCESS: ' . curl_error($ch));
I have tried with SoapUI application and works fine but with cURL I'm receiving the error:
unable to use client certificate (no key found or wrong pass phrase?)
I have tried without success:
Disable CURLOPT_SSL_VERIFYPEER and/or CURLOPT_SSL_VERIFYHOST
Add CURLOPT_SSLKEYTYPE and/or CURLOPT_SSLKEY fields
EDIT 1:
I have been trying around with SOAPClient besides cURL and it seems that the error might be the headers.
My headers after print_r($soapClient) are the following:
Host: qly.mbway.pt
Connection: Keep-Alive
User-Agent: PHP-SOAP/5.5.9-1ubuntu4.14
Content-Type: application/soap+xml; charset=utf-8; action=""
Content-Length: 1750
I would like to know how can I remove the action=""? I tried to extend the original class without success in terms of changing the header.
class MySoapClient extends SoapClient
{
public function __construct($wsdl, $options = array())
{
$ctx_opts = array('http' => array('header' => array('Content-Type' => 'application/soapyyyyyml')));
$ctx = stream_context_create($ctx_opts);
parent::__construct($wsdl, array('stream_context' => $ctx));
}
}
Solved with cURL.
The problem was the path of the pem file.
I was using base_url() . 'public/cert.pem' but that's not possible. Instead I need to use a relative path such as ./public/cert.pem.
I have a Flask app, with a basic function, where I have exposed app.run() to a public ip, so that it is accessible from an external server;[ using Flask - Externally Visible Dev Server ]
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = 8080)
The curl request I have written in my php code is:
$signed_url = "http://my-ip-address:8080/";
$ch = curl_init($signed_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data= curl_exec($ch);
echo $data;
I can do a curl request :
curl http://my-ip-address:8080/
from command line. However, when the curl request is embedded within my PHP code, it gives me an error "Connection refused".
Kindly help!
If the PHP code is on another server, but your command line cURL request is on the same server, then you aren't comparing apples to apples.
Two things that might be wrong:
Your Flask server has a firewall that doesn't allow external connections.
You are connecting using an private network IP address rather than a public IP address.
For now your PHP code looks correct, so I would narrow down the problem a little bit. Ignore that PHP code and try to connect using cURL on the command line from the same server you are running your PHP code on.
try to set your port with curl options like this:
curl_setopt($ch, CURLOPT_PORT, 8080);
so your signed url will be:
$signed_url = "http://my-ip-address";
I use this code for my work and worked :)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost:5000/spmi/api/1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"teks_analysis\":\"tidak ada skor nol\"}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
the key is CURLOPT_POSTFIELDS