Download File Using Curl in php to a specific folder - php

I have a Google Drive File Url suppose for eg.
https://doc-0c-90-docs.googleusercontent.com/docs/securesc/rgh255lj001rts71cq6a0d0fmikln8fe/gg1vds4tn8h88pushsj7s1c1qvsb8nk3/1442404800000/16565899266202741945/16565899266202741945/0B86G8IQ4Uf9ATk5wRW9pdXN6OFE?e=download&gd=true
I want to download it to a specific folder for that i am using curl
function pickerCallback(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var fileId=doc[google.picker.Document.ID];
$.ajax({
type: "POST",
url: "files/sample.php",
data: { file_id:fileId,token:oauthToken },
success: function(data)
{
}
});
}
}
sample.php
$upload_path='folder_path';
$fileId = $_POST['file_id'];
$oAuthToken = $_POST['token'];
$getUrl = 'https://www.googleapis.com/drive/v2/files/'. $fileId .'?alt=media';
$authHeader = 'Authorization: Bearer ' . $oAuthToken ;
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$returned_content = get_data($getUrl);
file_put_contents($upload_path.'/'."55dad26bf4165.jpg", $returned_content);
this is the name of the file that i am downloading 55dad26bf4165.jpg, but it gives following error :
string(379)" { "error"; { "errors":[{
"domain":"usageLimits","reason":dailyLimitExceededUnreg",
message:Daily Limit for Unauthenticated Use Exceeded. Continue use
requires signup.".
"extendedHelp":"https://code.google.com/apisconsole" }], "code":403,
"message":"Daily Limit for Unauthenticated Use Exceeded. Continued
use requires signup."}}"
Please help why this error is occuring.

Related

How to handle error from php handler file

If there is an error in the js/send_to_telegram.php file, then the error script will work. How to do it?
jQuery("form").submit(function () {
var form_data = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "js/send_to_telegram.php",
data: form_data,
success: function (result) {
donemodal.style.display = "block";
},
error: function (jqXHR, exception) {
errormodal.style.display = "block";
}
});
});
in js/send_to_telegram.php the following code:
$token = "5306003979:AAEPK2NhlxW";
$chat_id = "497358";
$txt = htmlspecialchars($_POST["text"]);
$sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}","r");
Now, even if you enter the wrong token in $sendToTelegram, it returns success. How to get error if token is wrong?
Short answer: It doesn't use API response status code unless you tell him does that. What if we sent multiple HTTP requests and got different status codes? Which of them should be used?
Solution: This is what you need:
<?php
function post($url, $fields = []) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
if (is_array($fields) && count($fields)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
$response = post("https://api.telegram.org/bot{$token}/sendMessage", [
'chat_id' => $chat_id,
'text' => $txt,
]);
if ($response->ok) {
echo '{"message": "ok"}';
} else {
http_response_code(500);
echo '{"message": "Something went wrong"}';
}

CURL Form Response

I am having an issue with my form. The issue is that when submit is clicked the jQuery does not work within the response.length > 0 statement but however the form is working and importing data but I need it to update the div and load the thank you page instead of acting like its doing nothing :)
It should be response.length > 0 - then load the errors and update div else go to the thank you page
jQuery:
$('#mountianForm').submit(function(e) { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
if (response.length > 0) {
$('#mountianFormResponse').html(response); // update the DIV
} else {
window.location.href = 'https://example.com/thank-you/';
}
}
});
e.preventDefault();
});
Process Code:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$url = 'https://id.infusionsoft.com/app/form/iframe/formID';
$userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36';
if (!empty($_GET))
{
$url .= '?'.http_build_query($_GET);
}
$isPOST = !empty($_POST);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_POST, $isPOST);
if ($isPOST)
{
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
}
$response = curl_exec($ch);
curl_close($ch);
if(preg_match('/(<ul>.*<\/ul>)/is', $response, $match)){
$match[1];
}else{
$error = "Error";
$file = fopen("mountianProxyerror.php", 'w+'); // Create a new file, or overwrite the existing one.
fwrite($file, $error);
fclose($file);
}
?>
I think you didn't return the response from your process code.
if(preg_match('/(<ul>.*<\/ul>)/is', $response, $match))
{
$match[1];
$resp = array('status' => TRUE,'msg' => 'success','resp' => $response);
}
else
{
$error = "Error";
$file = fopen("mountianProxyerror.php", 'w+'); // Create a new file, or overwrite the existing one.
fwrite($file, $error);
fclose($file);
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
And in your ajax
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
dataType : 'json',
success: function(response) { // on success..
alert(response.msg);
if (response.status == true) {
$('#mountianFormResponse').html(response.resp);
// Do whatever with the success code
}
else
{
window.location.href = 'https://example.com/thank-you/';
}
}
});

aspnet core app strange request type

I am building a asp.net core app with the debfault aspnetidentitycore plugedin, the only change is i added an action by modified the regiester method to a api, which means can be called by another app.
[HttpPost]
[AllowAnonymous]
public async Task<EngineResult<object>> RegisterByApi([FromBody]RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new IdentityUser
{
DisplayName = model.Name,
UserName = model.Email,
Email = model.Email,
PhoneNumber = model.PhoneNumber,
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return new EngineResult<object>(true) { Entity = new { sub = user.Id, name = user.DisplayName } };
}
return new EngineResult<object>(false) { Entity = string.Join(";", result.Errors?.Select(e => e.Description)) };
}
return new EngineResult<object>(false) { Entity = string.Join(";", ModelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage)) };
}
but when a php calls this api, i get a strange content-type, which is
application/json; boundary=------------------------e3f0ef0cc3e74f25
here is the php code
<?php
$data = [
"Name"=>"testname",
"Email"=>"123#testdomain.com",
"Password"=>"123qwe!#QWE",
"ConfirmPassword"=>"123qwe!##QWE",
"PhoneNumber"=>"12312321321",
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://xxxx/Account/RegisterByApi");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
header_remove();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
anyone know what's happening here?
finally, it is a my php code issue, that not use a json data, replace the post data with a convert to josn will resolve this issue:
$payload = json_encode($data);

Garbage accessToken using facebook login

I am using facebook login using oauth. Sometime I am getting proper accessToken or sometime this kind of garbage values in accessToken
{"source":"uni","s":"s","p":{"z":"0","c":"0","i":"287"},"r": {"z":"1","c":"15239"},"node_id":"23.57.77.12"}.
Because of that my next requests to graph API fails. What is that thing and How do I handle this??
I have multiple domains ex. www.example.com, www.example12.com, www.example22.com etc.
I have created app for www.example.com on facebook and using it for all domains using the window.postmessage:
homepage.php (When user click on facebook login button):
if(!window.addEventListener){
window.attachEvent("onclick", processFacebookLogin);
}
else{
window.addEventListener("message", processFacebookLogin, false);
}
var width = 500;
var height = 500;
var left = ((window.innerWidth / 2) - (width / 2)) + window.screenLeft;
var top = ((window.innerHeight / 2) - (height / 2)) + window.screenTop;
winObj = window.open("http://www.example.com/fb-login?currentDomain=www.example12.com", "fbwindow", "height="+width+",width="+height+",top="+top+",left="+left);
function processFacebookLogin(e) {
winObj.close();
if(e.data != "error" && e.data != "missing_param"){
accessToken = e.data;
$.ajax({
async: false,
url: "UrlToProcessFacebookLogin",
type: "POST",
dataType: "json",
data:
{
"medium" :"facebook",
"accessToken" : accessToken
},
success: function(data)
{
//redirect to some another url
}
});
}
}
child window url page contains the following code fbLoginController.php:
The above window.open contains the indexAction url of fbLoginController (I am using Zend Framework):
public function indexAction()
{
$communityDomain = preg_replace('#^https?://#', '', $_GET['community']);
$fbLoginUrl = "https://www.facebook.com/v1.0/dialog/oauth?client_id=FbAppClientId&scope=AllRequiredScopes&auth_type=rerequest&return_scopes=true&display=popup&redirect_uri=http://www.example.com/fb-login/fb-response?community=".$communityDomain;
$this->_redirect($fbLoginUrl);
exit;
}
public function fbResponseAction()
{
$arrParams = $this->_getAllParams();
$code = $arrParams['code'];
$communityDomain = $arrParams['community'];
$grantedScopes = $arrParams['granted_scopes'];
$error = $arrParams['error'];
if(!empty($error))
{
echo "<script>window.opener.postMessage('error', 'http://".$communityDomain."');</script>";
exit;
}
if(empty($communityDomain) || empty($grantedScopes))
{
echo "<script>window.opener.postMessage('missing_param', 'http://".$communityDomain."');</script>";
exit;
}
$curlUrl = "https://graph.facebook.com/v1.0/oauth/access_token?client_id=FbAppClientId&client_secret=FbAppClientSecret&code=" . $code . "&redirect_uri=http://www.example.com/fb-login/fb-response?community=" . $communityDomain;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, 0);
curl_setopt($ch, CURLOPT_POST, 0);
$curlResponse = curl_exec($ch);
$curlError = curl_error($ch);
curl_close($ch);
parse_str($curlResponse,$parsedStr);
echo "<script>window.opener.postMessage('".$parsedStr['access_token']."', 'http://".$communityDomain."');</script>";
exit;
}
for proper understanding I have put each and every line of code in this question.

Login using Curl Php (POST method)

Hi every one,
I have a login form which has mail id and password, on submit it should call an api which inturn generates a auth token. I have used POST method in Php curl but getting the following error.
Apache Tomcat/6.0.36 - Error report
.. some html styles..
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method
and this is my ajax call..
function callapi()
{
data = new Object();
var email= document.getElementById("input01").value;
var pwd=document.getElementById("input02").value;
if(email != ""&& pwd != "")
{
data.Email = email;
data.Pwd = pwd;
}
jQuery.ajax({
url: "http://localhost/stackato/nlogin.php",
type: "POST",
dataType:"json",
data:data,
error: function (data) {
alert('error--'+data);
},
success: function (data) {
if(data=="invalid")
{
}
else
{
window.location.href="finalstackatolists1.html";
}
}
});
}
and this is my curl php page
<?php
header('Content-type: application/json');
$url = $_SERVER['REQUEST_URI'];
$scriptname = $_SERVER['SCRIPT_NAME'];
$queryString = $_SERVER['QUERY_STRING'];
$mail=$_POST["Email"];
$pwd=$_POST["Pwd"];
$action = $_POST["action"];
$nurl = str_replace($scriptname,"...the api...",$url);
//open connection
$ch = curl_init();
$data = array("username" => $mail, "password" => $pwd);
$req_data = json_encode($data);
curl_setopt($ch, CURLOPT_URL, $nurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req_data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//execute post
if( ! $result = curl_exec($ch)) {
die(curl_error($ch));
curl_close($ch);
}
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == '500')
{
header("Status: 500 Server Error");
}
curl_close($ch);
echo $result;
?>
(I tried it in REST-Client and the token has been generating)
Please help me to solve this.. thanks in advance..
You have to specify that the posted data is of type JSON
add this line to your curl code
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/json"));

Categories