Using cURL to upload a file without # symbol? - php

I have a slight problem here, how can I tell cURL specifically to attach a file to a request?
If I am uploading a file with cURL, then the common method is to attach it as part of POST data array with the value having # in front of it, for example:
CURLOPT_POSTFIELDS=>array('my-file'=>'#my-file.txt')
This would obviously work, but I have two problems with it:
What if it is not actually a file I am uploading? What if my POST value actually IS '#my-file.txt' and it attempts to upload the file instead? It creates a loophole I am desperately trying to avoid.
How can I upload a file from a URL? Would I have to download it, store it in temporary folder and then attach it with # from that temporary folder? Why can't I give cURL just contents that I wish to use as file?
cURL CURLOPT_INFILE is not an option, since it won't show up as part of $_FILES array.
It seems like such a loophole in cURL to be dependent on # symbol in the POST field value. Is there a way around it? Why isn't there a CURLOPT_FILEFIELDS array? Command-line cURL has a separate flag for this (-F), but I don't see it as an option in PHP for some reason.
Any help would be greatly appreciated, thanks!

In case anyone is viewing this in 2019 and beyond after finding this result on Google (as I have) the issue has been resolved as per this bug fix.
You can now use CURLFile to send files via PHP CURL requests as below:
$fullpath = '/var/www/html/website/test.png';
$mime = 'image/png';
$publicname = 'testpic';
$cfile = curl_file_create($fullpath,$mime,$publicname);
$fields[$publicname] = curl_file_create($fullpath,$mime,$publicname);
Which would be then used in e.g.
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
Further information can be found here.

What I ended up doing is detecting if any of the input data started with an # symbol and if they did, then submitting them as a GET variable (as part of the submit URL in cURL). It does not help with all cases (such as when a large string is submitted that starts with an #), but cuts out the problems I had with Twitter handles.

Related

Azure Functions with PHP

I'm trying out Azure Functions using PHP.
Getting the request information is not working for me.
I've not been able to find any documentation at all with the information of how to use Azure Functions with PHP code.
According to the only couple of examples, it seems that in order to retrieve the input information you need to first get the content of the req variable (or whatever name you assign in the function configuration).
That has the path of the file containing the request information (in theory).
$input_path = getenv('req');
So far, if I check the content of it, I get something like this:
D:\local\Temp\Functions\Binding\e2b6e195-02f7-481b-a279-eef6f82bc7b4\req
If I check if the file exists it says true, but the file size is 0.
Do anyone knows what to do here? Anyone with an example? Does anyone know where the documentation is?
Thanks
Ok, unfortunately there's pretty limited documentation out there for php as you have discovered.
At present, looking at the code might be the best doc. Here is the InitializeHttpRequestEnvironmentVariables function that adds request metadata to the environment for the script languages (node, powershell, php, python).
Important environment variables are:
REQ_ORIGINAL_URL
REQ_METHOD
REQ_QUERY
REQ_QUERY_<queryname>
REQ_HEADERS_<headername>
REQ_PARAMS_<paramname>
I'm assuming you've made a GET request, in which case there is no content (req is an empty file), but you will see that these other environment variables contain request data. If you were to make a POST request with a body then req would have data.
here is a full example parsing a GET request in PHP with an Azure Function :)
https://www.lieben.nu/liebensraum/2017/08/parsing-a-get-request-in-php-with-an-azure-function/
snippet from source:
<?php
//retrieve original GET string
$getReqString = getenv('REQ_QUERY');
//remove the ? for the parse_str function
$getReqString = substr($getReqString,1,strlen($getReqString));
//convert the GET string to an array
$parsedRequest = array();
parse_str($getReqString,$parsedRequest);
//show contents of the new array
print_r($parsedRequest);
//show the value of a GET variable
echo $parsedRequest["code"];
?>

file_get_contents not working when parameters included in a relative url

I am trying to create a simple web service that will give a result depending on parameters passed.
I would like to use file_get_contents but am having difficulties getting it to work. I have researched many of the other questions relating to the file_get_contents issues but none have been exactly the situation I seem to having.
I have a webpage:
example.com/xdirectory/index.php
I am attempting to get the value of the output of that page using:
file_get_contents(urlencode('https://www.example.com/xdirectory/index.php'));*
That does not work due to some issue with the https. Since the requesting page and the target are both on the same server I try again with a relative path:
file_get_contents(urlencode('../xdirectory/index.php'));
That does work and retrieves the html output of the page as expected.
Now if I try:
file_get_contents(urlencode('../xdirectory/index.php?id=100'));
The html output is (should be): Hello World.
The result retrieved by the command is blank. I check the error log and have an error:
[Fri Dec 04 12:22:54 2015] [error] [client 10.50.0.12] PHP Warning: file_get_contents(../xdirectory/index.php?id=100): failed to open stream: No such file or directory in /var/www/html/inventory/index.php on line 40, referer: https://www.example.com/inventory/index.php
The php.ini has these set:
allow_url_fopen, On local and On master
allow_url_include, On local and On master
Since I can get the content properly using only the url and NOT when using it with parameters I'm guessing that there is an issue with parameters and file_get_contents. I cannot find any notice against using parameters in the documentation so am at a loss and asking for your help.
Additional Notes:
I have tried this using urlencode and not using urlencode. Also, I am not trying to retrieve a file but dynamically created html output depending on parameters passed (just as much of the html output at index.php is dynamically created).
** There are several folks giving me all kind of good suggestions and it has been suggested that I must use the full blown absolute path. I just completed an experiment using file_get_contents to get http://www.duckduckgo.com, that worked, and then with a urlencoded parameter (http://www.duckduckgo.com/?q=php+is+cool)... that worked too.
It was when I tried the secure side of things, https://www.duckduckgo.com that it failed, and, with the same error message in the log as I have been receiving with my other queries.
So, now I have a refined question and I may need to update the question title to reflect it.
Does anyone know how to get a parameterized relative url to work with file_get_contents? (i.e. 'file_get_contents(urlencode('../xdirectory/index.php?id=' . urlencode('100'))); )
Unless you provide a full-blown absolute protocol://host/path-type url to file_get_contents, it WILL assume you're dealing with a local filesystem path.
That means your urlencode() version is wrongly doing
file_get_contents('..%2Fxdirectory%2Findex.php');
and you are HIGHLY unlikely to have a hidden file named ..%2Fetc....
call url with domain, try this
file_get_contents('https://www.example.com/inventory/index.php?id=100');
From reading your comments and additional notes, I think you don't want file_get_contents but you want include.
see How to execute and get content of a .php file in a variable?
Several of these answers give you useful pointers on what it looks like you're trying to achieve.
file_get_contents will return the contents of a file rather than the output of a file, unless it's a URL, but as you seem to have other issues with passing the URI absolutely....
So; you can construct something like:
$_GET['id'] = 100;
//this will pass the variable into the index.php file to use as if it was
// a GET value passed in the URI.
$output = include $_SERVER['DOCUMENT_ROOT']."/file/address/index.php";
unset($_GET['id']);
//$output holds the HTML code as a string,
The above feels hacky trying to incorporate $_GET values into the index.php page, but if you can edit the index.php page you can use plain PHP passed values and also get the output returned with a specific return $output; statement at the end of the included file.
It has been two years since I used PHP so I am just speculating about what I might try in your situation.
Instead of trying fetching the parsed file contents with arguments as a query string, I might try to set the variables directly within the php script and then include it (that is if the framework you use allows this).
To achive this I would use pattern:
ob_start -> set the variable, include the file that uses the variable -> ob_get_contents -> ob_end_clean
It is like opening your terminal and running the php file with arguments.
Anyway, I would not be surprised if there are better ways to achieve the same results. Happy hacking :o)
EDIT:
I like to emphasize that I am just speculating. I don't know if there are any security issues with this approach. You could of course ask and see if anyone knows here on stackoverflow.
EDIT2:
Hmm, scrap what I said last. I would check if you can use argv instead.
'argv' Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string. http://php.net/manual/en/reserved.variables.server.php
Then you just call your php script locally but without the query mark indicator "?". This way you can use the php interpreter without the server.
This is likely to be the most general solution because you can also use argv for get requests if I am understanding the manual correctly.

Save binary request body as file

I wrote a program that reads a binary file into the RAM and then sends it using an HTTP request to my server. It uses the PUT method and the binary file is (in) the body.
Now how can I tell my server to receive and safe the file in a folder?
If possible without any additional libraries that I would need to download (unless it's more efficient).
I know, there are some similar threads to this one, but they either they where about receiving text or they were about doing it with libraries or there simply was no sufficient answer.
I'd also like to know, if it would be more efficient or smarter to use the POST method or any other instead of PUT.
You can get at the data by opening a stream to php://input, like so:
$datastr = fopen('php://input',rb);
if ($fp = fopen('outputfile.bin', "wb")){
while(!feof($datastr)){
fwrite($fp,fread($datastr,4096)) ;
}
}
As to whether to use POST or anything else depends on what is happening with the data, and whether you care about being RESTful or such. See other questions/answers, indempotency.
The advantage I would see with using POST is that it's more commonly used (on most submission forms where you upload a file), and therefore has more support from within PHP and html.

How to write response to file using php

I wish to write the response of hitting a given url into the href attribute of an anchor tag using PHP. How can I do this?
Here's an example of what I excpect to happen
mylink.com/getdoc?name=documentA
returns a string as a response:
mylink.com/document2012-03-15.pdf
I need to write this response (using PHP into the href attribute as shown below:
Open Document A
(so the above will be the final source of my page.
I think there are a few ways to do what you want. Not all of them will work exactly as you ask for, but the end result should be the same.
Solution one
My first possible solution was already posted by #shanethehat. You could use file_get_contents to call your PHP script via HTTP and get the response.
Solution two
Another possible solution was suggested in the comments of the post by #YourCommonSense. You could simply include the getdoc script in the PHP script that is generating your HTML file, like this:
$_GET["name"] = "documentA";
echo " Open Document A ";
Solution three
Or you could change the way the getdoc script works. You could use a script more like this:
header("Content-type:application/pdf");
header("Content-Disposition:attachment; filename=\"{$_GET["name"]}\"");
readfile($_GET["name"]);
And you keep your link like this: Open Document A . When getdoc.php is called, it will get the specified file and start a file download.
NOTE: you should probably do some input sanitization with this method (removing slashes, making sure the file ends in .pdf, etc) to make sure someone doesn't try to get a file they're not allowed to get.
That's all I'm coming up with at the moment. There might be a more clever way to do it, but hopefully one of these solutions will do it for you. I would try solution 2 or 3 first, and if they don't work out for you, then go with solution 1.
<?php
//get output from URL
$myfile = file_get_contents('http://mylink.com/getdoc?name=documentA');
?>
Open Document A
How to write response to file using php
Noway.
PHP do not process HTTP requests.
You have to set up your web server to do the rewrite.
There are 100500 questions under mod_rewrite tag, you will find the solution easily.
Note that you may wish to rewrite your url to /getdoc.php?name=document2012-03-15.pdf, not one you mentioned in your question

using file get contents on a url that requires post data

i need to do a "file_get_contents" on a URL and there has to be data posted to the url before the contents are retrieved. is this possible? maybe something like
$contents = file_get_contents($_POST"http://www.example.com/");
so that i can then work with the $contents variable?
You cannot*** POST data using file_get_contents, you must use something like cURL
* I mark this because it is actually possible taking advantage of the third parameter which uses http context(see example one). However it really isn't worth your trouble if you have something like cURL.
Ah, I have tried to do this. Simply put you can't unless you install new extra software on your sever and go through A LOT of hassel and server load.
Best bet is to use GET if at all possible!
:)

Categories