How to suppress curl JSON response - json

Here is the code which in a file from the browser:
<?php
curl_setopt_array($ch = curl_init(), array(
CURLOPT_URL => "https://somesite/messages.json",
CURLOPT_POSTFIELDS => array(
"token" => "xxx",
"user" => "xxx",
"message" => "hello world",
)));
curl_exec($ch);
curl_close($ch);
?>
This runs properly and returns this to the browser:
{"status":1,"request":"34bb823184583c8bca6d9d56d297d795"}
I want to suppress that message and replace it with something else like a text string such as "worked". \
Displaying an image or pointing to a success .html page would be nice.
This is my first use of curl.

set CURLOPT_RETURNTRANSFER to true and let curl_exec($ch) return a value in a variable
<?php
curl_setopt_array($ch = curl_init(), array(
CURLOPT_URL => "https://somesite/messages.json",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
"token" => "xxx",
"user" => "xxx",
"message" => "hello world",
)));
$result = curl_exec($ch);
curl_close($ch);
echo "some text"; // or echo file_get_content('some_html_page.html');
?>

Related

Yii2 Select2 multiple with ajax: Illegal offset type

I use Yii2 and widget Select2. I want onkeyup to search products from table "Products" with options for multiple select, because i must save result in second table "rel_products". I do know why it return error : "Illegal offset type"
Here is model:
public $products = array(); =>because i write result in second table
here is view:
$url = \yii\helpers\Url::to(['/product/prodlist']);
echo $form->field($model, 'products')->widget(Select2::classname(), [
'initValueText' => 'Search for a city ...', // set the initial display text
'model' => $model,
'attribute' => 'products',
'theme' => 'bootstrap',
'options' => ['placeholder' => 'Search for a city ...'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => $url,
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(product) { return product.text; }'),
'templateSelection' => new JsExpression('function (product) { return product.text; }'),
],
]);
Here is Controller:
public function actionProdlist($q = null, $id = null) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$query = new Query;
$query->select()
->from('product')
->joinWith('translation')
->where(['like', 'title', $q])
->limit(20);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
elseif ($id > 0) {
$out['results'] = ['id' => $id, 'text' => Product::find($id)->title];
}
return $out;
}
change in model:
public $products; =>because i write result in second table

'value' function doesn't work in Yii2 view

in my view I'm trying to add 'value' function, which shows the field if the id = 0, otherwise it doesn't show it. I'm trying to do it like so:
echo $form->field($model, 'test', [
'options' => [
'class' => $twoColumns . ' required',
'value' => function ($model) {
return $model->testvar == 0 ? 'Test' : null;
}
]
])
I've added function into 'value', but somehow it doesn't work. Could someone explain me why?
I'm getting htmlspecialchars error
Closure here is not supported and there is no reason to use it anyway.
You only need something like:
$model->interest = null;
if ($model->is_interest_variable == 0) {
$model->interest = 'Test';
}
echo $form->field($model, 'interest', [
'addon' => [
'append' => [
'content' => '%',
],
],
'options' => [
'class' => $twoColumns . ' required',
]
])->textInput([
'placeholder' => '0.0000',
'class' => 'form-control amount-4'
]);

Login with other fields using Auth in cakephp3

Problem regarding login with Auth in cakephp3
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Articles',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
it only allows me to use username by default, Okay If I wanted to login using email, that through I have searched and got this:
UserController.php
public function login()
{
if ($this->request->is('post'))
{
$this->Auth->config('authenticate', [
'Form' => [
'fields' => ['username' => 'email']
]
]);
$this->Auth->constructAuthenticate();
$this->request->data['email'] = $this->request->data['username'];
unset($this->request->data['username']);
$user = $this->Auth->identify();
if ($user)
{
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
I can change fields from username to email and reconstruct it but What if I wanted to login with ID field.
$this->Auth->config('authenticate', [
'Form' => [
'fields' => ['username' => 'id']
]
]);
If I change from email to id, it is not allowing me to login. Do I have to use then queries instead?
I just had the same issue and solved it like this using cakePHP 3.3
Your AppController
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => $this->referer(),
'loginRedirect' => [
'plugin' => false,
'controller' => 'Pages',
'action' => 'home',
],
]);
Your UserController (login action)
/**
* #return Response|null
*/
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('Your username or password is incorrect.');
}
}
Your basic Users/login.ctp template
<?= $this->Form->create() ?>
<?= $this->Form->input('email') ?>
<?= $this->Form->input('password') ?>
<?= $this->Form->button('Login') ?>
<?= $this->Form->end() ?>
Your problem is, when you changed the 'email' field to 'id' in the below code,
`('authenticate', ['Form' => ['fields' => ['username' => 'id']]]);`
you should have changed the input field of your view 'login.ctp'.
from this: <?= $this->Form->input('email') ?>
to this: <?= $this->Form->input('id') ?>

perl JSON decode is not giving expected result

I have below JSON input -
{"links":{"self":"/some/path"},"data":
[{"type":"some_service","id":"foo","attributes":
{"created":true,"active":true,"suspended":false}},
{"type":"some_service","id":"dummy","attributes":{"created":false}}]}
I am using below code -
use strict;
use warnings;
use JSON::XS;
use Data::Dumper;
my $result = decode_json($input);
print Dumper($result) . "\n";
But i am getting below output -
$VAR1 = {
'data' => [
{
'attributes' => {
'active' => bless( do{\(my $o = 1)}, 'JSON::XS::Boolean' ),
'created' => $VAR1->{'data'}[0]{'attributes'}{'active'},
'suspended' => bless( do{\(my $o = 0)}, 'JSON::XS::Boolean' )
},
'id' => 'foo',
'type' => 'some_service'
},
{
'id' => 'dummy',
'attributes' => {
'created' => $VAR1->{'data'}[0]{'attributes'}{'suspended'}
},
'type' => 'some_service'
}
],
'links' => {
'self' => '/some/path'
}
};
Looks like the value in 'created' is $VAR1->{'data'}[0]{'attributes'}{'active'} which does not seems to be accurate and same happens at other places too.
Am i missing somewhere in code or the JSON input has some error?
Kindly provide your suggestions.
The JSON decoder is just "mapping/pointing" the values to previous values that have already been parsed. You can see your first created points to
$VAR1->{'data'}[0]{'attributes'}{'active'},
, the value of which is true, just like active should be. You are looking at the Data::Dumper representation of the hash array.
If you were to retrieve an element from the Perl variable, you would find that it matches up with your original input:
print $result->{"data"}[0]->{"attributes"}->{"created"}; # prints 1
To print the Data::Dumper output without this occurring, simply set this flag in your script:
$Data::Dumper::Deepcopy = 1;
Why do you think it's inaccurate? If we look at the JSON, active and created both have the same value: true. Maybe you'll find it clearer to dump the structure as follows:
use JSON::XS qw( decode_json );
use Data::Dumper qw( );
my $data = decode_json(<<'__EOI__');
{"links":{"self":"/some/path"},"data [{"type":"some_service","id":"foo","attributes": {"created":true,"active":true,"suspended":false}}, {"type":"some_service","id":"dummy","attributes":{"created":false}}]}
__EOI__
print(Data::Dumper->Dump(
[ JSON::XS::true, JSON::XS::false, $data ],
[qw( true false data )],
));
Output:
$true = bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' );
$false = bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' );
$data = {
'data' => [
{
'attributes' => {
'active' => $true,
'created' => $true,
'suspended' => $false
},
'id' => 'foo',
'type' => 'some_service'
},
{
'attributes' => {
'created' => $false
},
'id' => 'dummy',
'type' => 'some_service'
}
],
'links' => {
'self' => '/some/path'
}
};

generate json data with mysql help

Any idea how to get this out put with queries?
$obj = array(
"attr" => array(
"id" => 1,
"rel" => "drive"
),
"data" => "My Documents",
"children" => array(
array(
"attr" => array(
"id" => 2,
"rel" => "file"
),
"data" => "file1.doc",
"state" => ""
)
)
);
echo json_encode($obj);
i need to loop only below part of above code.
array(
"attr" => array(
"id" => 2,
"rel" => "file"
),
"data" => "file1.doc",
"state" => ""
)
any help would be great.
Thanks
$x = 0;
while($row = mssql_fetch_object($query) )
{
$json[$x] = array (
'lastname' => $row->firstname,
'firstname' => $row->lastname
);
$x++;
}
echo json_encode($json);
You might try compiling and installing the third-party JSON UDFs:
http://www.mysqludf.org/lib_mysqludf_json/index.php