Submitting a form after processing in PHP - php

we have a form that grabs a whole bunch of details and then submits it to a mail program which send an email to certain people.
I need to put some extra processing between the form and mail program which checks info from a db and then changes the form data accordingly.
I thought I would be able to use curl for this but once I do the processing I need to submit the form and have things run the way they would as if the php wasn't there and it seems I can't do this with curl.
Question is can I do this with curl? Or is there a better way to go about this. (although I can do minor changes to both the mail and form they should stay the same as much as possible).
Edit: I'm not sure what information I can put in but I'll try and simplify it.
At the moment: form -> mail program
What I am trying to do: form -> php ->mail program
Mail program takes POST variables so what I want to do is grab the post variables, change some of them and then send them to the mail program and the previous process looks the same.

Use this:
http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/
<?php
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = #stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
Requires PHP5. Arrange all the data you need in PHP and stream out the post values.

make the PHP file to generate a form with the attribute filled with processed value. then you use Javascript to submit the form in the end.

Short answer was curl can do it for what I need, needed:
`curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);`

Related

PHP header not working in foreach

Somewhat strange situation here
$location = 'Location: http://localhost/pages';
//header($location); exit; works
$response->header($location)->send(); exit; //doesn't work
and the $response object's class
public headers = [];
public function header($string, $replace = true, $code = 200)
{
$this->headers[] = [
'string' => $string,
'replace' => $replace,
'code' => $code
];
return $this;
}
public function send()
{
foreach ($this->headers as $header) {
header($header['string'], $header['replace'], $header['code']);
}
}
The code works fine when using vanilla header but it doesn't when using the methods. Am I missing something here?
You are returning the Location header to the browser with a 200 status code.
For a redirection to actually occur, a 3xx response code should be sent instead (usually, a 302). A 200 response code simply means "OK, content follows". For a redirection to actually take place, a 3xx response code must be given.
Your code is ultimately calling
header('Location: http://localhost/pages', true, 200);
which isn't going to result in the browser redirecting you to the desired location.
PHP itself special-cases calls to header('Location: ...') and unless otherwise specified, uses a 302 instead of leaving the response code unchanged. You may want to adjust your code to do the same to keep the same behavior as PHP.
Also, important to note that, while every HTTP response only has one response code, header() allows you to set the response code each time you call it.
Thus, if you use your code like this:
$response
->header("Location: http://localhost/pages", true, 302)
->header("SomeOtherheader: value")
->send()
;
the 302 you intended to send will get replaced with the 200 that gets set in the next call to header().
Instead, what you should do is either separate the concept of setting the status code from actually setting the header content, e.g.:
$response
->header("Location: http://localhost/pages"))
->header("SomeOtherheader: value")
->responseCode(302)
->send()
;
or instead do what header() does and treat an unspecified response code as meaning, don't change the what's already been set:
public function header($string, $replace = true, $code = false) { ... }
false (or 0) passed on to PHP's header() will indicate that.

PHP Process page 404'ing when sending back a good JSON response

Have a sendmail.php page that i'm calling via ajax on a WordPress site.
This is the basics of how it looks:
if ($_POST) {
foreach($_POST as $field => $val) {
if ($val == '') {
$jsonReturn = ['success' => false, 'message' => 'Validation errors whilst processing your form, please go back and check.'];
echo json_encode($jsonReturn);
die();
}
}
if ($noErrors) { // set elsewhere, but works okay
/*
Send an email
*/
if ($mail->send()){
$jsonReturn = ['success' => true, 'message' => "Thank you, message sent."];
echo json_encode($jsonReturn);
}
}
} else {
header("Location: /");
die();
}
If the 'validation' fails at the top of the page, I get a 200 page back containing the JSON return of success false.
However, if I pass validation and send the email thens end the json return it 404's the page.
I tested also by putting:
$jsonReturn = ['success' => true, 'message' => "Thank you, message sent."];
echo json_encode($jsonReturn);
Directly under the first foreach and it also 404's. So im guessing there is something wrong with that?
Any help.
Sorted, the input field has a name of "name".
Changing that worked, speaking to a colleague it appears that WordPress has a certain set of field names reserved for its queries. In this case it was seeing the field name and sending the request off to another page which doesn't exist.
Im sure a person with more knowledge at WP can explain better, but for now if anyone comes across this issue just make sure to check the input names.

How to use zend_http_client or curl in right way

I'm using zend_http_client. What i want is to send a request to transfer(without redirecting) to another site and send number in field that I have and get the answer with info i need to use on my site. That's what i'm doing, but how to send my number to that field and submit it?
$url = 'http://gdeposylka.ru/';
$config = array(
'timeout' => 30
);
$client = new Zend_Http_Client($url, $config);
try {
$response = $client->request('GET');
if ($response->getStatus() == 200) {
$ctype = $response->getHeader('Content-type');
$body = $response->getBody();
$dom = new Zend_Dom_Query($body);
$results = $dom->query('limit');
$item->site_k = 1 + (int) $results->current()->textContent;
var_dump($response);
exit;
}
} catch (Zend_Http_Client_Adapter_Exception $e) {
}
Thanks and sorry for grammar mistakes.
Because there is a hash on the site you're trying to send a request, you probably wont be able to get this done. Hash mechanism makes it impossible to send request straight to the URL stated in action param of form tag. It's designed particulary to prevent such action you want to make. Still, since there is no captcha you can try web automation.
What you might find useful is ie. Selenium http://docs.seleniumhq.org/

Sent post request using Zend_Http_Client

I want to send a post request with a url redirect to a request page. Jest think request page currently use for handle submit form.
I tried the following code to my request page.
<?php
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Request come to the page\n";
fwrite($fh, $stringData);
if (isset($_POST)) {
$stringData = $_POST['user'];
fwrite($fh, $stringData);
}
fclose($fh);
echo 'page found';
I tried Zend_Http_Client to do that. This is my simple action.
public function indexAction()
{
$client = new Zend_Http_Client('http://localhost/test/test.php');
$client->setParameterPost(array('user' => 'dinuka'));
$client->setConfig(array('strictredirects' => true));
$response = $client->request(Zend_Http_Client::POST);
}
Now request send to the test.php. But not redirect to the http://localhost/test/test.php page. I want send request + redirect. I asked this question previously. But it closed as pure question. Please help me. I haven't good knowledge about http request. What is the strictredirects?
I think this might cover the basics of what you want:
<?php
class IndexController extends Zend_Controller_Action {
public function init() {
}
public function indexAction() {
//set form action to indexController nextAction
$form = My_Form();
$form->setAction('/index/next');
//asign form to view
$this->view->form = $form;
}
public function nextAction() {
//if form is posted and valid
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();
//Do some stuff
}
} else {
//if form not posted go to form in indexAction
$this->_forward('index');
}
}
}
it seems as though this the form of your question, but what you really want to know is how send post data in a redirect instead of get data, if I'm on the right track please
comment on how else we can change this to help you solve your problem.
public function indexAction()
{
$client = new Zend_Http_Client('http://localhost/test/test.php');
$client->setParameterPost(array('user' => 'dinuka'));
$client->setConfig(array('strictredirects' => true));
$response = $client->request(Zend_Http_Client::POST);
}
I get the idea that what you want with this piece of code is to submit a post request to this url and to redirect your browser there at the same time.
This should be possible and according to what I can find it is supposed to be as simple as $response->location but I can't make it work. ->location is supposed to be a header element but I can't find it. Maybe one of our other gurus can help.

Reddit API in php returns bad captcha for submitting story

Using php for Reddit api for submitting a story returns bad captcha as error.
I am able to login using the api and get usermod and captcha perfectly using api.
Ideally if the reddit_session cookie is passed it should post and not return bad captcha can someone shed me some light on this..
reference link:
https://github.com/reddit/reddit/wiki/API
<?php
$user = "";
$passwd = "";
$url = "http://www.reddit.com/api/login/".$user;
$r = new HttpRequest($url, HttpRequest::METH_POST);
$r->addPostFields(array('api_type' => 'json', 'user' => $user, 'passwd' => $passwd));
try {
$send = $r->send();
$userinfo = $send->getBody();
} catch (HttpException $ex) {
echo $ex;
}
$arr = json_decode($userinfo,true);
$modhash = $arr['json']['data']['modhash'];
$reddit_session = $arr['json']['data']['cookie'];
$post = array('uh'=>$modhash,
'kind'=>'link',
'url'=>'yourlink.com',
'sr'=>'funny',
'title'=>'omog-asdfasf',
'id'=>'newlink',
'r'=>'funnyier',
'renderstyle'=> 'html'
);
$url = "http://www.reddit.com/api/submit";
// Upvote RoboHobo's comment :)
// Add user cookie data
$r->addCookies(array("reddit_session" => $reddit_session));
// Set URL to vote
$r->setUrl($url);
// Add vote information, found at http://wiki.github.com/talklittle/reddit-is-fun/api-all-functions
$r->setPostFields($post);
// Send request blindly
try {
$userinfo = $r->send();
} catch (HttpException $ex) {
echo $ex;
}
pre($userinfo);
exit;
function pre($r){
echo "<pre />";
print_r($r);
}
?>
For anyone else that stumbled onto this question lately and is still having that issue:
The above issue was fixed and works correctly however if you created a new account for your reddit bot and try to submit a story you will recieve a bad_captcha error. New accounts have to submit captchas until they gain a certain amount of karma so this is the error you are seeing. Try the request with an older account and this should solve your problem.
From what I can tell, at the moment CAPTCHA is broken in the Reddit API. They originally were using an outdated PyCAPTCHA and were migrating to reCAPTCHA. Since then, there has been an issue with using api_type:json which has a work around and someone on github is currently working it. He also offered an explanation/solution:
Quite simply, the json (though not jquery) result should contain the captcha_id when a >captcha is required. By captcha_id I mean the part to complete a url like the followng: >http://www.reddit.com/captcha/(captcha_id).png
The use case I encountered is when trying to submit a story via the api using >api_type:json. I am nicely notified that my non-existent captcha is incorrect, however, I >then have to make a request to http://www.reddit.com/api/new_captcha in order to get the >captcha_id. This last round trip seems unnecessary.

Categories