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...
Related
I can't figure out why the server's response doesn't allow me to validate the recaptcha. My PHP code is:
$captcha = $_POST['g-recaptcha-response'];
$secret = "my key";
$postdata = "secret=".$secret."&response=".$captcha;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
$out = json_decode($server_output);
curl_close($ch);
if($out->success == true){/*make stuff*/} /* when the user clicks, $out->success is not true! */
My HTML form is quite ordinary.
<form method="POST" id="form">
<!-- inputs -->
<div class="g-recaptcha" data-sitekey="my key" style="margin:10px"></div>
<input type="submit" name="submit" value="Valider">
</form>
I know the problem must be really silly. I've found a workaround which is, instead of checking if $out->success==true, checking if strlen($captcha) > 1. But I'm pretty sure it's not very likely to block robots... Any idea? Thanks...
EDIT: I just ran a ZAP attack on my website (ZED attack proxy, a security tool from OWASP foundation). It fails completing the sign-up form (before that, it was able to create 100 users in less than a minute!). So this means that some robots will blocked. I still want to get it done properly though...
Can you try to send your data as an array like that :
$postdata = array(
'secret' => $secret,
'response' => $captcha
);
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
I have PHP API codeblocks from a data extraction tool/website (http://import.io) in the form below. I want to have a search box that returns the result from not one, but multiple of these "connector" codeblocks (they are called connectors because they connect your search queries with the results piped through import.io, presumably).
I'm a noob at PHP, so I'm not sure how to go about this.
<?php
$userGuid = "kjnjkn-32d2-4b1c-a9c5-erferferferferf";
$apiKey = "APIKEY";
function query($connectorGuid, $input, $userGuid, $apiKey) {
$url = "https://api.import.io/store/connector/" . $connectorGuid . "/_query?_user=" . urlencode($userGuid) . "&_apikey=" . urlencode($apiKey);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("input" => $input)));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
// Query for tile WEBSEARCH
$result = query("98c9bac2-e623-4e31-8a3e-erferferferf", array(
"search_query" => "term1",
), $userGuid, $apiKey);
var_dump($result);
// Query for tile WEBSEARCH
$result = query("98c9bac2-e623-4e31-8a3e-bferfreferfe", array(
"search_query" => "term2",
), $userGuid, $apiKey);
var_dump($result);
I think the first thing you will want is some kind of HTML form that POSTs to your PHP script. I haven't tested this but something like it will do:
<form action="path/to/myscript.php" method="POST">
<input type="text" name="search" placeholder="query">
<input type="submit" value="Search">
</form>
This will issue an HTTP POST request to your script (call it myscript.php or change the HTML to match your filename) with the input term in the $_POST data array.
This means you can get the search term typed in using $_POST["search"], and use it as the input to the query:
$result = query("98c9bac2-e623-4e31-8a3e-erferferferf", array(
"search_query" => $_POST["search"],
), $userGuid, $apiKey);
var_dump($result);
Notes:
There is zero validation on this - you will want to sanitize the form input if you put this in production anywhere
There is an interesting guide on the PHP site, which says similar things.
If you do anything more complex than this you will almost certainly be better to use a fully-fledged client library for a language other than PHP - there are more listed on this page.
Full disclosure, I work for import.io (hope this has helped!)
I would like to have a form on a page that after submitting sends the person to a thank you page, but I would like to send the data from the form to another .php file on a remote server. I've used the action to send the info as a post directly to the remote server and it works just fine, but for security I don't want the location on the remote to be seen in any code. The solution I was working on is after a submit, the form action would send you to a .php that would send the post info to the remote via cURL. Which is where it goes down hill. I'm not bent on using cURL, just the only thing I read that sounded like it could work. So to recap if that came out confusing; person hits submit, they go to a .php that says "your a wonderful person," but it also sends the info in the post to a remote server while only showing the location of the remote in the php so it's not visible in code.
My html that has the form on it:
<form action="landing.php" method="post">
Client:<input name="client" type="text" size="20" maxlength="30">
<br />
Test1:<input name="test1" type="text" size="20" maxlength="30">
<br />
Test2:<input name="test2" type="text" size="20" maxlength="30">
<br />
<input type="submit" name="submit" value="Submit" />
</form>
Which goes to this page:
<?php
$ch = curl_init();
$data = array('client' => 'Foo', 'test1' => '123', 'test2' => '987');
curl_setopt($ch, CURLOPT_URL, 'http://MyServer/test.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
?>
Thank You etc.
And it doesn't work... I'm new to cURL so that may be horribly off for what I'm trying to do. My main thing is to hide the remote's location.
Am I on the right track?
Is this possible?
Check whether Curl is enable or Not
After posting, try to grab the output from Curl
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/path/to/form");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'foo' => 'foo foo foo',
'bar' => 'bar bar bar',
'baz' => 'baz baz baz'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
?>
I think there is one more alternative to :-
Use can store your data on session.
Then redirect to the page.
Hope this information will help you.
Or there is one more solution, you can use below code to redirect to the new page:
<?php
header("Status: 301 Moved Permanently");
header("Location:http://MyServer/test.php?". $_SERVER['QUERY_STRING']);
exit;
?>
Thanks and Regards
Pushkar
First of go through curl. Refer this link for posting data.
As you said "My main thing is to hide the remote's location", you can use database in this situation. save your remote locations in one of table and retrieve it whenever you want.
Try this to solve your current issue.
<?php
//set POST variables
$url = 'http://MyServer/test.php';
$data = array('client' => 'Foo', 'test1' => '123', 'test2' => '987');
//url-ify the data for the POST
foreach($data as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
?>
I guess you need to POSTFIELDS as a string like this
$data = 'client=Foo&test1=123&test2=987'
to get the return data add
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$returnText = curl_exec($ch);
$data= curl_getinfo($ch);
if you wanna use it as an array please read this
The full data to post in a HTTP "POST" operation. To post a file,
prepend a filename with # and use the full path. The filetype can be
explicitly specified by following the filename with the type in the
format ';type=mimetype'. This parameter can either be passed as a
urlencoded string like 'para1=val1¶2=val2&...' or as an array with
the field name as key and field data as value. If value is an array,
the Content-Type header will be set to multipart/form-data. As of PHP
5.2.0, value must be an array if files are passed to this option with the # prefix.
Im trying to shorten a url using ggole api's.Here is my php code .It gives a blank page when i load
<?php
define('GOOGLE_API_KEY', 'GoogleApiKey');
define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
?>
My html file:
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<FORM NAME ="form1" METHOD =" " ACTION = "shortner.php">
<INPUT TYPE = "TEXT" VALUE ="Enter a url to shorten" name="url">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Shorten">
</FORM>
</body>
</html
I think I have found a solution to your problem. Since you are connecting to a URL that uses SSL, you will need to add some extra parameters to your code for CURL. Try the following instead:
<?php
define('GOOGLE_API_KEY', 'GoogleApiKey');
define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
// extra parameters for working with SSL URL's; eypeon (stackoverflow)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
?>
I think it's coming form your html. You didn't put the form methode, so it send data by get.
And you show something only if you have post.
Try to do in the form method="post"
Edit
Bobby the main problem is that you don't have one problem but several in this code.
First if you don't do
<FORM NAME="form1" METHOD="POST" ACTION="shortner.php">
the if (isset($_POST['url'])) will never return true, because the variable send by the form will be GET (or do a if (isset($_GET['url']))).
Secondly you call the function with { $response = shortenUrl('$url'); }. Here you're not sending the url value but the string '$url'. So your variable $longUrl is always '$url'.
Thirdly you don't use sprintf like you should.
echo sprintf(
$response['longUrl'],
$response['id']
);
Sprintf need to take a string format:
echo sprintf("%s %s" // for example
$response['longUrl'],
$response['id']
);
But do you know that you can do directly
echo $response['longUrl'] . ' ' . $response['id'];
You can concatenate string directly with . in php
curl_exec() returns boolean false if something didn't go right with the request. You're not testing for that and assuming it worked. Change your code to:
$result = curl_exec($ch);
if ($result === FALSE) {
die("Curl error: " . curl_error($ch);
}
As well, you need to specify CURLOPT_RETURNTRANSFER - by default curl will write anything it receives to the PHP output. With this option set, it'll return the transfer to your $result variable, instead of writing it out.
You need to set CURLOPT_RETURNTRANSFER option in your code
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
// Create cURL
$apiURL = https://www.googleapis.com/urlshortener/v1/url?key=gfskdgsd
$ch = curl_init();
// If we're shortening a URL...
if($shorten) {
curl_setopt($ch,CURLOPT_URL,$apiURL);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);