Slack Incoming Webhook with PHP form - php

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

Related

Sendgrid Azure PHP

I am a newbie to php, azure, and sendgrid.
here is some code I found that I am trying to use for the html form.
<!-- BEGINNING OF CONTACT FORM -->
<div class="section-page-landing" id="contact">
<div class="inner-section">
<div class="contain">
<center><h2>Contact Me</h2>
<form class="contact" action="a_test_mailer_processor.php" method="post">
<p>Name:</p> <!-- Can choose to customize form.html inputs starting here as needed, but be sure to reference any changes in mailer.php post fields-->
<input type="text" name="name" />
<p>E-mail:</p>
<input type="text" name="email" />
<p>Subject:</p>
<input type="text" name="subject" />
<p>Message:</p>
<textarea name="message" syle="width: 45%; text-align: center;">Please leave a short message here</textarea></p>
<input class="send" type="submit" value="Send"> <!-- Send button-->
</form></center>
</div>
</div>
</div>
<!--end contact form-->
Here is the PHP I am trying to use
I updated the code as follows, swapping out my credentials and email address. No errors but still not working for me. Is there something else I can test?
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
var_dump(function_exists('curl_version'));
$url = 'https://api.sendgrid.com/';
$user = 'MYSENDGRIDUSERNAME';
$pass = 'MYSENDGRIDPASSWORD';
$params = array(
'api_user' => $user,
'api_key' => $pass,
'to' => 'MYEMAILADDRESS',
'subject' => 'testing from curl',
'html' => 'testing body',
'text' => 'testing body',
'from' => 'MYEMAILADDRESS',
);
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
// print everything out
print_r($response);
?>
And here are the errors I am getting.
bool(true)
Notice: Undefined variable: curl in D:\home\site\wwwroot\a_test_mailer_processor.php on line 36 Warning: curl_setopt() expects parameter 1 to be resource, null given in D:\home\site\wwwroot\a_test_mailer_processor.php on line 36
I tried simply removing line 36, curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); and the errors stopped but the form still did not get sent/received. Let me know what I am doing wrong.
As you hadn’t defined $curl before setting parameters using curl_setopt, and here is a code sample on SendGrid code examples page, please try it:
<?php
$url = 'https://api.sendgrid.com/';
$user = 'USERNAME';
$pass = 'PASSWORD';
$params = array(
'api_user' => $user,
'api_key' => $pass,
'to' => 'example3#sendgrid.com',
'subject' => 'testing from curl',
'html' => 'testing body',
'text' => 'testing body',
'from' => 'example#sendgrid.com',
);
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
// print everything out
print_r($response);
?>
--Update--
If you get error message as not defined constant CURL_SSLVERSION_TLSv1_2, we can directly set integer variable to CURLOPT_SSLVERSION.
We can find details in http://php.net/manual/en/function.curl-setopt.php:
One of CURL_SSLVERSION_DEFAULT (0), CURL_SSLVERSION_TLSv1 (1), CURL_SSLVERSION_SSLv2 (2), CURL_SSLVERSION_SSLv3 (3), CURL_SSLVERSION_TLSv1_0 (4), CURL_SSLVERSION_TLSv1_1 (5) or CURL_SSLVERSION_TLSv1_2 (6).
set as: curl_setopt($session, CURLOPT_SSLVERSION, 6);
And I have to set an additional option :
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
so that I can succeed to set my request to SendGrid Server.

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 send a data '\n' using curl post in 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

PHP string from HTTP post to another server

I will be using PHP further on this site, otherwise interested in learning more python to achieve these results.
I start with a search form that allows the user to enter in the 'findme' value which needs to be translated to a url. (for example purposes I will use findme = 12345678)
<form name="search" method="post" action="search.php" target="_blank" novalidate>
<input type="text" name="findme" />
<input type="submit" name="submit" value="submit" />
</form>
And then, I would like to retrieve a string within a HTTP post response page from a second server and store a url as a PHP string.
First I need to submit the form to another server, here is my attempt at search.php
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://another.server.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'surname' => 'surname',
'name' => 'name',
'findme' => 'findme'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
?>
The other server responds by serving a new page (ie. https://another.server.com/response.html), I want to then find the line containing the findme string, below is the format which the findme value of 12345678 would appear in a line of the response page. I want to save ABCDE as a string.
<tr class="special"><td>12345678......
Hopefully I can acheive with
<?php
file_put_contents("response.html", file_get_contents("https://another.server.com/response.html"));
$content = file_get_contents('response.html');
preg_match('~^(.*'.$findme.'.'</a>'.*)$~',$content,$line);
echo $line[1];
$findme_url = substr("abcdef", -37, 5);
echo $findme_url
?>
Updated with cURL and preg_match possible solutions, however the file put contents needs to be reading the response page from cURL
Yes, this is a perfect time to use curl.
$request = curl_init( 'https://another.server.com' );
curl_setopt( $request, CURLOPT_POST, true ); // use POST
$response = curl_exec( $request );
// catch errors
if( $response === false ) {
throw new Exception( curl_error($response) );
}
curl_close( $request );
// parse response...

Scraping Book Prices

I'm trying to write a scrape app, and I'm running in to problems. My PHP Curl code isn't pulling up the pages with the price of the books. It's returning me to the web root of the domain.
I'm trying to search the site by ISBN.
I've been bashing my head against the wall for days. Any help will be most appreciated!
Code:
<form method="post" for="new-search" name="SearchTerm" class='form-validate' id="SearchTerm" action="index.php">
<textarea rows="3" name="SearchTerm" id="SearchTerm" cols="40" class="validate-required error"></textarea><div class="error" id="SearchTerm-error">
<br>
<button class="search primary" type="submit">continue</button>
</form>
<?php
/*
echo("<pre>");print_r($_GET);echo("</pre>");
echo("<pre>");print_r($_POST);echo("</pre>");
*/
$isbn = $_POST['SearchTerm'];
$userAgent = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;rv:1.8.1.16) Gecko/20080702 Firefox/2.0.0.16';
$fields = array(
'url' => ("http://www.bookleberry.com/Search/SearchKeyword"),
'qurl' => ("http://www.bookleberry.com/Search/SearchKeyword/" . $_POST['SearchTerm']),
'SearchTerm' => ($_POST['SearchTerm']),
'Page' => ('1'),
'class' => ('textfield validate-required'),
'for' => ('new-search'),
'result-count' => ('1'),
'status' => 'success',
);
$SearchTerm = ($fields['SearchTerm']);
$url = ($fields['url']);
$Page = ($fields['Page']);
echo("<pre>");
print_r($fields);
echo("</pre>");
if ($isbn != NULL){
//open connection
$ch = curl_init($url);
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_HEADER, $userAgent);
curl_setopt($ch, CURLOPT_URL, $url);
echo "before curl_exec:<br>";
echo "curl_errno=". curl_errno($ch) ."<br>";
echo "curl_error=". curl_error($ch) ."<br>";
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "?SearchTerm=$SearchTerm");
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 9999999);
curl_setopt($ch,CURLOPT_HTTPHEADER,array (
"Accept: application/json"
));
$info = curl_getinfo($ch);
//execute post
$result = curl_exec($ch);
print $result;
print "<pre>\n";
print_r(curl_getinfo($ch)); // get error info
?>
Don't hurt your head, use it!
Install fiddler.
Do a request using the browser, look in fiddler to exactly what is posted. This includes all headers, cookies and form variables.
Do a post using your code, examine fiddler again
Compare the differences between the two and adjust your script.
Repeat.
Also it helps to install firebug. Using the copy Xpath, and putting that into a php DOM xpath query makes scraping fun and easy!

Categories