PHP send data to some other webpage - php

I want to have a script on one website and database on other website.
First website has 2 fields where they enter username and password. Then php posts username/password to other php file and that php does something and then somehow sends the data to my second website, where I insert username and password to MySql database.
So I can do everything except:
I have 2 variables in PHP file, and I want to send them to other webpage, which gets them with maybe $_POST ? Also posting should be automatic, so the script posts them itself not via button press. How to do it?
Is my question clear? I can explain.
Thanks.

Why can't your script on your dummy website retrieve the data via $_POST and then call the script from your real website?
http://davidwalsh.name/execute-http-post-php-curl
Check that out. This way your can POST to your real website from your dummy site's script, completely transparent to the user.
Hope that makes sense.

You can use the PHP cURL library to send these kinds of data requests.
Link: http://php.net/manual/en/book.curl.php

There are three obvious ways to do this:
1) Simple – keep the page hosted on site 2, but use an iframe on site 1 to embed it.
2) Post the form from site 1 to site 2 by setting the action attribute to a script on site 2.
3) Post the form on site 1 to a script on site 1, then use CURL to post it to the other site behind the scenes.

/**
* create request || application/json
* #param $method
* #param $url
* #param $args
* #param $isSentBody
* #param $cert
* #return resource
*/
function createRequest($method, $url, $args, $isSentBody, $cert = false)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($args));
if ($isSentBody) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($args));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
//'Authorization : Bearer ' . getAccessToken(),
));
}
if ($cert)
curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . $cert);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
try {
return curl_exec($ch);
} catch (Exception $e) {
throw $e;
}
}

Related

PHP: cURL or header - faster and better way to send cross domain data and redirect

I create one small API what collect contact form informations from one website and store in database on another website in managment application what I also build.
On website where is contact form is this code:
// collect all fields
$save = array(
'oAuth'=>'{KEY}',
'secret'=>'{SECRET-KEY}',
'category'=>'Category',
'name'=>'Jon Doe',
'email'=>'jon#doe.com',
'phone'=>'123 456 7890',
// ... etc. other fields
);
// made GET request
$fields=array();
foreach($save as $key=>$val){
$fields[]=$key."=".rawurlencode($val);
}
// Set cross domain URL
$url='http://api.mydomain.com/';
// Send informations in database
$cURL = curl_init();
curl_setopt($cURL,CURLOPT_URL, $url.'?'.join("&",$fields));
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($cURL, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($cURL, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($cURL, CURLOPT_TIMEOUT, 2);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$output=curl_exec($cURL);
curl_close($cURL);
usleep(1000);
// redirect
header("Location: http://somemysite.com/thank-you-page");
session_destroy();
exit;
My question is do to use cURL like now for this or to use header() function to send GET?
I ask because I not use output here and sometimes redirection start before cURL finish request.
What is faster way to send GET info and not lost data?
The redirection will not start before cURL finishes. What may happen is that cURL fails to load you remote page, and you don't handle that error. You should add something like this:
if($output === false || curl_getinfo($cURL, CURLINFO_HTTP_CODE) != 200) {
// Here you handle your error
}
If you are looking for an alternative to load remote webpages, you can set allow_url_fopen to true in your php.ini and then use this simple function instead of cURL:
$output = file_get_contents($url.'?'.join("&",$fields));

php+curl to send a post request with fields

trying to send post request to api, to get an image back.
example url:
https://providers.cloudsoftphone.com/lib/prettyqr/createQR.php?user=1003123&format=png&cloudid=asdasdasd&pass=123123123
the above url works fine in the browser,
the api doesnt care if the request is get/post,
result of my code is always 'invalid input'.
code:
$url='https://providers.cloudsoftphone.com/lib/prettyqr/createQR.php';
$u = rand();
$p = rand();
$fields = array(
'user'=> urlencode($u),
'pass'=> urlencode($p),
'format'=> urlencode('jpg'),
'cloudid' => urlencode('test')
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
on a side note: is there a way to debug the request in order to see what is being sent ?
The URL provided isn't working for POST request. Here is resulting screenshot (I tried using Advance Rest Client)
However Its working perfectly with GET method. So you can continue using GET request method to generate QR code.
I agree that GET isn't much secure compare to POST method but in your case while requesting from curl user won't get to know about such URL parameters (userid, password). Because curl request will be sending from your web server and not from client/user's browser.
Later you can just output the response image you got from the api.

how to POST data using Curl in php?

I have created webservices in restler framework and I am trying to insert data using curl in php from client lib that I have created.
api.php
/**
* Manually routed method. we can specify as many routes as we want
*
* #url POST addcomment/{token}/{email}/{comment}/{story_id}
*/
function addComment($token,$email,$comment,$story_id){
return $this->dp->insertComment($token,$email,$comment,$story_id);
}
for testing purpose from client : testing.php
$data_string = "token=900150983cd24fb0d6963f7d28e17f72&email=kamal#gmail.com&comment=commentusingcurl&story_id=2";
$ch = curl_init('http://localhost/Restler/public/examples/news/addcomment');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_HTTPHEADER,array("Content-Type : text","Content-lenght:".strlen($data_string)));
$result = curl_exec($ch);
but it's throwing 404. Please help.
//curl_setopt($ch, CURLOPT_HTTPHEADER,array("Content-Type : text","Content-lenght:".strlen($data_string)));
NOTE: Uncomment the line may be.
See the example of post data using curl.
function post($requestJson) {
$postUrl = $this->endpoint."?access_token=".$this->token;
//Get length of post
$postlength = strlen($requestJson);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$postUrl);
curl_setopt($ch,CURLOPT_POST,$postlength);
curl_setopt($ch,CURLOPT_POSTFIELDS,$requestJson);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
//close connection
curl_close($ch);
return $response;
}
Checkout some links for more information,
Execute a HTTP POST Using PHP CURL
Submitting a form post with PHP and CURL
Post to a URL Using cURL and PHP
Setup a simple cURL connection to POST data using PHP
Edit:
Restler always returning error 404 not found
may help you.
You should not be mapping all the parameters to URL,
/**
* Manually routed method. we can specify as many routes as we want
*
* #url POST addcomment/{token}/{email}/{comment}/{story_id}
*/
function addComment($token,$email,$comment,$story_id){
return $this->dp->insertComment($token,$email,$comment,$story_id);
}
By doing so the API can only accept URL such as
http://localhost/Restler/public/examples/news/addcomment/900150983cd24fb0d6963f7d28e17f72/kamal#gmail.com/commentusingcurl/2
Change you API method to
/**
* Manually routed method. we can specify as many routes as we want
*
* #url POST addcomment
*/
function addComment($token,$email,$comment,$story_id){
return $this->dp->insertComment($token,$email,$comment,$story_id);
}
Then your cURL example should work fine
$data_string = "token=900150983cd24fb0d6963f7d28e17f72&email=kamal#gmail.com&comment=commentusingcurl&story_id=2";
$ch = curl_init('http://localhost/Restler/public/examples/news/addcomment');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_HTTPHEADER,array("Content-Type : text","Content-lenght:".strlen($data_string)));
$result = curl_exec($ch);

Automatically filling out web forms and returning the resulting page

This is my first time posting here. I greatly appreciate any and all guidance on this subject.
I'm trying to make a program that automatically fills in web forms and submits the data, returning the resulting page to the program so it can continue to 'browse' the page, allowing it to recursively submit even more data.
The main problems I'm having are:
The 'submit' button is coded in Javascript, so I don't know where the form data goes when making the page request.
I want to fill in the forms using data from an Excel table, so I need to be able to access data from outside the page.
I need to be able to navigate the resulting page to continue to submit more data.
More specifically, I'm trying to first login to the Practice Mate website, navigate to 'Manage Patients', hit 'Add Patients', and fill in the proper forms and submit.
I'm filling in the forms from an Excel table thousands of rows long.
Sorry I can't be more clear on this without providing a username and password.
What I've been trying to do is use Javascript to make page requests from a page that retrieves information from the Excel document using PHP. I still can't seem to get anything to work with this method though.
I apologize for being a relative novice at this. Thanks in advance.
You can use PHP cURL to browse & submit forms to websites, but it does depend on how the website is setup. Most have security checks in place to prevent bots and can be tricky to get everything to work right.
I spent a little bit of time and came up with this login script. Without a valid username and password I can't verify that it is successful, but should do what you need. This short example first browses to the page to set any cookies and scrape a __VIEWSTATE value needed to submit the form. It then submits the form using the username/password you provide.
<?php
// Login information
$username = 'test';
$password = 'mypass';
$utcoffset = '-6';
$cookiefile = '/writable/directory/for/cookies.txt';
$client = new Client($cookiefile);
// Retrieve page first to store cookies
$page = $client -> get("https://pm.officeally.com/pm/login.aspx");
// scrape __VIEWSTATE value
$start = strpos($page, '__VIEWSTATE" value="') + 20;
$end = strpos($page, '"', $start);
$viewstate = substr($page, $start, $end - $start);
// Do our actual login
$form_data = array(
'__LASTFOCUS' => '',
'__EVENTTARGET' => '',
'__EVENTARGUMENT' => '',
'__VIEWSTATE' => $viewstate,
'hdnUtcOffset' => $utcoffset,
'Login1$UserName' => $username,
'Login1$Password' => $password,
'Login1$LoginButton' => 'Log In'
);
$page = $client -> get("https://pm.officeally.com/pm/login.aspx", $form_data);
// cURL wrapper class
class Login {
private $_cookiefile;
public function __construct($cookiefile) {
if (!is_writable($cookiefile)) {
throw new Exception('Cannot write cookiefile: ' . $cookiefile);
}
$this -> _cookiefile = $cookiefile;
}
public function get($url, $referer = 'http://www.google.com', $data = false) {
// Setup cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $referer);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this -> _cookiefile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this -> _cookiefile);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
// Is there data to post
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
return curl_exec($ch);
}
}
Well, I think the cURL will do the trick, the curl_init() handler is explicable enough. Still at the inception of the doc peruse, howbeit, good results are anticipated. Well, not too sure about the PHP flexibility of structures as that will mean a lot with cURL. Hope to find good luck down the line.

How to integrate a symfony website with whmcs

I'm trying to find a way to integrate my website, coded using Symfony with my billing system, WHMCS.
The first thing I tried was creating a new symfony module called whmcs and in that module, I was using ob_start/require_once/ob_get_contents to retreive the page but it kept resulting in a blank page, without any error in the logs or anywhere else. Since this was going to be a navigation nightmare anyway, I gave up on that idea.
My second idea was to take advantage of the WHMCS hooks system. So far, it worked except for one thing. I have no idea how to call my layout.php file. Here is my current code:
function getSymfonyLayout()
{
require_once($_SERVER['DOCUMENT_ROOT'].'/../config/ProjectConfiguration.class.php');
$configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'prod', true);
$context = sfContext::createInstance($configuration);
$context->getRequest()->setRelativeUrlRoot('');
$context->getInstance()->getConfiguration()->loadHelpers('Partial');
echo get_partial("global/header");
}
add_hook("ClientAreaPage",1,"getSymfonyLayout");
My issue here is that, while the header does load, there is no meta, no css, no javascript. Those settings are saved in my view.yml file and partials don't load that file.
I need to find a way to do something like echo get_layout("layout"); or echo get_methodaction("whmcs", "index");
It's probably something silly but I've been going thru wikis, forums and my symfony book and I just can't find the code I need to use.
Try to use curl
$url = 'your symfony url';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$data = curl_exec($ch);
echo $data;
The code above sends a curl request to the url $url
$query_string is the data you are going to post to the page if needed
$query_string = "";
foreach ($postfields AS $k => $v)
$query_string .= "$k=" . urlencode($v) . "&";
$query_string = trim($query_string, '&');
where $postfields is an array of the parameters to send
Additionally you can send a cross domain ajax request (if you're using jQuery you just set the $.ajax option dataType to jsonp) and that would load only the content part of the action (stylesheets and javascripts are not included)
In your action method, use:
$output = $this->getController()->getPresentationFor("module", "action");
This will render the output of the specified module and action into $output; see http://www.symfony-project.org/api/1_2/sfController#method_getpresentationfor for details

Categories