I need to post to a URL and I am doing this with curl. But the problem is with the HTML content I am posting. I am using this page which I am requesting to send an html email. So it will have inline styles. When I urlencode() or rawurlenocde() these style attribute is stripped. So the mail will not look correct. How can I avoid this and post the HTML as it is ?
This is my code :
$mail_url = "to=".$email->uEmail;
$mail_url .= "&from=info#domain.com";
$mail_url .= "&subject=".$email_campaign[0]->email_subject;
$mail_url .= "&type=signleOffer";
$mail_url .= "&html=".rawurlencode($email_campaign[0]->email_content);
//open curl request to send the mail
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count(5));
curl_setopt($ch,CURLOPT_POSTFIELDS,$mail_url);
//execute post
$result = curl_exec($ch);
Here is an example, use http_build_query() to build your post data from an array of values:
<?php
//Receiver debug
if($_SERVER['REQUEST_METHOD']=='POST'){
file_put_contents('test.POST.values.txt',print_r($_POST,true));
/*
Array
(
[to] => example#example.com
[from] => info#domain.com
[subject] => subject
[type] => signleOffer
[html] =>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Mail Template</title>
<style>.yada{color:green;}</style>
</head>
<body>
<p style="color:red">Red</p>
<p class="yada">Green</p>
</body>
</html>
)
*/
die;
}
$curl_to_post_parameters = array(
'to'=>'example#example.com',
'from'=>'info#domain.com',
'subject'=>'subject',
'type'=>'signleOffer',
'html'=>'
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Mail Template</title>
<style>.yada{color:green;}</style>
</head>
<body>
<p style="color:red">Red</p>
<p class="yada">Green</p>
</body>
</html>
'
);
$curl_options = array(
CURLOPT_URL => "http://localhost/test.php",
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query( $curl_to_post_parameters ), //<<<
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false
);
$curl = curl_init();
curl_setopt_array($curl, $curl_options);
$result = curl_exec($curl);
curl_close($curl);
?>
Do a POST as described in this post:
Passing $_POST values with cURL
It should solve your problem.
Related
When I try to access moz api using below code
$accessID = 'mozscape-key';
$secretKey = 'secert key';
// Set your expires times for several minutes into the future.
// An expires time excessively far in the future will not be honored by the Mozscape API.
$expires = time() + 300;
// Put each parameter on a new line.
$stringToSign = $accessID."\n".$expires;
// Get the "raw" or binary output of the hmac hash.
$binarySignature = hash_hmac('sha1', $stringToSign, $secretKey, true);
// Base64-encode it and then url-encode that.
$urlSafeSignature = urlencode(base64_encode($binarySignature));
// Specify the URL that you want link metrics for.
$objectURL = "www.seomoz.org";
// Add up all the bit flags you want returned.
// Learn more here: https://moz.com/help/guides/moz-api/mozscape/api-reference/url-metrics
$cols = "103079215108";
// Put it all together and you get your request URL.
// This example uses the Mozscape URL Metrics API.
$requestUrl = "http://lsapi.seomoz.com/linkscape/url-metrics/".urlencode($objectURL)."?Cols=".$cols."&AccessID=".$accessID."&Expires=".$expires."&Signature=".$urlSafeSignature;
echo $requestUrl;
die;
// Use Curl to send off your request.
$options = array(
CURLOPT_RETURNTRANSFER => true
);
$ch = curl_init($requestUrl);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
$f = fopen('tte.txt','a');
fwrite($f,$content);
fclose($f);
print_r($content);
The out it return is below
<html style="height:100%">
<head>
<meta content="NOINDEX, NOFOLLOW" name="ROBOTS">
<meta content="telephone=no" name="format-detection">
<meta content="initial-scale=1.0" name="viewport">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<title></title>
</head>
<body style="margin:0px;height:100%">
<iframe frameborder="0" height="100%" marginheight="0px" marginwidth="0px"
src="/_Incapsula_Resource?CWUDNSAI=9&xinfo=10-113037580-0%200NNN%20RT(1470041335360%200)%20q(0%20-1%20-1%20-1)%20r(0%20-1)%20B12(8,811001,0)%20U5&incident_id=220010400174850153-812164000562037002&edet=12&cinfo=08000000"
width="100%">Request unsuccessful. Incapsula incident ID:
220010400174850153-812164000562037002</iframe>
<meta content="NOINDEX, NOFOLLOW" name="ROBOTS">
<meta content="telephone=no" name="format-detection">
<meta content="initial-scale=1.0" name="viewport">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<iframe frameborder="0" height="100%" marginheight="0px" marginwidth="0px"
src="/_Incapsula_Resource?CWUDNSAI=9&xinfo=6-31536099-0%200NNN%20RT(1470041496215%200)%20q(0%20-1%20-1%20-1)%20r(0%20-1)%20B12(8,811001,0)%20U5&incident_id=220010400174850153-224923142338658566&edet=12&cinfo=08000000"
width="100%">Request unsuccessful. Incapsula incident ID:
220010400174850153-224923142338658566</iframe>
</body>
</html>
Seems like incapsula is treating request as robot. Can anyone please help me how I can fix it.
If you said you are using the $requestUrl to a GET (in browser) it works fine, try combining your options array.
It should look like this:
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $requestUrl,
CURLOPT_USERAGENT => 'Maybe You Need Agent?'
));
Note about agent (taken from web):
cURL is a behemoth, and has many many possibilities. Some sites might
only serve pages to some user agents, and when working with APIs, some
might request you send a specfici user agent, this is something to be
aware of.
Also worth checking - you have ID of failture from Incapsula - 220010400174850153-224923142338658566
Can you check the logs and see what is there?
Trying to parse an rss feed, this code works if I use a feed that doesn't need auth. So I assume it must be a curl issue. Please help, thanks.
<?php
$curl = curl_init();
curl_setopt_array($curl, Array(
CURLOPT_URL => 'http://insite.unthsc.edu/dailynews/feed/',
CURLOPT_USERAGENT => 'spider',
CURLOPT_TIMEOUT => 120,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_ENCODING => 'UTF-8'
));
$data = curl_exec($curl);
curl_close($curl);
$xml = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
//die('<pre>' . print_r($xml], TRUE) . '</pre>');
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>
<?php foreach ($xml->channel->item as $item) {
$creator = $item->children('dc', TRUE);
echo '<h2>' . $item->title . '</h2>';
echo '<h2>' . $item->category . '</h2>';
}
?>
</body>
</html>
I am using Google Contact API V3 with OAuth 2.0 to retrieve the contacts from Google Account, I am getting a OAuth Token from a child window using jQuery, and after post that token to another file which should get the User's Contacts, but when I pass the token to get the contacts from Google, but it gives an error "Warning: file_get_contents(https://www.google.com/m8/feeds/contacts/default/full&oauth_token=[token]) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 401 Authorization required in ...\getContacts.php on line 7"
Here is my code for reference:
In my index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="js/jquery-1.8.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var windowSizeArray = [ "width=200,height=200",
"width=300,height=400,scrollbars=yes" ];
$(document).ready(function(){
$('#newWindow').click(function (event){
var url = $(this).attr("href");
var windowName = "popUp";//$(this).attr("name");
var windowSize = windowSizeArray[ $(this).attr("rel") ];
window.open(url, windowName, windowSize);
event.preventDefault();
});
});
function getContacts(accessToken){
$.post("getContacts.php?token="+accessToken,function(data){
$("#contacts").html(data);
});
}
</script>
</head>
<body>
Click Here! to import your contact.
<div id="contacts"></div>
in my childWindow.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery-1.8.1.min.js"></script>
</head>
<body>
<?php
$authcode= $_GET["code"];
$clientid='My Client ID';
$clientsecret='My Client Secret';
$redirecturi='http://localhost/googleContacts/validate.php';
$fields=array(
'code'=> urlencode($authcode),
'client_id'=> urlencode($clientid),
'client_secret'=> urlencode($clientsecret),
'redirect_uri'=> urlencode($redirecturi),
'grant_type'=> urlencode('authorization_code')
);
//url-ify the data for the POST
$fields_string='';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string=rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch,CURLOPT_POST,5);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//to trust any ssl certificates
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
//extracting access_token from response string
$response= json_decode($result);
$accesstoken= $response->access_token;
//echo "<span>".$accesstoken."</span><hr>";
?>
<script type="text/javascript">
$(document).ready(function() {
window.opener.getContacts("<?php echo $accesstoken; ?>");
window.close();
});
</script>
And finally in my getContacts.php:
<?php
$accesstoken = $_REQUEST['token'];
//passing accesstoken to obtain contact details
$xmlresponse= file_get_contents('https://www.google.com/m8/feeds/contacts/default/full&oauth_token='.$accesstoken);
//reading xml using SimpleXML
$xml= new SimpleXMLElement($xmlresponse);
foreach($xml->entry as $content){
$nameEmail = "";
if(!empty($content->title)){
$nameEmail .= "<span style=\"text-decoration:underline;\">".$content->title."</span>: ";
}
$gd = $content->children('http://schemas.google.com/g/2005');
if($gd){
$nameEmail .= $gd->attributes()->address."<hr>";
echo $nameEmail;
}else{
echo $nameEmail."<hr>";
}
}
?>
Please tell me where is the mistake. Thanks in advance
To allow https for file_get_contents() you should have enabled the php extension php_openssl.dll.
Make sure that in your php.ini you have this lines:
extension=php_openssl.dll
allow_url_fopen = On
I have this php file that gets the points (id,name,geolocation) of london.The problem is that I get the correct results as a json format but when i decode it and trying to get to contains array of results I get an error.How i can get the data from '/location/location/contains' attribute?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>search</title>
</head>
<body>
<?php
function freebasequery ($fid){
$query = array(array('id' => $fid, '/location/location/contains'=>array(array('id'=>NULL,'name' => NULL,'/location/location/geolocation' =>array(array('/location/geocode/longitude' =>NULL,'/location/geocode/latitude' => NULL))))));
$query_envelope = array('query' => $query);
$service_url = 'http://api.freebase.com/api/service/mqlread';
$url = $service_url . '?query=' . urlencode(json_encode($query_envelope));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$points=freebasequery('/en/london');
//echo $points;
$results=json_decode($points)->result;
foreach($results as $poi){
echo $poi->id;
$contains="/location/location/contains";
$poisarray=$poi->$contains;
foreach($poisarray as $point){
echo $point->id;
}
}
?>
</body>
</html>
The error it was on json_decode ( It requires to have a true) the solution is:
json_decode($points,true);
and then I can access the data array I want like this:
$results["result"][0]["/location/location/contains"];
I spent a lot of time trying to register an achievement with facebook using grahp API, but
I am always getting this :
{"error":{"type":"OAuthException","message":"(#2) Object at achievement URL is not of type game.achievement"}}
The code is :
$achievementUrl = 'http://www.dappergames.com/test.html';
$url = 'https://graph.facebook.com/' . $appID . '/achievements?achievement=' .
$achievementUrl . '&display_order=' . $order . '&access_token=' . $accessToken . '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);
print_r($data);
Any help will be greatly appreciated.
Thanks
Looking at your test, you're missing the most important tag, og:url.
Facebook uses that tag to find the location of where to parse the information, I was having a similar problem on adding achievements to my app until I figured that out. Here's how mine looks. Mine passes the debugger and works currently on Facebook.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>Game Loader</title>
<meta property="og:type" content="game.achievement"/>
<meta property="og:title" content="Game Loader"/>
<meta property="og:url" content="FULL LINK TO THIS PAGE"/>
<meta property="og:description" content="You loaded the gam!e"/>
<meta property="og:image" content="Link to 50x50 image"/>
<meta property="og:points" content="10"/>
<meta property="fb:app_id" content="YOUR_APP_ID"/>
</head>
<body>
</body>
</html>
After updating your HTML to this, run it through the debugger linked above so that it is updated on Facebook's end (and to see if you receive any warnings) and then create it and give it to users.
Here's how I created it:
curl -D "achievement=[URL TO ACHIEVEMENT]&access_token=[APPLICATION ACCESS TOKEN]" https://graph.facebook.com/APP_ID/achievements
and I then rewarded it to users using the Facebook Javascript API on my canvas application like so:
FB.api('/'+user_id+'/achievements', 'POST', { 'access_token': [APPLICATION ACCESS TOKEN], 'achievement':[FULL URL]},
function(response) {
if(console)
console.log(response);
});
Make sure that you have the correct Open Graph meta tags in your achievement URL $achievementUrl:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#">
<head>
<title>ACHIEVEMENT_TITLE</title>
<meta property="og:type" content="game.achievement"/>
<meta property="og:url" content="URL_FOR_THIS_PAGE"/>
<meta property="og:title" content="ACHIEVEMENT_TITLE"/>
<meta property="og:description" content="ACHIEVEMENT_DESCRIPTON"/>
<meta property="og:image" content="URL_FOR_ACHIEVEMENT_IMAGE"/>
<meta property="og:points" content="POINTS_FOR_ACHIEVEMENT"/>
<meta property="fb:app_id" content="YOUR_APP_ID"/>
</head>
<body>
Promotional content for the Achievement.
This is the landing page where a user will be directed after
clicking on the achievement story.
</body>
</html>
The above is just an example from this post. Note the first meta tag in the example? I suppose it's missing in your page.
<meta property="og:title" content="Game Loader"/>
<meta property="og:url" content="FULL LINK TO THIS PAGE"/>
These are required fields. Provide all the required fields and try again with the debugger tool, if debugger tool passes your page then you are ok to register achievement.