I have the issuses with VK access_token. I added to &access_token= a Secure key of the project, but VKontakte still says that User authorization failed: invalid access_token (4)..
How I can fix it?
$url = 'personasvk';
function get_vk($username) {
$get = get_data('https://api.vk.com/method/users.get?user_id='.$username.'&v=5.85&access_token=SECURE_KEY_OF_PROJECT');
$result = json_decode($get, true);
if (empty($result['response'][0]['gid']) || empty($result['response'][0]['screen_name'])) {
return false;
} else {
return $result;
}
}
$vk_data = get_vk($url);
$title = $vk_data['response'][0]['screen_name'];
$link_id = $vk_data['response'][0]['gid'];
$image = $vk_data['response'][0]['photo'];
echo $title;
Try adding it in the body of your POST request.
I am not familiar with PHP, but this curl gives me all the necessary information.
curl -X POST \
-d 'v=5.85' \
-d 'access_token=SECURE_KEY_OF_PROJECT' \
-d 'user_id=700' \
https://api.vk.com/method/users.get
Related
So what I'm trying to do is: with a link similar to: http://localhost/API-REST/Endpoints/ajoutDeMessage.php?contenu='Hello'&idUser=4. For now, I'm only testing my request with Postman. So I'm putting this URL directly in Postman, and press send.
When I'm doing a request without a body, it works fine.
So, I need to send a string and an id through the URL, and with a function, I'm inserting these data in my database.
With the php://input, I expect to have the variables contenu and idUser in the body for a SQL request.
What I want to do next is a React app which will communicate with the API (but that's not related for now).
So here is my code:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require_once('../Configuration/database.php');
require_once('../Users/messages.php');
$database = new Database();
$db = $database->getConnection();
$json = json_decode(file_get_contents("php://input"),true);
var_dump($json);
if(!empty($json->contenu) && !empty($json->idUser)){
$contenu = strip_tags($json->contenu);
$idUser = strip_tags($json->idUser);
$message = new Messages($db);
if ($message->addMessage($contenu,$idUser)){
http_response_code(201);
$response['message'] = 'GOOD ENTRY';
}else{
http_response_code(400);
$response['message'] = 'BAD ENTRY';
}
}else{
http_response_code(400);
$response['message'] = 'INCOMPREHENSIBLE DATA';
}
echo json_encode($response);
} else {
http_response_code(405);
$response['error_code'] = 405;
$response['message'] = 'BAD REQUEST TYPE';
echo json_encode($response);
}
There is no post body
i'm putting this url directly in postman, and press send.
I don't use postman myself, but doing this will generate a post request with no data it's the equivalent of:
curl -X POST http://example.com
That's not passing a post body at all. The intent is more like:
curl http://example.com
-H 'Content-Type: application/json'
-d '{"contenu":"Hello","idUser":4}'
This is why file_get_contents("php://input") doesn't return anything.
Note that html form data is available via $_POST - but only for urlencoded POST bodies (which I understand not to be the intent of the question).
Where is the data?
i'm putting this url directly in postman, and press send.
Returning to this quote, the only place for the data is in the url - that is not the normal way to pass data with a post request.
Url arguments are available via $_GET, with the url in the question this code:
<?php
var_dump($_GET);
will output:
array(2) {
["contenu"]=>
string(7) "'Hello'"
["idUser"]=>
string(1) "4"
}
A detail, but note the string includes the single quotes which are in the url (that are probably not desired).
What's the right way to do this?
With a request being made like this:
curl http://example.com
-H 'Content-Type: application/json'
-d '{"contenu":"Hello","idUser":4}'
That data can be accessed like so:
<?php
$body = file_get_contents('php://input');
$data = json_decode($body, true);
$jsonError = json_last_error();
if ($jsonError) {
print_r(['input' => $body, 'error' => json_last_error_msg()]);
exit;
}
echo $data['contenu']; // Hello
echo $data['idUser']; // 4
...
This is very similar to the code in the question, the error appears to primarily be how the request is being made rather than the php logic.
I have the command:
curl -k -u **username:password** --request POST -H "Content-Type:application/json" -d "{\"name\":\"John\",\"age\":\"31\",\"test\":\"New York\"}" http://siteteste.com/receive.php
I want to get the server-side username and password with PHP.
I am using the POST method.
My PHP:
<?php
// Only allow POST requests
***// I want the username and password here with PHP POST.***
***$user = $_POST[""]; // Not working :(***
if (strtoupper($_SERVER['REQUEST_METHOD']) != 'POST') {
throw new Exception('Only POST requests are allowed');
}
// Make sure Content-Type is application/json
$content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
if (stripos($content_type, 'application/json') === false) {
throw new Exception('Content-Type must be application/json');
}
// Read the input stream
$body = file_get_contents("php://input");
// Decode the JSON object
$object = json_decode($body, true);
// Throw an exception if decoding failed
if (!is_array($object)) {
throw new Exception('Failed to decode JSON object');
}
// Display the object
$getit = $object['test'];
print $getit;
How can I do it?
I try, but not working.
I search StackOverflow and others site, but not found informatio
Your body is json-encoded.
You will get your data here:
$body = file_get_contents("php://input");
// Decode the JSON object
$object = json_decode($body, true);
var_dump($object); // <-- do this to view your data.
The -u option you are using is used for authentication. For example for http-authentication.
In case you want to add data, you have to modify your -d parameter. For example, here i added a user:
-d "{\"name\":\"John\",\"age\":\"31\",\"test\":\"New York\",\"user\":\"test-user\"}"
Or in the other case you really want the http-authentication-data use:
$_SERVER['PHP_AUTH_USER']
$_SERVER['PHP_AUTH_PW']
For some automated tests that I did, I had to record requests from Chrome, and then repeat them in curl commands.
I start checking how to do it...
The way I did it was:
Access websites when the developers tools open.
Issue requests, make sure they are logged in the console.
Right click on the requests, select 'Save as HAR with content', and save to a file.
Then run the following php script to parse the HAR file and output the correct curls:
script:
<?php
$contents=file_get_contents('/home/elyashivl/har.har');
$json = json_decode($contents);
$entries = $json->log->entries;
foreach ($entries as $entry) {
$req = $entry->request;
$curl = 'curl -X '.$req->method;
foreach($req->headers as $header) {
$curl .= " -H '$header->name: $header->value'";
}
if (property_exists($req, 'postData')) {
# Json encode to convert newline to literal '\n'
$data = json_encode((string)$req->postData->text);
$curl .= " -d '$data'";
}
$curl .= " '$req->url'";
echo $curl."\n";
}
Don't know in which version they added this feature, but Chrome now offers a "Save as cURL" option:
You can access this by going under the Network tab of the Developer Tools, and right clicking on a XHR request
Building upon the code by ElyashivLavi, I added a file name argument, error checking when reading from the file, putting curl in verbose mode, and disabling the Accept-encoding request header, which usually results in getting back compressed output that would make it hard to debug, as well as automatic execution of curl commands:
<?php
function bail($msg)
{
fprintf(STDERR, "Fatal error: $msg\n");
exit(1);
}
global $argv;
if (count($argv) < 2)
bail("Missing HAR file name");
$fname = $argv[1];
$contents=file_get_contents($fname);
if ($contents === false)
bail("Could not read file $fname");
$json = json_decode($contents);
$entries = $json->log->entries;
foreach ($entries as $entry)
{
$req = $entry->request;
$curl = 'curl --verbose -X '.$req->method;
foreach($req->headers as $header)
{
if (strtolower($header->name) === "accept-encoding")
continue; // avoid gzip response
$curl .= " -H '$header->name: $header->value'";
}
if (property_exists($req, 'postData'))
{
# Json encode to convert newline to literal '\n'
$data = json_encode((string)$req->postData->text);
$curl .= " -d '$data'";
}
$curl .= " '$req->url'";
echo $curl."\n";
system($curl);
}
Is it possible to get the cURL command from the PHP's object? I mean, make this:
$ch = curl_init('http://'.$host . $url);
//...
$response = curl_exec($ch);
Look like this:
curl -X POST -d http://www.google.com/
Is it possible? Is there a trick or a native method?
It's not possible to get the command line equivalent (options) to execute the tool curl from the PHP library cURL.
Both tool and PHP library use libcurl to perform client-side URL transfers, which is a C library. But that's all. Very likely you have a PHP equivalent for most of curl options available in cURL, however, it's not a rule.
I don't think you simply would like to do requests from your application using curl, if you want so, you'd be using PHP library's. That said, there is no easy way to get what you want. Probably you'll need to build the command as a string. Something like this:
function getCurlCommand($url, $method = 'GET', array $params = null /* , ... */ )
{
$cmd = 'curl';
$params = [];
if ($method !== 'GET') {
$params[] = '-X ' . $method;
}
if ($data !== null) {
$params[] = '-d ' . http_build_query($data);
}
// ...
return $cmd . ' ' . implode(' ', $params) . ' ' . $url;
}
I have to execute this curl command in php:
curl --digest -u YourApiKey:YourApiSecret "http://api.moodstocks.com/v2/ref/YourID" --form image_file=#"image.jpg" -X PUT
So far I have this:
function ms_addimage($file, $hash_id){
$postdata = array("image_file" => "#/".realpath($file));
$opts[CURLOPT_URL] = $this->API_BASE_URL . "ref/".$hash_id;
$opts[CURLOPT_VERBOSE] =1;
$opts[CURLOPT_POST] =true;
$opts[CURLOPT_POSTFIELDS] =$postdata;
$ch = curl_init();
curl_setopt_array($ch, $opts);
$raw_resp = curl_exec($ch);
echo "Response " . $raw_resp . "\n";
curl_close($ch);
}
The file path is correct but I am missing something.
How do I pass the --form parameter and the PUT argument?
So I was missing the following:
$opts[CURLOPT_CUSTOMREQUEST] = "PUT";
Now it is working.