Fix request failed using php - php

I make an api using Linkedin for website. After created all files, my application run fine but the only that has problem is when I try to allow the website, gives me this errors:
my purpose is to access in this page:
My code has error in this line:
init.php
<?php
SESSION_start();
$client_id="xxxxxxxxxxxxxx";
$client_secret="xxxxxxxxxxxxxxxx";
$redirect_uri="http://localhost/gmail-connect.php/callback.php";
$csrf_token = "random_int(1111111, 9999999)";
$scopes="r_basicprofile%20r_emailaddress";
function curl($url, $parameters)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_POST, 1);
$header =[];
$header[] = "Content-type:applicationx-www-form-urlencoded";
$result = curl_exec($ch);
return $result;
}
function getCallback()
{
$client_id="xxxxxxxxxxxxxx";
$client_secret="jxxxxxxxxxxxxxxxx";
$redirect_uri="http://localhost/gmail-connect.php/callback.php";
$csrf_token ="random_int(1111111, 9999999)";
$scopes="r_basicprofile%20r_emailaddress";
}
if(isset($_REQUEST['code'])) {
$code = $_REQUEST['code'];
$url = "https://www.linkedin.com/oauth/v2/accessToken";
$params = [
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'code' => $code,
'grant_type' => 'authorization_code',
];
$accessToken = curl($url, http_build_query($params));
$accessToken = json_decode($accessToken)->access_Token;
$URL="https://api.linkedin.com/v1/people/~:(id,firstName,lastName,pictureUrls::(original),headline,publicProfileUrl,location,industry,positions,email-address)?format=json&oauth2_access_token=" .$accessToken;
$user = file_get_contents($url, false);
return(json_decode($user));
}
?>
Callback.php:
<?php
require_once "init.php";
$user = getCallback();
$_SESSION['user'] = $user;
header("location: landing.php");
?>
And this is the landing page:
<?php
require "init.php";
if(!isset($_SESSION['user'])) {
$user = 0;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>profile</title>
</head>
<body style="margin-top:200px; text-align:center;">
<div>
<h1>successful</h1>
<h1>here is describing your details info</h1>
<label style="font-weight:600">First Name</label><br>
<label><?php echo $user['firstName'] ?></label><br><br>
<label style="font-weight:600">Last Name</label><br>
<label><?php echo $user['lastName'] ?></label><br><br>
<label style="font-weight:600">Email address</label><br>
<label><?php echo $user['emailaddress'] ?></label><br><br>
<label style="font-weight:600">Headline</label><br>
<label><?php echo $user['headline'] ?></label><br><br>
<label style="font-weight:600">Industry</label><br>
<label><?php echo $user['industry'] ?></label><br><br>
<button>Log out</button>
</div>
</body>
</html>
the x it is for secure reason, I have put $client_secret="", $client_id="".
In this project I want to see my profile completed with details on landing page and not empty as it's show here for example in first name to be writen a name and ect.
how to fix those errors,thanks

The first error (Undefined property) is because the HTTP request didn't get a valid response ($accessToken) in:
$accessToken = curl();
This could be because the URL requested is invalid. You can:
Check if $params array is correctly set. Call print_r($params) or print_r(http_build_query($params)) before calling curl to check it.
Check if the curl() call has the right parameters (url and parameters) it could be better to use only a full url ($url . "?" . http_build_query($params)) if the request is using GET, but
The accessToken API must be requested as POST request (not GET), so make sure your cUrl call sends a POST request (See: https://developer.linkedin.com/docs/oauth2#)
The second error is related to the first one, because the access token is empty, you get a HTTP 400 error (bad request). So if you fix the first step the second could be fine.

try this code before $accessToken :
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
return true;
this make solute the error message

Related

Why No response from Google Invisible recaptcha?

Trying to achieve Google invisible recaptcha, but I am not getting any response after verification.
Here is my code:
invisible_recaptcha.php (form)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Recaptcha Demo</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmit(token) {
document.getElementById("i-recaptcha").submit();
}
</script>
</head>
<body>
<!-- FORM GOES HERE -->
<form id='i-recaptcha' action="process_recaptcha.php" method="post">
<label for="fname">First Name*</label><br>
<input type="text" name="fname" id="fname" required autofocus><br><br>
<label for="lname">Last Name*</label><br>
<input type="text" name="lname" id="lname" required><br><br>
<label for="email">Email Address*</label><br>
<input type="email" name="email" id="email" required><br><br>
<button class="g-recaptcha" data-sitekey="XXXXXXmy_site_keyXXXXXXXXX" data-size="invisible" data-callback="onSubmit">
Submit
</button>
</form>
</body>
</html>
process_recaptcha.php (verify the recaptcha)
<?php
// Checks if form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => 'XXXXXX_my_secret_key_XXXXXXXXX',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
//echo $user_response."<br><br><br><br>". $fields_string;exit;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the reCAPTCHA is not properly set up
echo 'reCAPTCHA error: Check to make sure your keys match the registered domain and are in the correct locations. You may also want to doublecheck your code for typos or syntax errors.';
} else {
// If CAPTCHA is successful...
// Paste mail function or whatever else you want to happen here!
echo '<br><p>CAPTCHA was completed successfully!</p><br>';
}
} ?>
It always gives me this message:
reCAPTCHA error: Check to make sure your keys match the registered domain and are in the correct locations. You may also want to doublecheck your code for typos or syntax errors.
Please try this One
try {
//Get google capcha details
if ($site_details['google_captcha_secret_key'] != '') {
$site_key = $site_details['google_captcha_secret_key'];
} else {
$site_key = GOOGLE_CAPTCHA_SECRET_KEY;
}
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => $site_key,
'response' => $captcha,
'remoteip' => $this->userIpAddress];
$options = [
'http' => [
'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);
return json_decode($result)->success;
} catch (Exception $e) {
return null;
}
Make sure you double-check your code over for syntax errors. You are missing the left quote around your site key. You also have an extra parenthesis where it says json_decode.
Finally, you don't need to separate it into two PHP files if you are going to use this condition:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
So the php code in process_recaptcha.php can be embedded in invisible_recaptcha.php. You would then have to change the form's action attribute to itself (invisible_recaptcha.php). The condition will check if the form has been submitted yet. If is has, it will process your recaptcha code, if not, it will skip it.

Create an php form and make an api request

I have to create an simple form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML page</title>
</head>
<body>
<form method="post" action="process.php">
<input type="text" name="firstname" placeholder="rahul_sharma">
<button type="submit">send</button>
</form>
</body>
</html>
From my process.php file, I have to hit an url like below:
https://stackoverflow.com/api?rahul_sharma
which will give back an json response
{"status":"Success","username":"your username is RAHULSHARMA"}
If status is success, have to display the username value.
New to php.Any help is appreciated.
you can call API using curl.
$url='https://stackoverflow.com/api?';
$call_url = $url . $_POST['first_name'] ;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $call_url,
CURLOPT_SSL_VERIFYPEER => false,
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;//{"status":"Success","username":"your username is RAHULSHARMA"}
In your process.php file, you can use the $_POST superglobal to fetch the form data.
$firstname = $_POST['firstname'];
After that you can concatenate it using the . operator to form the url.
$url = "https://your-api-site.com/api?" . $firstname;
Next you can fetch the content from the url using a curl request.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
The result from fetching the url will be obtained in the $output variable. Suppose the result from your API is a JSON string like the one you provided, you can use json_decode PHP function to convert it to an associative array.
$result = json_decode($output);
Now you can use if conditions to check if status is Success and display the username.
if ($result['status'] == "Success") {
echo $result['username'];
}

How to call a API in CAKE PHP?

I have seen many answer in stack overflow about this. But Nothing is working. I am trying to send a mail using SMTP server. But the server is dynamic. For me this is not a problem, but for sending mail I am try to make an api. For call the API I did the below code.
function curl_get_contents($url)
{
//echo $url; die;
$ch = curl_init();
//curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$data_ar = array(
"email_ip" => $SmtpServer,
"username" =>$SmtpUser,
"password" => $SmtpPass,
"port" => $SmtpPort,
"email_id" => 'admin#owntheblog.com',
"email_to" => $_POST['to'],
"email_subject" => $_POST['sub'],
"email_content" => $_POST['message']
);
$data_js = json_encode($data_ar);
$url='http://setup.spotrix.com/app/webroot/mail/mail.php?smtp='.$data_js;
$response = curl_get_contents($url);
or replace the last line with $response = file_get_contents($url);
I found the above code in the stackoverflow. But in the both the case (as in the CURL or file_get_contents) the API calling is not working. But if you directly hit the URL in the browser then the mail is working. Like the URL is,
http://setup.spotrix.com/app/webroot/mail/mail.php?smtp={%22email_ip%22:%22IP%22,%22username%22:%22username%22,%22password%22:%22password%22,%22port%22:port,%22email_id%22:%22form_email%22,%22email_to%22:%22to_email%22,%22email_subject%22:%22Test%20Subject%22,%22email_content%22:%22Test%20Message%22}
Then the mail is working. But not working in the code. I am using cakephp 2.X. I think I made a mistake here. Please help me to solve this problem.
I made a form in php for test the mail portion. I am sharing the code also.
<?php
//Server Address
$SmtpServer= 'Your SMTP IP';
$SmtpPort= YOUR SMTP PORT; //default
$SmtpUser='YOUR SMTP USER NAME';
$SmtpPass='YOUR SMTP PASSWORD';
function curl_get_contents($url)
{
$ch = curl_init();
//curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$data_ar = array(
"email_ip" => $SmtpServer,
"username" =>$SmtpUser,
"password" => $SmtpPass,
"port" => $SmtpPort,
"email_id" => $_POST['from'],
"email_to" => $_POST['to'],
"email_subject" => $_POST['sub'],
"email_content" => $_POST['message']
);
$data_js = json_encode($data_ar);
$url='http://setup.spotrix.com/app/webroot/mail/mail.php?smtp='.$data_js;
$response = curl_get_contents($url);
//$response = file_get_contents($url);
echo $response;
die;
}
?>
<!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=iso-8859-1" />
<title>Test Mail</title>
</head>
<body>
<form method="post" action="">
<table width="500px">
<tr><td width="20%">To : </td>
<td ><input type="text" name="to" /></td></tr>
<tr><td>From :</td><td><input type='text' name="from" /></td></tr>
<tr><td>Subject :</td><td><input type='text' name="sub" /></td></tr>
<tr><td>Message :</td><td><textarea name="message"></textarea></td></tr>
<tr><td></td><td><input type="submit" value=" Send " /></td></tr>
</table>
</form>
</body>
</html>
You can copy paste the above code and change to your SMTP details and use the mail system. You can echo the $url to see the requested url. Try to copy paste the url in the browser see the mail is working but not from the code. If the mail send successfully then it will reture 1 else 0. Please make me correct id I make any mistake.
Thanks in advance for help.

Pulling instagram photos in php

I am going to pull my hair out. Can anyone please help me get this to work I am sure it's something stupid.. I have got all the PHP errors to go away, but I can not get images to show up. Code below...
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="jquery.fancybox-1.3.4.css" type="text/css">
<script type='text/javascript' src='jquery.min.js'></script>
<script type='text/javascript' src='jquery.fancybox-1.3.4.pack.js'></script>
<script type="text/javascript">
$(function() {
$("a.group").fancybox({
'nextEffect' : 'fade',
'prevEffect' : 'fade',
'overlayOpacity' : 0.8,
'overlayColor' : '#000000',
'arrows' : false,
});
});
</script>
<?php
// Supply a user id and an access token
$userid = "1d458ab0c149424c812e664c32b48149";
$accessToken = "c195717e379f48c68df451cc3d60524a";
// Gets our data
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Pulls and parses data.
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?access_token={$accessToken}");
$result = json_decode($result);
?>
<?php if(!empty($result->data)): ?>
<?php foreach ($result->data as $post){ ?>
<!-- Renders images. #Options (thumbnail,low_resoulution, high_resolution) -->
<a class="group" rel="group1" href="<?= $post->images->standard_resolution->url ?>"><img src="<?= $post->images->thumbnail->url ?>"></a>
<?php } ?>
<?php endif ?>
</html>
What you need is to add some checks at various points to find out what is coming back from Instagram and handle any issues. While debugging, sticking var_dump() all over the place can be helpful to see where issues lie.
Here is an example of your PHP section with some additional checks:
<?php
// Supply a user id and an access token
$userid = "USER ID";
$accessToken = "ACCESS TOKEN";
// Gets our data
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
// Check a response was returned
if ($info['http_code'] == '404') {
echo ('Error: HTTP 404 returned, bad request');
die();
}
curl_close($ch);
return $result;
}
// Pulls and parses data.
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/?access_token={$accessToken}");
$result = json_decode($result);
// Check the json_decode succeeded
if (empty($result)) {
echo "Error: JSON not returned from API";
die();
}
// Check no error was returned from Instagram
if ($result->meta->code != 200) {
echo "Error: ".$result->meta->error_message;
die();
}
?>
If you plan on doing a lot of work with the Instagram API, you may want to look at a library to do most of the heavy lifting. This one appears to be the most popular at present.

Cakephp : Validate recaptcha

I have downloaded a recaptchalib and successfully implemented the recaptcha and its displaying the recaptcha on my page but i am not able to validate it ... how can i validate the recaptcha
In View File
<div id="recaptcha_div"></div>
<script type="text/javascript">
$(function(){
Recaptcha.create("<?php echo Configure::read("recatpch_settings.public_key")?>", 'recaptcha_div', {
theme: "red",
callback: Recaptcha.focus_response_field});
});
</script>
Controller's Login action
public function login() {
App::import('Vendor', 'recaptchalib', array('file' => 'recaptchalib/recaptchalib.php'));
$resp = recaptcha_check_answer (Configure::read("recatpch_settings.private_key"),
$_SERVER["REMOTE_ADDR"],
$this->params['form']["recaptcha_challenge_field"],
$this->params['form']["recaptcha_response_field"]);
pr($resp);
exit();
if (!$resp->is_valid) {
$this->Session->setFlash('The reCAPTCHA wasn\'t entered correctly. Please, try again.');
} else {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Your username/password combination was incorrect');
}
}
}
}
I am not able to validate the captcha. I want to login the user if i types the correct captcha and obviously username and password.
I know that this is a very old question by now but I'll just go ahead and answer for those who might be looking into implementing this.
Add the Site/Secret key to your app/config/bootstrap.php file.
//Recaptcha Config
Configure::write('Recaptcha.SiteKey','YourSiteKey');
Configure::write('Recaptcha.SecretKey','YourSecretKey');
Adding the reCaptcha widget to your view/form:
<div>
<div class="g-recaptcha"
data-sitekey="<?php echo Configure::read('Recaptcha.SiteKey'); ?>">
</div>
<?php echo $this->Html->script('https://www.google.com/recaptcha/api.js"'); ?>
</div>
Verifying the user's response (reusable function inside your controller):
private function __checkRecaptchaResponse($response){
// verifying the response is done through a request to this URL
$url = 'https://www.google.com/recaptcha/api/siteverify';
// The API request has three parameters (last one is optional)
$data = array('secret' => Configure::read('Recaptcha.SecretKey'),
'response' => $response,
'remoteip' => $_SERVER['REMOTE_ADDR']);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
// We could also use curl to send the API request
$context = stream_context_create($options);
$json_result = file_get_contents($url, false, $context);
$result = json_decode($json_result);
return $result->success;
}
You check response by calling the above function after submitting a form containing the widget:
if($this->__checkRecaptchaResponse($this->request->data['g-recaptcha-response'])){
// user solved the captcha
} else {
// user failed to solve the captcha
}
Useful resources:
https://developers.google.com/recaptcha/docs/display
https://developers.google.com/recaptcha/docs/verify
Google has been introduced new reCaptcha API which is Are you a robot? A new design captcha system. This protects your website for robots and spammers, in this post I had implemented new reCaptch API system with HTML login form using CakePHP. Please take a look quick look at the demo.
Get reCaptcha Key
Click here to create a Google reCaptcha application.
Register Your Website
Give your website domain details without http:
Google Site Key
You will use this in HTML code.
Google Secret Key
This will help your website to communication with Google.
HTML code
Contains HTML code with Google reCaptcha snippet. You have to modify the GOOGLE_SITE_KEY value.
<html>
<head>
/* Google reCaptcha JS */
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<form action="" method="post">
<label>Username</label>
<?php echo $this->Form->text('User.username', array('maxlength' => 32))?>
<label>Password</label>
<?php echo $this->Form->password('User.password', array('maxlength' => 32))?>
<div class="g-recaptcha" data-sitekey="GOOGLE_SITE_KEY"></div>
<input type="submit" value="Log In" />
</form>
</body>
</html>
Create new Vendor in Vendor file:
curl.php
<?php
function getCurlData($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
$curlData = curl_exec($curl);
curl_close($curl);
return $curlData;
}
?>
Using in controller, You have to modify the GOOGLE_SECRET_KEY value.
$recaptcha = $this->data['g-recaptcha-response'];
$google_url = "https://www.google.com/recaptcha/api/siteverify";
$secret = 'GOOGLE_SECRET_KEY';
$ip = $_SERVER['REMOTE_ADDR'];
$url = $google_url . "?secret=" . $secret . "&response=" . $recaptcha ."&remoteip=" . $ip;
App::import('Vendor', 'curl');
$res = getCurlData($url);
$res = json_decode($res, true);
if(empty($res['success'])){
//if success not empty
//some code here
}
Hope it's useful.

Categories