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'];
}
Related
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
If you access the webpage https://api.mercadolibre.com/items/MLB752465575 you will receive a JSON response. All I need to start is print the item "id" on the screen.
This is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$json_str = "https://api.mercadolibre.com/items/MLB752465575";
$obj = json_decode($json_str);
echo "id: $obj->id<br>";
?>
</body>
</html>
All I want is receive the MLB752465575 part into my browser.
How can I do it?
$json_str = "https://api.mercadolibre.com/items/MLB752465575";
The above does not retrieve the data it's saving the url to the var and that's not what you want.
You just need to fetch the content You can use cURL or file_get_contents()
cURL version:
<?php
$url = "https://api.mercadolibre.com/items/MLB752465575";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$r = curl_exec($curl);
curl_close($curl);
$array = json_decode($r, true);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
file_get_contents version:
<?php
$r = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');
echo "<pre>";
echo print_r(json_decode($r, true));
echo "</pre>";
?>
Both of them will work unless the remote website requires you to be human (has extra verifications to stop robot requests). cURL would be a better way if that were the case because you can fake a user agent using a header array.
Once you have the array build it's just a matter of accessing the required data. using $r as an array result of the remote json structure.
Use curl to get the result, and json_decode to turn it into an array.
<?php
$url = "https://api.mercadolibre.com/items/MLB752465575";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpcode != 200) {
echo "error " . $httpcode;
curl_close($ch);
return -1;
}
$result_arr = json_decode($result, true);
echo $result_arr['id'];
curl_close($ch);
$jsonResponse = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');
$obj = json_decode($jsonResponse);
echo "id: {$obj->id}<br>";
What you did in your code was to json_decode the URL itself. You needed to get the content from the URL, and then decode the content.
The code is working fine but i am not able to insert the user data in the mysql database.
<?php
$facebookAppAuthUrl = 'https://graph.facebook.com/oauth/access_token';
$facebookGraphUrl = 'https://graph.facebook.com';
$facebookClientId = ''; // Put your App Id here.
$facebookRedirectUrl = ''; // Redirect url same as passed before.
$facebookAppSecret = ""; // Put your App Secret here.
$code = $_GET['code'];
$url =$facebookAppAuthUrl."?client_id=".$facebookClientId
."&redirect_uri=".$facebookRedirectUrl
."&client_secret=".$facebookAppSecret
."&code=".$code;
$output = urlResponse($url);
$var = strtok($output, "&");
$ApCode = strtok($var, "=");
$ApCode = strtok("=");
// This $ApCode will be used as a token to get user info from facebook.
$url = $facebookGraphUrl.'/me';
echo '<pre>';
$resposeObj = json_decode(processUrl($url,$ApCode));
var_dump($resposeObj);
echo '<pre>';
function urlResponse($url)
{
$ch = curl_init();
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function processUrl($url,$apCode){
if(stripos($url,'?')>0)
$url = $url.'&access_token='.$apCode;
else
$url = $url.'?access_token='.$apCode;
return urlResponse($url);
}
?>
I guess the code below is wrong. I got the user data from facebook in JSON format but unfortunately I am not able to add user data in mysql using the PHP. How could we insert the json format data in mysql using php?
<?php
require('../conn.php');
$name = $url['id']['name'];
$first_name = $url['id']['first_name'];
$last_name = $url['id']['last_name'];
$hometown = $url['id']['hometown'];
{
$sql="insert into user values('','$name','$first_name','$last_name','$hometown')";
mysql_query($sql);
}
?>
<script type="text/javascript">window.location="../index.php"</script>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
Here what you need to do , first the JSON returned data needs to be converted to array as
$response = json_decode($response,true);
Now with this data you have the array and you can use print_r($response) and see how the array looks like and use the data in the query.
Hope this helps
So, apparently I can't comment without 50 rep points - so whatever. I suspect your insert statement is off. Why do you have an empty string at the beginning? I hope that's not your primary key field. I would specify my fields if I were you and leave the auto-inc field out of it so it can auto increment :)
$sql="insert into user (`name`,`firstName`,`LastName`,`homeTown`) values('$name','$first_name','$last_name','$hometown')";
Im creating a web payment form.As according to pci I cant store a credit card number so i use a third party api for encrypting thr credit card number.According to that third party documentation,I have to add their script in my html form <script type="text/javascript" src="./-client-2.1.2.js"></script> and also to the form a unique value to the form
<input id="txtEncryptionKey" name="txtEncryptionKey" class="_encryptionkey"
type="hidden" value="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvWpIQFjQQCPpaIlJKpeg
irp5kLkzLB1AxHmnLk73D3TJbAGqr1QmlsWDBtMPMRpdzzUM7ZwX3kzhIuATV4Pe
7RKp3nZlVmcrT0YCQXBrTwqZNh775z58GP2kZs+gVfNqBampJPzSB/hB62KkByhE
Cn6grrRjiAVwJyZVEvs/********+aE16emtX12RgI5JdzdOiNyZEQteU6zRBRJE
ocPWVxExaOpVVVJ5+UnW0LcalzA+lRGRTrQJ5JguAPiAOzRPTK/lYFFpCAl/F8wt
oAVG1c8zO2NcQ0Pko+fmeidRFxJ/did2btV+9Mkze3mBphwFmvnxa35LF+Cs/XJH
DwIDAQAB" />
and to the field I wish to encrypt Credit card number:
<input type="text" name="txtCreditCard" id="txtCreditCard" class="_data"
and also to the submit button
<input type="submit" name="btn_process" value="Submit" id="btn_process" class="_submit btn btn-success">
and here is my entire code
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
</script>
<script type="text/javascript" src="./-client-2.1.2.js"></script>
</head>
<body>
<h2>Data Collection</h2><p>
<form action="process.php" method="post">
<input id="txtEncryptionKey" name="txtEncryptionKey" class="encryptionkey"
type="hidden" value="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvWpIQFjQQCPpaIlJKpeg
irp5kLkzLB1AxHmnLk73D3TJbAGqr1QmlsWDBtMPMRpdzzUM7ZwX3kzhIuATV4Pe
7RKp3nZlVmcrT0YCQXBrTwqZNh775z58GP2kZs+gVfNqBampJPzSB/hB62KkByhE
Cn6grrRjiAVwJyZVEvs/2vrxaEpO+aE16emtX12RgI5JdzdOiNyZEQteU6zRBRJE
ocPWVxExaOpVVVJ5+UnW0LcalzA+lRGRTrQJ5JguAPiAOzRPTK/lYFFpCAl/F8wt
oAVG1c8zO2NcQ0Pko+fmeidRFxJ/did2btV+9Mkze3mBphwFmvnxa35LF+Cs/XJH
DwIDAQAB" />
Name: <input type="text" name="name"><br>
Credit card number: <input type="text" name="credit" id="credit" class="_data"><br>
<input type="submit" name="btn_process" value="Submit" id="btn_process" class="_submit btn btn-success">
</form>
</body>
</html>
So what happens here is,my credit card number is taken by the javascript as soon as I click on submit and is converted into a cipher text in the page it self which returns a unique cipher text as something like this
_cipherText=EIQ4H1Tmmxb0wvyfX9HvbSg0SH0ez1GyZSZjQ8OQqKOI8wtY%2B06uq9XlsDSQdmvRtZtCwJv%2FFbo6xxQ4ClPQZN06nO%2BB8Hw3PddPFLqGtViOMCpBif9Tv0LXPy4%2FQ2L%2F5crTjVQa6WdoJABTgFlOcJ8x%2Bs%2FSSmR5Hd7R9SznfpJQp64IQ6FP%2F2ASxpU14YswgDvTumYZ%2BPElbdKG5u71snNWoQNUClWFn4d8yk6%2BaJ%2FDUGWqotpxchhOFvHMePXsdE8%2F2mGlmz5iiOSH5LlvHptenQMtTvHjBuwdMo4rnutjJ%2FRqaR3sWcndZIWYmEZ7OfA%3D%3D
Now usinng a php I need to store this cipher into a variable and sent it to a web service
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg()
{
echo "Hello world!";
}
//creates a token.
function Tokenize()
{
// see details here http:/.turnapi.com/docs/1.0/rest-tokenize
$_id = "763994532109974";
$api_key = "0za2fOfdWU8575BnTH";
$encrypted_data = "acAx/CwWGCURIhwf7gIw36TFmXoGFrFa5l9hCgcGEW4/mVQAAzZuT4XRjktb7XR0sAthHTuSPYegNYUy7g1stP+ypfVBcH0hNiI72N22yy3WYp0VUfAKDp33HBgUVQwg0TWAenRSNbUwC0Qv49E5bubYo4YBnERWi4JNLJZPlEQUfjMovvWQsQdFHd7U79XJZnZQdW92CKFDrTX8bCS4/n0LDEEVBILJGBnjnvKOQjQarsX8OuU6/73qpy36f9Gz3+X6IRfRhVbINNV0Seii6qSXT03NyvbERDsU/CiOrZ1tY0RuiKh4rsvCfPYrX2h67ZZ7nzrz0DeV+BYyo0e06A==";
// CC data to tokenize..
$data = array(
'ID' =>_id,
'APIKey' => $api_key,
'EncryptedData' => $encrypted_data,
'TokenScheme' => 4
);
//convert to JSON
$json = json_encode($data);
echo "Step1 done... ";
echo $json;
//curl config
$url = 'https://test-api..com:8081/TokenServices.svc/REST/TokenizeFromEncryptedValue';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json', //we are using json in this example, you could use xml as well
'Content-Length: '.strlen($json),
'Accept: application/json') //we are using json in this example, you could use xml as well
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//call web service
$result = curl_exec($ch);
//decode result
$jsonResult = json_decode($result, true);
//handle result
if ($jsonResult['Success'] == FALSE)
{
echo "Error Message: ";
echo $jsonResult['Error'];
}
else
{
echo "your token is: ";
echo $jsonResult['Token'];
}
}
//writeMsg();
Tokenize();
?>
</body>
</html>
see here $encrypted_data = "acAx/CwWGCURIhwf7gIw36TFmXoGFrFa5l9hCgcGEW4/mVQAAzZuT4XRjktb7XR0sAthHTuSPYegNYUy7g1stP+ypfVBcH0hNiI72N22yy3WYp0VUfAKDp33HBgUVQwg0TWAenRSNbUwC0Qv49E5bubYo4YBnERWi4JNLJZPlEQUfjMovvWQsQdFHd7U79XJZnZQdW92CKFDrTX8bCS4/n0LDEEVBILJGBnjnvKOQjQarsX8OuU6/73qpy36f9Gz3+X6IRfRhVbINNV0Seii6qSXT03NyvbERDsU/CiOrZ1tY0RuiKh4rsvCfPYrX2h67ZZ7nzrz0DeV+BYyo0e06A=="
i need the cipher text i got using when i pressed the submit button..I need the statement in php to retieve this cipher text into the variable $encrypted_data (as of now I have given a standalone data there)
Also there is someproblem in the php section where some payloads are being sent to a webservice using JSON,but I dont seem getting a response( ie the token which is been sent bak as a response from the webservice wehn i sent my token_id,api key and encrypted data
can someone help in making this code working?Im actaully new to php and Im doing all this with the help of their documentation and online steps.Do bear this long question,im a begineer,so I have to present this compeletly.
Thanks in advance
If the CURL request is failing completely you should have an error in curl_error($ch) or if it returns a strange result you can get information about the last request made using curl_info($ch) so some combination of the two should help you work out where an error might be occurring.
Suppose i have many values here with form method POST
$_POST["value1"]
$_POST["value2"]
$_POST["value3"]
$_POST["value4"]
$_POST["value5"]
$_POST["value6"]
$_POST["value7"]
and i want to send them to nextpage.php
any function to do that? Besides using
<form method="POST" action="nextpage.php">
<input type="hidden" name="value1" value="value1 />
</form>
Passing without session
If there is no security concern and your post data contains something like search parameters . For example $_POST has
array('query'=>'keyword', 'orderby' => 'name', 'range' => '4-10' )
You can generate a query string from that data using http_build_query and create anchor tag for user to click and pass on that data to next page along with url.
$url = 'nextpage.php?' . http_build_query($_POST);
it will generate a url like nextpage.php?query=keyword&orderby=name&range=4-10 that you can use in html anchor tag and in next page you can get it from $_GET.
Using session
Alternatively you already have the option you storing it in $_SESSION and after using destroy the session in order to keep your site performance up.
store all your values in $_SESSION and use it in next page, or you can create URL using these values and redirect your page to nextpage.php
For passing post values to next page store the complete $_POST superglobal array variable into session and then on next page you can access those values using $_SESSION variable
Alternatively you can use curl to send HTTP request to next page using POST method
Then those variables will be accessible using $_POST variable on next page
Please refer the code snippet mentioned below as an example for sending HTTP request using post method through curl
$url='http://203.114.240.77/paynetz/epi/fts';
$data = array('login' => '11','pass' => 'Test#123','ttype' =>'NBFundTransfer','prodid'=>'NSE','amt'=>50,'txncurr'=>'INR','txnscamt'=>0,'clientcode'=>007,'txnid'=>uniqid(),'date'=>date('d/m/Y H:i:s'),'custacc'=>'123456789');
$datastring = http_build_query($data);
//die($url.'?'.$datastring);
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 180);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring);
$output = curl_exec($ch);
//echo $output; die;
curl_close($ch);
you can use Session or cookie to access to other page
Use this code.
<!DOCTYPE HTML>
<html>
<head>
<title>First page</title>
</head>
<body onload="document.getElementById('send').submit()">
<form id="send" action="next_page.php" style="display: none;">
<?PHP
foreach($_POST as $key => $val)
{
echo '<input type="hidden" name="'.$key.'" value="'.$val.'" />';
}
?>
</form>
</body>
</html>