Http post request using fopen - php

In the first file - the file I execute I have the following content:
<?php
$name = "Julia";
$article = "I like papers";
$url = "http://domain.com/process.php";
$param = array('http' => array(
'method' => 'POST',
'content' => $article
));
$mad = #stream_context_create($param);
$fp = #fopen($url, 'rb', false, $mad);
$response = #stream_get_contents($fp);
echo $response;
?>
in the second file http://domain.com/process.php I have this:
<?php
$name = $_POST["name"];
$article = $_POST["content"];
$article = $_POST["article"];
echo $article;
echo $name;
echo "Hello there</br>:\n";
?>
The output that I get is just:
"Hello there"
So what is wrong, how do I pass the values $article and $name via the request and how to I extract them in the file process.php?

You got it wrong at the content part, use http_build_query() to build the POST query.
$param = array( 'http' => array('method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query($data)
));
And your post parameters should be like below, where the input name as key
$data['name'] = 'Julia';
$data['article'] = 'I like papers';
Personally, I will use curl.

Related

use a random proxy in a php function without curl

function ID($name)
{
$name = trim($name);
$url = "$name";
$postdata = http_build_query(
array(
'url' => $url,
'check' => 'Lookup'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://www.website.net/search?='.$url.'');
$regex = '/og:image"\s*content="([^"]+)"/';
preg_match($regex, $result, $matches)
return($matches[1]);
This function is working fine, now i have 3 paid proxies with the same user:pass, and i want to randomize proxy every time the function is called so my website never use it's own Ip adress. I saw a lot of stuff about CURL I don't want to use that
I found this code but i don't know how to add it to the actual code:
$filename = getcwd() . "/proxies.json";
$file = fopen($filename, "r");
if ($file == false) { echo ("Error in opening file");
exit();
}
$filesize = filesize($filename);
$filetext = fread($file, $filesize);
fclose($file);
$proxies = json_decode($filetext, true);
$rand_proxy = array_rand($proxies);
$proxy = $proxies[$rand_proxy]["url"];
$proxyauth = $proxies[$rand_proxy]["auth"];
and this is the proxies.json file:
[{"url":"XX.XX.XXX.YY:80","auth":"user:pass"},
{"url":"XX.YY.XX.YYY:80","auth":"user:pass"},
{"url":"XX.XX.YYY.X:80","auth":"user:pass"}]

PHP Posting data to another php file hosted in a remote server using file_get_contents

I have access to 3 different remote servers. They all host the same php file, it's named processing.php.
And in a different server I have 3 pages :
index.html : that contains a form with POST method that send data to forward.php
forward.php : that forward the form values to processing.php on the other servers
processing.php : Display the posted data
The Problem : the code in processing.php is not executed and the returned result is a plain text of the source code of processing.php!!
forward.php :
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
rtrim($_POST['listserver'],"-");
$listServer = explode("-",$_POST['listserver']);
foreach ($listServer as $server){
if(!empty($server)){
$url = 'http://'.$server.'/processing.php';
$data = array('field1' => $field1, 'field2' => $field2);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
echo "You can't ";
}else{
echo ('result : '.$result);
}
}
}
Processing.php
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
$result = $field1+$field2;
$myFile = "files/result.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $result);
fclose($fh);
But in all the servers, result.txt is empty!!
Thanx to #MarkusZeller suggestion, I managed to get it work using cURL.
This thread was very helpful, thank you Stack Over Flow community !

Receive PHP code with an POST request

I need to send a POST request to another file called global.php, for this I try this code below:
$url = 'global.php';
$data = array('stack' => 'overflow');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
This is the global.php file that should process the request:
if(isset($_POST['stack'])){
echo 'exists';
}else{
echo 'error';
}
The problem is that instead of the command var_dump ($ result); show exists, it shows the PHP code? how can I solve this problem?
And why when I try to do the same thing using ajax it returns me the text exists and not PHP code?
You should use full url, to process php file through server.
$url = 'http://YOURURL.com/global.php';
AJAX call is made from browser, to absolute URL, thats why You are getting desired response.

Issue with rest services

I am facing one issue while i am calling rest service using file_get_contents
its working fine when response is success but its giving blank result in case of failure or error response. while when I am checking it using rest client its giving me correct response for both case whether its success or failure.
can anyone please help? below is the source code which i have written.
<?php
$postdata = array(
'email' => $email,
'password' => $password
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => $headers = array(
'Accept: application/json',
'Content-Type: application/json'
)
//'content' => $postdata
)
);
$context = stream_context_create($opts);
//echo "<pre>"; print_r($context); exit;
$url = WS_URL . "issavvy-api/account/login?" . http_build_query($postdata);
$result = file_get_contents($url, false, $context);
echo "<pre>";
print_r(json_decode($result));
exit;
?>
If you wanna stick with file_get_contents use $http_response_header and parse it
You can use this
function httpStatusCode($headers){
$match = null;
$pattern = "!(?P<version>HTTP/\d+\.\d+) (?P<code>\d+) (?P<status>.*)!";
foreach($headers as $header){
if(preg_match($pattern, $header, $match)){
return $match['code'];
}
}
return null;
}
To check if request was successful run
$success = (200 == httpStatusCode($http_response_header));
https://eval.in/145906

Restful API for CakePHP 2

I am creating a Restful WebService with CakePHP 2 however, i am getting 500 Internal Server Error since i am not able to capture Post Data. The Rest Server is as below:
App::import ( 'Vendor', 'ExchangeFunctions', array ('file'=> 'exchange/exchangefunctions.php'));
class ExchangeController extends AppController
{
public $components = array('RequestHandler');
public
function index()
{
$exchange = new ExchangeFunctions();
$data = $this->request->data('json_decode');
$exchange->username = $_POST['username'];
$exchange->password = $_POST['password'];
$emailList = $exchange->listEmails();
$response = new stdClass();
$response->emailList = $emailList;
foreach($emailList->messages as $listid => $email)
{
$tempEmail = $exchange->getEmailContent(
$email->Id,
$email->ChangeKey,
TRUE,
$_POST['attachmentPath']
);
$response->emails[$tempEmail['attachmentCode']] = $tempEmail;
}
$this->set('response', $response);
$this->set('_serialize','response');
}
}
and the client goes as:
class ApitestController extends AppController
{
Public function index()
{
$this->layout = 'ajax';
$jRequestURLPrefix = 'http://localhost/EWSApi/';
$postUrl = $jRequestURLPrefix."exchange/index.json";
$postData = array(
'username' => 'username',
'password' => 'password',
'attachmentPath'=> $_SERVER['DOCUMENT_ROOT'] . $this->base . DIRECTORY_SEPARATOR . 'emailDownloads' . DIRECTORY_SEPARATOR . 'attachments'
);
$postData = json_encode($postData);
pr($postData);
$ch = curl_init( $postUrl );
$options = array(
CURLOPT_RETURNTRANSFER=> true,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData)
),
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_POSTFIELDS => $postData,
);
curl_setopt_array( $ch, $options );
$jsonString = curl_exec($ch);
curl_close($ch);
$data = json_decode($jsonString, FALSE);
echo $jsonString;
}
}
Not sure where i am messing up! Please help!
Ok, after a second look there are some more suspicious things. As already mentioned, your CURL request uses GET instead of POST.
$options = array(
...
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $postData,
);
Another thing is that you are encoding the POST data for your CURL call to JSON, but then you are trying to access it on the other side using $_POST, however there won't be anything, POST data would have to be key/value query string formatted in order to appear in $_POST. You have to read php://input instead, which may be what you were trying to do with
$data = $this->request->data('json_decode');
However you must use CakeRequest::input() for that purpose, and of course you must then use the $data variable instead of $_POST
$data = $this->request->input('json_decode');
$exchange->username = $data['username'];
$exchange->password = $data['password'];
....
$tempEmail = $exchange->getEmailContent(
$email->Id,
$email->ChangeKey,
TRUE,
$data['attachmentPath']
);
Also make double sure that your CURL request looks like expected:
$options = array(
...
CURLOPT_POSTFIELDS => $postData,
CURLINFO_HEADER_OUT => true // supported as of PHP 5.1.3
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo '<pre>';
print_r($info);
echo '</pre>';

Categories