How to Send via email the Entire Request in PHP - php

I'm trying to create a php that sends via email all possible information about the request. Currently I'm using something like:
Email request php:
<?php
$remoteIp = $_SERVER['REMOTE_ADDR'];
$remoteHost = $_SERVER['HTTP_HOST'];
$remoteRef = $_SERVER['HTTP_REFERER'];
$remoteUrl = $_SERVER['REQUEST_URI'];
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$yourEmailAddress = "user#mail.com";
$emailSubject = "New request from: ".$remoteIp;
$emailContent = "The URL Request was made to: $remoteUrl
The request REFERER was: $remoteRef
The IP was $remoteIp
The User Agent was: $userAgent";
// send the message
mail($yourEmailAddress, $emailSubject, $emailContent);
?>
I like to add the Entire http request (GET OR POST) to the email been send so $emailContent it look like this:
$emailContent = "The URL Request was made to: $remoteUrl
The request REFERER was: $remoteRef
The IP was $remoteIp
The User Agent was: $userAgent"
The Full request was:
$fullrequest";
Looking around I found this https://gist.github.com/magnetikonline/650e30e485c0f91f2f40 which allows you to create file but I'm not sure on how to put it together with my PHP so it sends me an email with the request. (Creating the file is not necessary)
This PHP I like to integrate to my Email request php
<?php
// https://gist.github.com/magnetikonline/650e30e485c0f91f2f40
class DumpHTTPRequestToFile {
public function execute($targetFile) {
$data = sprintf(
"%s %s %s\n\nHTTP headers:\n",
$_SERVER['REQUEST_METHOD'],
$_SERVER['REQUEST_URI'],
$_SERVER['SERVER_PROTOCOL']
);
foreach ($this->getHeaderList() as $name => $value) {
$data .= $name . ': ' . $value . "\n";
}
$data .= "\nRequest body:\n";
file_put_contents(
$targetFile,
$data . file_get_contents('php://input') . "\n"
);
echo("Done!\n\n");
}
private function getHeaderList() {
$headerList = [];
foreach ($_SERVER as $name => $value) {
if (preg_match('/^HTTP_/',$name)) {
// convert HTTP_HEADER_NAME to Header-Name
$name = strtr(substr($name,5),'_',' ');
$name = ucwords(strtolower($name));
$name = strtr($name,' ','-');
// add to list
$headerList[$name] = $value;
}
}
return $headerList;
}
}
(new DumpHTTPRequestToFile)->execute('./dumprequest.txt');
Can any one help me to add class DumpHTTPRequestToFile to $fullrequest?

Something like
<?php
$message="The following request was made:\n";
foreach($_REQUEST as $k=>$v){
$message.=$k." : ".$v."\n\n";
}
mail($to_address, $subject, $message, $headers);
?>
Replace $_REQUEST with the super global of your choice. Or run similar loops across multiple superglobals ($_SERVER, etc) if $_REQUEST doesn't have all you want in it.

Related

IP Geolocation API Header request with php

I am trying to use ip-api.com (IP Geolocation) to retrieve usage limit.
1st - I've managed to use the api with php, but they don't give the usage limit (max 45/minute) in the response format.
They say that that information is returned in the HTTP header.
2nd - So I opened chrome developer network to see if I find the variables (X-R1 and X-Ttl) or whatever they called in the HTTP header but I don't see them there.
3rd - What I've managed to do is using php function (get_headers($url)), it works fine but when ever the script is run it counts as 2 requests for the API, so the usage limits always counts as 2.
How do I find them in the 2nd step or with some php function so I don't have to make another request like i did in the 3rd?
<?php
//1st request
function getClientIp(){
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
//ip from share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
//ip pass from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$clientIp = getClientIp();
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$clientIp));
if ($query['status'] == 'success'){
echo $query['city'];
echo '<br>';
echo $query['query'];
};
//2nd Request
echo '<br><br>';
$url = 'http://ip-api.com/php/'.$clientIp;
//print_r(get_headers($url));
print_r(get_headers($url, 1)['X-Rl']);
My solution in the end was just using the array variable $http_response_header.
Like this I can get the API response + header in a single request.
<?php
function getClientIp(){
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
//ip from share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
//ip pass from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
function parseHeaders( $headers )
{
$head = array();
foreach( $headers as $k=>$v )
{
$t = explode( ':', $v, 2 );
if( isset( $t[1] ) )
$head[ trim($t[0]) ] = trim( $t[1] );
else
{
$head[] = $v;
if( preg_match( "#HTTP/[0-9\.]+\s+([0-9]+)#",$v, $out ) )
$head['reponse_code'] = intval($out[1]);
}
}
return $head['X-Rl'];
}
//body request
$clientIp = getClientIp();
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$clientIp));
if ($query['status'] == 'success'){
echo $query['city'];
echo '<br>';
echo $query['query'];
}
//header request
echo '<br>Available requests: '.parseHeaders($http_response_header);

Remote mail() function

I am trying to use my localhost to connect to another server remotely and execute a mail function so i use get method to send the email and the subject
here is my localhost file :
<?php
for ($email=0; $email< $n_emails; $email++){
$urlsmtp = $link.'?email='.$destino.'&subject='.$tornado.'&msg='.$msgrand.'&name='.$_POST['naming'].'&from='.$_POST['localting'];
//this link is something like http://test.com/RemoteSmpt.php?email=test#mail.com &subject=test&msg=test&name=test&from=test
$urlsmtp = str_replace(" ", "%20", $urlsmtp);
$response = file_get_contents($urlsmtp);
}
?>
and the file RemoteSmpt.php which i will put it in the server contains this code :
<?php
if ( isset( $_GET['email']) && $_GET['subject'] && $_GET['msg'] && $_GET['name'] && $_GET['from']) {
$email = $_GET['email'];
$subject = $_GET['subject'];
$msg = $_GET['msg'];
$name = $_GET['name'];
$from = $_GET['from'];
$headers = 'From: '.$name.'<'.$from.'>\n';
$enviar = mail($email, $subject, $msg, $headers);
if ($enviar){
echo ('<font color="green"> -'. $email .' 0k -- With Subject : '.$subject.'</font><br>');
} else {
echo ('<font color="red"> -'. $email .' Not Sended -- With Subject : '.$subject.'</font><br>');
}
}else
{echo 'Invalid Data !<br>';}
?>
so after i upload the RemoteSmpt.php file and try this is what i got :
Warning: file_get_contents(http://...#mail.com&subject=tset&msg=test&name=test&from=test): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in Mylocalhost file !
Please any idea how to fix this code !
You need to properly encode special characters in the URL parameters, which can be done using urlencode().
You can use the http_build_query() function to build a query string from an associative array, and properly encode everything.
$params = http_build_query([
'email' => $destino,
'subject' => $tornado,
'msg' => $msgrand,
'name' => $_POST['naming'],
'from' => $_POST['localting']
]);
$urlsmtp = $link . '?' . $params;

Telegram bot send file and text PHP

I've got a basic bot set up that will send text back to the user, now I also want to send the user an audio message. But that I cannot do, here is the code.
I'm also using this https://github.com/Eleirbag89/TelegramBotPHP to send the audio
include("Telegram.php);
define('BOT_TOKEN', 'tokentoken');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
$telegram = new Telegram(BOT_TOKEN);
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
$reply = sendMessage($message);
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply;
file_get_contents($sendto);
function sendMessage(&$string) {
switch ($string) {
case "Hi":
$message = "Hi Back";
sendAudio();
break;
case "Bye":
$message = "Bye Bye";
break;
default:
$message = "Default";
}
return $message
}
func sendAudio() {
$sound = curl_file_create('sampleAudio.mp3', 'audio/mp3');
$newContent = array('chat_id' => $chatID, 'audio' => $sound);
$telegram->sendAudio($newContent);
}
Calling the code outside of the functions works, but than the user gets the file each time they type something. I experimenting so a bit of explanation would be great.
You have some errors:
First line " is unclosed
Last function, you've typed "func" instead of "function"
In sendAudio() you've used $chatID but you've to pass it as a parameter of sendAudio() or to set is as global.

Using Zend_Http_Client to send json POST

I'm trying to send a json object as a POST command using the following:
$uri = "http://amore-luce.com/product_create";
$product = $observer->getEvent()->getProduct();
$json = Mage::helper('core')->jsonEncode($product);
Mage::log(" Json={$json}", null,'product-updates.txt');
// new HTTP request to some HTTP address
$client = new Zend_Http_Client('http://amore-luce.com/product_create');
// set some parameters
$client->setParameterPost('product', $json);
// POST request
$response = $client->request(Zend_Http_Client::POST);
When I view the $json the data is there and all looks good - however the POST is not sending the json data. I'm capturing it using a simple email form that should send me the response:
<?php
$webhookContent = "";
$ref = "";
$webhook = fopen('php://input' , 'rb');
while (!feof($webhook)) {
$webhookContent .= fread($webhook, 4096);
}
fclose($webhook);
$headers = array();
foreach($_SERVER as $key => $value) {
if (substr($key, 0, 5) <> 'HTTP_') {
continue;
}
$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$header] = $value;
}
foreach ($headers as $header => $value) {
$ref .= "$header: $value <br />\n";
}
$post = file_get_contents('php://input');
$to = "address#my-email.com"; //the address the email is being sent to
$subject = "This is the subject"; //the subject of the message
$msg = "This is the message - Webhook content: ".$webhookContent." This is url: ".$ref; //the message of the email
mail($to, $subject, $msg, 'From: PHP Scriptv2 <noreply#domain.com>'); //send the email.
echo ($_SERVER['HTTP_REFERER']."<br>".$_SERVER['REQUEST_URI']);
?>
This page works with other json POST requests I've sent to it. I'm fairly new at sending POST requests so any help would be greatly appreciated.
Try change :
$client->setParameterPost('product', $json);
to :
$client->setHeaders('Content-type','application/json');
$client->setParameterPost('product', $json);
or use:
$client->setRawData($json, 'application/json');
So Update / Answer changing how I did it to these lines of code:
$uri = "http://requestb.in/p6p4syp6";
$product = $observer->getEvent()->getProduct();
$json = Mage::helper('core')->jsonEncode($product);
Mage::log(" Json={$json}", null,'product-updates.txt');
$client = new Zend_Http_Client($uri);
$client->setRawData($json, null)->request('POST');
Changing the SetRawData($json, null) was the bit - using SetRawDate($json, 'application/json') caused it to fail.
Thanks Voodoo417 - I'll also try your suggestion and see if that lets me set the correct type

Retrieve a Get Http request in php

I need to retrieve a get http request in php and store it in a variable.
I need to execute the following:
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials
I know this is simple. just not able to get my head around it.
$content = file_get_contents('https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials');
Within the Open Graph protocol page on Facebook, there is an example within the documentation coded using PHP: http://developers.facebook.com/docs/opengraph/
<?php
$ogurl = "INSERT_YOUR_OG_URL_HERE";
define(FACEBOOK_APP_ID, "YOUR_APP_ID_HERE");
define(FACEBOOK_SECRET, "YOUR_SECRET_KEY_HERE");
$mymessage = "Hello World!";
$access_token_url = "https://graph.facebook.com/oauth/access_token";
$parameters = "grant_type=client_credentials&client_id=" . FACEBOOK_APP_ID ."&client_secret=" . FACEBOOK_SECRET;
$access_token = file_get_contents($access_token_url . "?" . $parameters);
$apprequest_url = "https://graph.facebook.com/feed";
$parameters = "?" . $access_token . "&message=" . urlencode($mymessage) . "&id=" . $ogurl . "&method=post";
$myurl = $apprequest_url . $parameters;
$result = file_get_contents($myurl);
// output the post id
echo "post_id" . $result;
}
?>
The key line in actually making the call being:
$result = file_get_contents($myurl);
There is also a good amount of other information about the resulting object you get back there that would be good to take a look into.
Hope this is helpful.
if ($fp = fopen('https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials', 'r')) {
$content = '';
// keep reading until there's nothing left
while ($line = fread($fp, 1024)) {
$content .= $line;
}
// do something with the content here
// ...
} else {
// an error occured when trying to open the specified url
}
You mean something like
$client_id = $_GET['client_id'];
$client_secret = $_GET['client_secret'];
$grant_type = $_GET['grant_type'];
?
Or rather something like
$content = file_get_contents($url);
?
Use the following
$id = $_GET['client_id'];
$type = $_GET['grant_type'];
$secret = $_GET['client_secret'];
Hope this helps you

Categories