I have built a log in system and I am adding google recaptcha for security. I am getting an error on this line: $result = json_decode($url, TRUE);
The error says;
failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request.
This is my first time using recaptcha and I am not sure if this is a common mistake.
<?php
$secret = '*****';
$response = $_POST['g-recaptcha-response'];
$remoteip = $_SERVER['REMOTE_ADDR'];
$captcha = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip");
$result = json_decode($url, TRUE);
$username;
$password;
$captcha;
if (isset($_POST['username']))
$username = $_POST['username'];
if (isset($_POST['password']))
$password = $_POST['password'];
if (isset($_POST['g-recaptcha-response']))
$captcha = $_POST['g-recaptcha-response'];
if (!$captcha) {
echo '<p class="error-message">Please Complete The Captcha!</p>';
header("location: login.php");
exit;
}
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LfG-S8UAAAAAIqW1sBE31yMPyO4zeqOCgDzL1mA&response=" . $captcha . "&remote=" . $_SERVER['REMOTE_ADDR']), true);
if ($response['success'] == false) {
echo '<p class="error-message">Please Fill Captcha!</p>';
} else {
echo '<p class="error-message2">Welcome</p>';
}
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$q = $handler->prepare('SELECT * FROM users WHERE username = ?');
$q->execute(array($username));
$result = $q->fetch(PDO::FETCH_ASSOC);
if ($result !== false) {
$hash_pwd = $result['password'];
$hash = password_verify($password, $hash_pwd);
if ($hash) {
$_SESSION['username'] = $username;
header("location:index.php");
return;
} else {
echo '<p class="error-message3"><br><br>You have ented an incorrect login!<br>Please try again</p>';
}
}
}
?>
If this really is your complete code:
It seems you are using $url (in the line $result = ...) without having initialized it before.
Additionally, I would expect that a variable with name $url contains an URL, and URLs are not in JSON format, so this raises some alarm signs. You eventually do not want to JSON-parse an URL, but instead parse what this URL returns when calling it.
Secondly, sometimes the line numbers within error messages or warnings are misleading. I highly doubt that the error you have mentioned (HTTP request failed) is related to json_decode(). json_decode(), as the name implies, just parses a string in JSON format, but does not load anything via HTTP.
So the error message probably comes from the line above ($captcha = file_get_contents(...);). I suppose that the URL you give there is wrong, or that Google refuses the request for another reason.
The first thing I would do is putting that URL into a variable and print it out (e.g. by using error_log()).
If that does not lead to the source of the problem, I would copy that URL (not from the code, but from the output produced by error_log()) and paste it directly into the address bar of a new browser window. If this yields the expected result (you should see Google's answer to the request in the browser window), the error is in your code. Otherwise, the error is in the URL.
<?php
session_start();
error_reporting(E_ALL);
try {
$ini = parse_ini_file("/var/www/admin.ini");
$user = $ini['user'];
$pass = $ini['pass'];
$name = $ini['name'];
$host = $ini['host'];
$handler = new PDO('mysql:host='.$host.'; dbname='.$name, $user, $pass);
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
error_log($e);
echo $e->getMessage();
}
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => [
'secret' => '********',
'response' => $_POST['g-recaptcha-response'],
],
]);
$response = json_decode(curl_exec($curl));
if (!$response->success) {
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$q = $handler->prepare('SELECT * FROM users WHERE username = ?');
$q->execute(array($username));
$result = $q -> fetch(PDO::FETCH_ASSOC);
if ($result !== false) {
$hash_pwd = $result['password'];
$hash = password_verify($password, $hash_pwd);
if ($hash) {
$_SESSION['username'] = $username;
header("location:index.php");return;
}
else {echo '<p class="error-message3"><br><br>You have ented an incorrect login!<br>Please try again</p>';
}
}
}
}
?>
Related
I am using Firebase/JWT with php. I am trying to read the token in "decoded" php file but it shows be Signature verification failed not sure why that is happening. This is how I am encoding the token
<?php
use \Firebase\JWT\JWT;
require 'vendor/autoload.php';
require('config/Database.php');
$db = new Database;
$key = "helloworld";
//$jwt = JWT::encode($token, $key, 'HS512');
$post = file_get_contents("php://input");
$postdata = json_decode($post);
if($postdata){
$email = $postdata->email;
$password = $postdata->password;
$query = "SELECT * FROM users WHERE email = :email";
$db->query($query);
$db->bind(":email", $email);
$rows = $db->resultset();
if(password_verify($password, $rows[0]["hash"])){
$rows[0]["Success"] = "Success";
$token = array(
"rows" => $rows
);
$jwt = JWT::encode($token, $key, 'HS256');
header("auth: " . $jwt);
echo json_encode($jwt, 128);
}else{
echo "Failed";
}
}
?>
Then I am decoding the token in this file
<?php
use \Firebase\JWT\JWT;
require 'vendor/autoload.php';
require('config/Database.php');
$db = new Database;
$key = "helloworld";
//$jwt = JWT::encode($token, $key, 'HS512');
$post = file_get_contents("php://input");
$postdata = json_decode($post);
if($postdata){
$userData = $postdata->userdata;
// check if token is same stored in the database then decode
$jwt = JWT::decode($userData, $key, array('HS256'));
echo $jwt;
}
?>
It fails, returning a "Signature verification failed" error.
Any help is appreciated. Thank you.
The problem why it wasn't verifying was because I was using json_encode on the jwt and that caused it to be wrapped around quotes again so the token looked something like this ""eY0lkajflajk...."" and that caused the verifying exception. Thank you #zerkms for bring that up.
I'm trying to authenticate on Bing Ads Api but I'm getting this message:
Authentication failed. Either supplied credentials are invalid or the account is inactive
This is my code:
$UserName = "xxx#hotmail.com";
$Password = "xxx";
$DeveloperToken = "xxx";
$CustomerId = xxx;
$AccountId = xxx;
$wsdl = "https://campaign.api.bingads.microsoft.com/Api/Advertiser/CampaignManagement/V10/CampaignManagementService.svc?singleWsdl";
try
{
$proxy = ClientProxy::ConstructWithAccountAndCustomerId($wsdl, $UserName, $Password, $DeveloperToken, $AccountId, $CustomerId, null);
// Specify one or more campaigns.
$campaigns = array();
$campaign = new Campaign();
$campaign->Name = "Winter Clothing " . $_SERVER['REQUEST_TIME'];
$campaign->Description = "Winter clothing line.";
$campaign->BudgetType = BudgetLimitType::MonthlyBudgetSpendUntilDepleted;
$campaign->MonthlyBudget = 1000.00;
$campaign->TimeZone = "PacificTimeUSCanadaTijuana";
$campaign->DaylightSaving = true;
// Used with FinalUrls shown in the ads that we will add below.
$campaign->TrackingUrlTemplate =
"http://tracker.example.com/?season={_season}&promocode={_promocode}&u={lpurl}";
$campaigns[] = $campaign;
// Add the campaign, ad group, keywords, and ads
$campaignIds = AddCampaigns($proxy, $AccountId, $campaigns);
PrintCampaignIdentifiers($campaignIds);
}
catch (SoapFault $e)
{
// Output the last request/response.
print "\nLast SOAP request/response:\n";
print $proxy->GetWsdl() . "\n";
print $proxy->GetService()->__getLastRequest()."\n";
print $proxy->GetService()->__getLastResponse()."\n";
// Campaign Management service operations can throw AdApiFaultDetail.
if (isset($e->detail->AdApiFaultDetail))
{
// Log this fault.
print "The operation failed with the following faults:\n";
$errors = is_array($e->detail->AdApiFaultDetail->Errors->AdApiError)
? $e->detail->AdApiFaultDetail->Errors->AdApiError
: array('AdApiError' => $e->detail->AdApiFaultDetail->Errors->AdApiError);
// If the AdApiError array is not null, the following are examples of error codes that may be found.
foreach ($errors as $error)
{
print "AdApiError\n";
printf("Code: %d\nError Code: %s\nMessage: %s\n", $error->Code, $error->ErrorCode, $error->Message);
switch ($error->Code)
{
case 105: // InvalidCredentials
break;
case 117: // CallRateExceeded
break;
default:
print "Please see MSDN documentation for more details about the error code output above.\n";
break;
}
}
Sorry for the delayed reply. I noticed that you are setting the UserName to ***#hotmail.com. If you are using an email address login i.e. Microsoft account, then you must use OAuth i.e. set the AuthenticationToken header element instead of setting the UserName/Password fields.
I have a PHP code for sending OTP, When i execute it in my local server its works well. But when i run this code after changing it from my local to server by changing host name etc, i am getting 500 internal server error. I don't know where i am going wrong. Any solution will be apreciated. Thank you
<?php
include './include/DbHandler.php';
$db = new DbHandler();
$response = array();
// echo $_POST['mobile'];
if (isset($_POST['mobile']) && $_POST['mobile'] != '') {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$otp = rand(100000, 999999);
$res = $db->createUser($name, $email, $mobile, $otp);
if ($res == USER_CREATED_SUCCESSFULLY) {
// send sms
sendSms($mobile, $otp);
$response["error"] = false;
$response["message"] = "SMS request is initiated! You will be receiving it shortly.";
} else if ($res == USER_CREATE_FAILED) {
$response["error"] = true;
$response["message"] = "Sorry! Error occurred in registration.";
} else if ($res == USER_ALREADY_EXISTED) {
$response["error"] = true;
$response["message"] = "Mobile number already existed!";
}
} else {
$response["error"] = true;
$response["message"] = "Sorry! mobile number is not valid or missing.";
}
echo json_encode($response);
function sendSms($mobile, $otp) {
$otp_prefix = ':';
//Your message to send, Add URL encoding here.
$message = urlencode("Hello Your OPT is '$otp_prefix $otp'");
$response_type = 'json';
//Define route
$route = "4";
//Prepare you post parameters
$postData = array(
'authkey' => AUTH_KEY,
'mobiles' => $mobile,
'message' => $message,
'sender' => SENDER_ID,
'route' => $route,
'response' => $response_type
);
//API URL
$url = "https://control.otp.com/sendhttp.php";
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
//Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//get response
$output = curl_exec($ch);
//Print error if any
if (curl_errno($ch)) {
echo 'error:' . curl_error($ch);
}
curl_close($ch);
}
?>
I dont think the 500 error comes from your code. That's likely an Apache config related problem. Possibly a stray .htaccess or php.ini got uploaded, or is syntactically wrong for the version of Apache you have on the server.
I want to send the request to another site with GET request and should return a string value. I am using the following cURL code to achieve this but its getting failed.
$user = 'username';
$password = 'password';
$sender_id = 'myid';
$sender_mobile = mobile number;
$message_text = 'Hi Testing SMS';
$priority = 'ndnd';
$sms_type = 'normal';
$redirect_link = "http://bhashsms.com/api/sendmsg.php?user=$user&pass=$password&sender=$sender_id&phone=$sender_mobile&text=$message_text&priority=$priority&stype=$sms_type";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$redirect_link);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$output=curl_exec($ch);
if($output == false)
{
echo "Error Number:".curl_errno($ch)."<br>";
echo "Error String:".curl_error($ch);
}
$info = curl_getinfo($ch);
curl_close($ch);
But if i use the header its sending successfully the following is using header
$user = 'username';
$password = 'password';
$sender_id = 'myid';
$sender_mobile = mobile number;
$message_text = 'Hi Testing SMS';
$priority = 'ndnd';
$sms_type = 'normal';
$redirect_link = "http://bhashsms.com/api/sendmsg.php?user=$user&pass=$password&sender=$sender_id&phone=$sender_mobile&text=$message_text&priority=$priority&stype=$sms_type";
header("Location:$redirect_link");
where am I going wrong!!!
You have an error on $sender_mobile = mobile number; should be like this $sender_mobile = 'mobile number';
I have a big problem about my database e the permission of my application in facebook.
when the user open the app (index.php) and accept the permission, the app go to another page (game.php)... when the game.php is open, the script check in the database to look if the ID of facebook is already present, if not the database make the user.
when the game.php is open at first time, the page generate this error:
OAuthException: An active access token must be used to query information about the current user.
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in game.php on line 67 check1Error: Duplicate entry '0' for key 'UIDfacebook' account
maybe because the ID of facebook is not ready for save in the database, and why? the permission was accept... if I refresh the page, the page will work fine and the database save the ID, username....
INDEX.PHP (REQUEST)
<?php
require('client/facebook.php');
$app_id = '***';
$app_secret = '***';
$canvas_page = "https://apps.facebook.com/***";
$canvas_url = "****";
$code = $_REQUEST['code'];
if(!$code){
$display= 'page';
$scope= 'offline_access, publish_stream, user_about_me, user_likes, email';
$redirect_url = 'game.php';
$oauth_url = 'https://www.facebook.com/dialog/oauth?canvas=1&client_id='.$app_id.'&display='.$display.'&redirect_uri='.urlencode($redirect_url).'&scope='.$scope;
$config = array('appId' => $app_id,'secret' => $app_secret,'cookie' => true,'domain' => true);
$facebook_client = new Facebook($config);
echo "<script type=\"text/javascript\">top.location.href = \"".$oauth_url."\";</script>";
}
?>
GAME.PHP
<?php
require 'client/facebook.php';
require('client/databaselogin.php');
///////////////////
$app_id = "***";
$secret = "***";
$app_url = "https://apps.facebook.com/***/";
//Create our Application instance
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie' => 'true',
));
// Get User ID
$user = $facebook->getUser();
//Do we have a user?
if(!$user) {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=> $app_url));
//redirect the url to prompt for login and permissions
} else {
try{
//Proced knowing you have a logged in user who's autenticated
$user_profile = $facebook->api('/me');
$name = $user_profile['name'];
$id = $user_profile['id'];
$first_name = $user_profile['first_name'];
$last_name = $user_profile['last_name'];
$link = $user_profile['link'];
$username = $user_profile['username'];
$gender = $user_profile['gender'];
$locale = $user_profile['locale'];
} catch (FacebookApiException $e) {
echo ($e);
$user = null;
}
}
$checkUIDdb = "";
$connection = "wait";
$id = $user_profile['id'];
$username = $user_profile['username'];
$goldDB = "0";
$user_type = "A";
///connect to the database
$connessione = mysql_connect($host, $userdb, $passdb)
or die("error: " . mysql_error());
print ("connect");
echo $connection = "ok";
echo $id;
///
$fb_id = $user_profile['id'];
$locale = $user_profile['locale'];
$con=mysqli_connect($sdb,$userdb,$passdb,$db);
if ($connection == "ok")
{
//Checking User Data # WT-Database
$check1_task = "SELECT * FROM `tabletest` WHERE `UIDfacebook` = " . $fb_id . " LIMIT 0, 30 ";
$check1_res = mysqli_query($con, $check1_task);
$checken2 = mysqli_fetch_array($check1_res);
print $checken2;
//If User does not exist # WT-Database -> insert
if (!($checken2)) {
$add = "INSERT INTO tabletest (id,UIDfacebook, username, goldDB, user_type) VALUES ('', '$fb_id', '$username', '$goldDB', '$user_type')";
mysqli_query($con, $add);
if (!$check1_res) {
echo "check1";
printf("Error: %s\n", mysqli_error($con));
}
}
//Double-check, User won't be able to load app on failure inserting to database
if (!($checken2)) {
//echo "Excuse us " . $first_name . ". Something went terribly wrong! Please try again later!";
}
}
//Close off the MySQL connection to save resources.
?>
<head>
</head>
</body>
</script>
MY APPLICATION
</script>
</body>
</html>
somebody know what is happen?
Thank you very much
EDIT:
I try to use this script for the GAME.PHP:
<?php
require 'client/facebook.php';
$app_id = "aaa";
$secret = "aaa";
$app_url = "http://app.facebook.com/aaa/";
// Create our Application instance
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
));
// Get User ID
$user = $facebook->getUser();
//Do we have a user?
if(!$user) {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=> $app_url));
//redirect the url to prompt for login and permissions
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
} else {
try{
//Proced knowing you have a logged in user who's autenticated
$user_profile = $facebook->api('/me');
$name = $user_profile['name'];
$id = $user_profile['id'];
$first_name = $user_profile['first_name'];
$last_name = $user_profile['last_name'];
$link = $user_profile['link'];
$username = $user_profile['username'];
$gender = $user_profile['gender'];
$locale = $user_profile['locale'];
} catch (FacebookApiException $e) {
echo ($e);
$user = null;
}
}
echo $username;
echo $id;
echo $user_profile;
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>php-sdk example1 </title>
<style>
body {
font-family:Arial, Helvetica, sans-serif;
}
a{
text-decoration:none;
}
but at the first time, the error is similar?
OAuthException: Error validating access token: The session was invalidated explicitly using an API call.
if i refresh the page, the problem disappears....