How to send a data '\n' using curl post in php? - php

I am sending same data with PHP cURL. But I am using "\n" character in a text area and it prints "Empty reply from server". Unless I use "\n", it is working.
For example:
<form action="gonder.php" method="post">
<textarea name="content" rows=23 cols=70></textarea>
<input class="button" type="submit" value="Kaydet">
</form>
And my gonder.php file:
<?php
if($_POST['content'] != ""){
$ch = curl_init('http://address/page.php');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'bilgi='.$_POST['content']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch) or die(curl_error($ch));
header("Location: index.php?olay=2");
}
?>
Additional information: My file has single-quotes at the end.
How can I solve this problem?
veriler.txt:
araba
ev
dükkan
mağaza
veriler.txt is in another server and I want to rewrite it with a textarea using post method

curl will encode for you if you pass an array, or you can use urlencode() in your existing code:
$content = array('bilgi' => $_POST['content']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);

I think that you need to send the text as HTML using this functions nl2br(htmlentities()) :
curl_setopt($ch, CURLOPT_POSTFIELDS, 'bilgi='.nl2br(htmlentities($_POST['content'])));
as
araba<br>
ev<br>
Then when you receive it extract the text from html code using str_replace( "<br>" , "\n" , $_POST['bilgi']); , And write it into you file veriler.txt

Related

CURL not posting data to URL

I have a simple form which i want to convert into a PHP backend system.
Now this form has an action to submit to a URL - the URL only accepts an invite only when a data with the name postdata and correct information is submitted (xml which has been encoded).
Works: - Note that the input name is called postdata and the value contains the xml which has been urlencoded and it works perfectly.
<form name="nonjava" method="post" action="https://url.com">
<input name="postdata" id="nonjavapostdata" type="hidden" value="&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;" />
<button type="submit" name="submit">Button</button>
</form>
However, i want to achieve the following by moving the postdata element within PHP as a lot of information is passed through that way.
Please note: the link is https but it wasnt working on local so i had to disable it within the CURL.
<?php
$url = 'https://super.com';
$xmlData = '<?xml version="1.0" encoding="utf-8"?>
<postdata
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<api>2</api>
</postdata>';
$testing = urlencode($xmlData);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "postdata=" . $testing);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$response = curl_exec($ch);
// Then, after your curl_exec call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
echo $header_size . '<br>';
echo htmlspecialchars($header) . '<br>';
echo htmlspecialchars($body) . '<br><br>';
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo "$http_status for $url <br>";
?>
I keep getting a 302 error (which is the url content is not finding the data so its redirecting to a not found page.)
302 is NOT error; it just means you need to go to the redirected URL. A browser does that automatically for you. In PHP code, you would have to do it yourself. Look at the Location header on 302.
I tried to look if there is a way that Curl could be told to follow through redirects; many language HTTP libraries support that. This thread seems to suggest that CuRL also supports it - Is there a way to follow redirects with command line cURL
Your code works as it is supposed to, I am getting POST data:
Array ( [postdata] => <?xml version="1.0" encoding="utf-8"?> <postdata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/20
01/XMLSchema"> <api>2</api> </postdata> )
as a result. The problem is on the receiving side, it isnt handling it correctly.
You need to follow the 302 redirect in curl. This is relatively easy to do by adding the location flag. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
This is the equivalent of doing curl -L at the CLI. You can see an example here in the php documentation.

Slack Incoming Webhook with PHP form

I'm trying to create a PHP script that automatically pushes text from <textarea> in my webform to Slack channel.
HTML:
<form action="http://main.xfiddle.com/<?php echo pf_file('g7f-ds0'); ?>" method="post" id="myform" name="myform">
<textarea name="text" id="" rows="3" cols="30">
</textarea> <br /><br />
<button id="mysubmit" type="submit" name="submit">Submit</button><br /><br /></form>
I managed to write a PHP script that posts hard coded message to Slack like this:
<?php
//API Url
$url = 'https://hooks.slack.com/services/T02NZ01FU/B08TTAPGE/000000000000000000';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$payload = array(
’text' => 'Testing text with PHP'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($payload);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
?>
But for some reason when I try to get text from <textarea name="text" rows="3" cols="30"></textarea> and save it into a variable then it doesn't work. I add this to the beginning of PHP to set the text variable:
if(isset($_POST['submit']))
$textdata = $_POST['text'];
and then change the $payload to
'text' => $textdata
A simple example of how to use slack incoming webhook with curl
<?php
define('SLACK_WEBHOOK', 'https://hooks.slack.com/services/xxx/yyy/zzz');
function slack($txt) {
$msg = array('text' => $txt);
$c = curl_init(SLACK_WEBHOOK);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, array('payload' => json_encode($msg)));
curl_exec($c);
curl_close($c);
}
?>
Snippet taken from here
There are two likely issues here.
The PHP formatting in your post is incorrect.
Replace ’text' => 'Testing text with PHP' with
'text' => 'Testing text with PHP'
Your curl is not set up correctly. Please see the following posts to debug curl and to fix what is likely wrong - no trusted SSL certificates

Not getting a response from web service - not sure what I'm doing wrong

This is my first shot at getting something back from a web service. What I'm expecting is something to the effect of 'Authorization Failed'. The URL is one in our test environment and the XML being sent is correct, but I'm not getting a response and don't know what I'm doing wrong.
The service is REST, the headers have to pass an encoded authorization (this example is correct) and the content type is set as xml.
When I use the same parameters to test it in the Advanced Rest Client in Chrome it connects and gives me a response.
Also, if there's a better way to create the XML, I'm all for that - this is just an example I found and started with. Code is below
<?php
if (!isset($_POST['firstname'])) {
?>
<form name="ppost" method="post" action="<?=$_SERVER['PHP_SELF']?>">
<input type="text" name="firstname" />
<input type="submit" name="SUbmit" value="Submit" />
</form>
<?php
} // end if, form not posted
else {
extract($_POST);
$inputdata = '
<ReqGetWebUserInfo>
<OrgId>598</OrgId>
<OrgUnitId>598</OrgUnitId>
<MasterCustomerId>'.$firstname.'</MasterCustomerId>
<SubCustomerId>0</SubCustomerId>
</ReqGetWebUserInfo>';
echo '<pre>'.$inputdata.'</pre>';
$url = "https://gsusacustom.ebiz.uapps.net/GSUSARestWebService/PersonifyWcfSvc.svc/GetWebUserInfo";
$headers = array(
'Authorization: Basic dG1hc2d1bmRhbTpwYXNzd29yZDE=',
'Content-Type: application/xml;charset=utf-8',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url ); // THE URL TO FETCH - CAN ALSO BE SET IN THE CURL_INIT
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0); // DON'T INLCUDE HEADER IN THE OUTPUT
curl_setopt($ch, CURLOPT_POST, 1); // TRUE FOR A REGULAR HTTP POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $inputdata); // THE DATA POST FROM THE FORM
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close ($ch);
print $response;
} // end else, form submitted and processed
?>
Thanks in advance.
My guess is you didn't handle the https connection as your has it. Try this option:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
If the error still persists then do the following to dig more.
Run the code with enabling all error reporting:
error_reporting(E_ALL);
Run the curl with enabling debugging option:
curl_setopt($ch, CURLOPT_VERBOSE, 1);

How to pass data containing special characters through curl

I cannot able to post data its contain the special characters through curl ,Any solution ?
first code is my curl function ,second code is my data need to pass
$communication_data_string = 'token='.json_encode(array(
"activityTypeId"=>12,
"activityId"=>5,
"userID"=> 10,
"partyID"=>20,
"message_area_name"=>("this is my test data with special cheractors&&!###$%$%%*)++")
)
);
echo(datPostingCURL($url, $communication_data_string));
?>
this seems to not returning anything if the messageData contains the special character's
Try urlencode
or
How about using the entity codes...
# = %40
& = %26
change the line
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
to
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($data_string));
the receive it in following way as you are not using any specific post variable
$data = urldecode(file_get_contents('php://input'));
Check the following code. I tested it in my local system. In my www director I created a folder named "test" for keeping the code. Then I created 2 files in that "test" folder. One file for sending the request and one for processing the request.
1. curl.php
<?php
function datPostingCURL($url, $data_string)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
return $result;
}
$url = "http://localhost/test/curl_post.php";
$communication_data_string = 'token='.json_encode(array(
"activityTypeId"=>12,
"activityId"=>5,
"userID"=> 10,
"partyID"=>20,
"message_area_name"=>base64_encode("hai ..this is my test data .!###$%$%%*)++")
)
);
echo(datPostingCURL($url, $communication_data_string));
?>
2. curl_post.php
<?php
print_r(json_decode($_POST['token']));
$details = json_decode($_POST['token']); var_dump($details);
echo base64_decode($details->message_area_name);
?>
Note : While using special characters you should encode that string. I tried to convert it with htmlspecialchars(). But it didn't worked. So I used base64 encoding method here.

PHP Curl upload file with file browse button

I want to remote upload my file into a server that accept uploads
using curl , but without typing the full file path every time with "#" symbol
can i make a browse button to select files then proceed to curl upload
this is my code ::
$post = array("file_box"=>"#/path/to/myfile.jpg");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://remote-site");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$output = curl_exec($ch);
curl_close($ch);
return $output;
just want to change "#/path/to/myfile.jpg" by browse button which passes it's value to php variable
I want to change this [[ $post = array("file_box"=>"#/path/to/myfile.jpg"); ]]
to something like that
[[ $post = array("file_box"=>"#".$variable_contains_file_path_from_browse_button); ]]
to prevent upload the file to middle server(host this script) in the temp path just from the client to the remote server directly
is there any solutions around this
thanks all for any help.
There are several questions in SO which deals with this
here are some of the links
uploading files using curl
Curl php file upload
And also google search strategy is http://bit.ly/PMUf2b
But still since you are asking for a browse button upload from front end, here is the complete set along with the tutor link
you can follow the tutor here which has both front end and php code
upload using curl
Here is the php code
$request_url = ‘http://www.example.com/test.php’;
$post_params['name'] = urlencode(’Test User’);
$post_params['file'] = ‘#’.'demo/testfile.txt’;
$post_params['submit'] = urlencode(’submit’);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
$result = curl_exec($ch);
curl_close($ch);
here is the html code
<form method=”post” action=”test.php” enctype=”multipart/form-data”>
<input type=”text” name=”name” value=”Test User” />
<input type=”file” name=”file” />
<input type=”submit” name=”submit” value=”submit” />
</form>

Categories