PHP : How to customing URL - php

Maybe this is an easy question.
I have a variable which save the user id in it.
$user_id = $_REQUEST['user_id'];
and then I have the URL like this :
try
{
$response = $client->delete('admin/user/**USER ID SHOULD HERE**',[
'headers' => ['Authorization' => $_SESSION['login']['apiKey']]
]);
}
I already try to put variable $user_id like this admin/user/$user_id in that URL but nothing happens.'
This is the delete method()
public function delete($url = null, array $options = [])
{
return $this->send($this->createRequest('DELETE', $url, $options));
}
Am I wrote something wrong ?
Thanks :)

PHP variables will not be parsed inside of a single quoted string. You should use "admin/user/$user_id" if you want the variable's value to be used.
So you could write it like this:
$response = $client->delete("admin/user/$user_id",[
Or simply by concatenating the string and user id variable using .:
$response = $client->delete('admin/user/'.$user_id,[

Related

Create Json using Flight php

I have a problem where I have to create a JSON using Flight::json.
I have an array, called $data, that contains some elements like
$data[] = array('id'=>$temp,'type'=>'remote','url'=>$path);
where $id and $path have different values like this:
[id] => http://desktop-pqb3a65:8080/marmotta/resource/22086372-476f-4974-b538-64019ab678b3
[url] => D:\Software\Marmotta\marmotta-home\resources\1d\4d\ea\1d4dea13-f8e6-4cf0-b96a-f88b08efda2b
When I try to convert that in a JSON using:
Flight::json($data);
my PHP page returns me this format instead:
{"id":"http:\/\/desktop-pqb3a65:8080\/marmotta\/resource\/22086372-476f-4974-b538-64019ab678b3","type":"remote","url":"D:\\Software\\Marmotta\\marmotta-home\\resources\\1d\\4d\\ea\\1d4dea13-f8e6-4cf0-b96a-f88b08efda2b"}
I read the documentation and I tried to convert using another function:
Flight::json($data, $code = 200, $encode = false, $charset = 'utf-8');
but it return an error like:
500 Internal Server Error
Array to string conversion (8)
So can you help me to convert $data without this type of error? I must use Flight to convert my array.
Thanks all for help!
EDIT
I solve my problem creating a function like this:
Flight::map('jsonc', function($obj, $status = 200) {
Flight::response()
->status($status)
->header('Content-Type', 'application/javascript')
->write(utf8_decode(json_encode($obj, JSON_UNESCAPED_SLASHES)))
->send();
});
If you want unescaped slashes I believe you can pass that as the 5th function parameter named $option, see source.
public function _json(
$data,
$code = 200,
$encode = true,
$charset = 'utf-8',
$option = 0
)

Get URL parameters inside custom module

I've created a custom block like this:
class HelloBlock extends BlockBase implements BlockPluginInterface{
/**
* {#inheritdoc}
*/
public function build() {
$config = $this->getConfiguration();
$result = db_query('SELECT * FROM {test}');
return array(
'#theme' => 'world',
'#test' => $result
);
}
}
And I now want to programmatically get some parameter from the URL.
For example:
If the URL is http://localhost/drup/hello/5569 I want to get hold of the value 5569 inside my module.
I have tried arg(1) and drupal_get_query_parameters() but I got this error messages:
Call to undefined function `Drupal\hello\Plugin\Block\arg()`
and
Call to undefined function `Drupal\hello\Plugin\Block\drupal_get_query_parameters()`
How can I get the parameters?
Use \Drupal\Core\Routing;:
$parameters = \Drupal::routeMatch()->getParameters();
The named parameters are available as
$value = \Drupal::routeMatch()->getParameter('slug_name_from_route');
Where 'slug_name_from_router' comes from your routing.yml path property
path: '/your/path/{slug_name_from_route}'
If you want the raw parameter without any upcasting you can get
$value = \Drupal::routeMatch()->getRawParameter('slug_name_from_route');
I used to get the parameter value from URL (localhost/check/myform?mob=89886665)
$param = \Drupal::request()->query->all();
And applied in my select Query
$query = \Drupal::database()->select('profile_register', 'p1');
$query->fields('p1');
$query->condition('p1.mobileno', $edituseprof);
$query->condition('publishstatus', 'no');
$result = $query->execute()->fetchAll();
But on multiple parameter value, i am now successful(Ex: http://10.163.14.41/multisite/check/myform?mob=89886665&id=1)
$query = \Drupal::database()->select('profile_register', 'p1');
$query->fields('p1');
$query->condition('p1.mobileno', $edituseprof['mob']);
$query->condition('p1.ids', $edituseprof['id']);
$query->condition('publishstatus', 'no');
$result = $query->execute()->fetchAll();
arg() is deprecated in drupal 8, however we can get values like arg() function does in drupal 7 & 6
$path = \Drupal::request()->getpathInfo();
$arg = explode('/',$path);
print_r($arg); exit();
The output would be parameters in url except basepath or (baseurl),
Array
(
[0] =>
[1] => node
[2] => add
)
To get query parameter form the url, you can us the following.
If you have the url for example,
domainname.com/page?uid=123&num=452
To get "uid" from the url, use..
$uid = \Drupal::request()->query->get('uid');
To get "num" from the url, use..
$num = \Drupal::request()->query->get('num');
$route_match = \Drupal::service('current_route_match');
$abc = $route_match->getParameter('node'); //node is refrence to what you have written in you routing file i.e:
in something.routing.yml
entity.node.somepath:
path: '/some/{node}/path'
I have used {node} as arg(1). And I can access it by using *->getParameter('node');
Hope this will work.
If your url is like this below example
http://localhost/drupal/node/6666
Then you have to get the full url path by
$current_path = \Drupal::request()->getPathInfo();
then explode the path to get the arguments array.
$path_args = explode('/', $current_path);
Another example if value passed by a key in url like below where id contains the value
http://localhost/drupal?id=123
You can get the id by given drupal request
$id = \Drupal::request()->query->get('id');
Here's the example of accessing URL parameters and passing them to a TWIG template,
I am considering you have already created your module and required files and suppose "/test?fn=admin" is your URL
In Your .module file implement hook_theme and define variables and template name (Make sure you replace "_" with "-" when creating the template file)
function my_module_theme () {
return [
'your_template_name' => [
'variables' => [
'first_name' => NULL,
],
];
}
Now create your controller and put below code in it.
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
class MyModule extends ControllerBase {
public function content(Request $request) {
return [
'#theme' => 'my_template',
'#first_name' => $request->query->get('fn'), //This is because the parameters are in $_GET, if you are accessing from $_POST then use "request" instead "query"
];
}
}
Now in your TWIG file which should be "my-template.html.twig" you can access this parameter as,
<h3>First Name: {{ first_name }}</h3>
And its done.
Hope this helps.
The Drupal docs are great on this: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes
define your path variable in yaml
example.name:
path: '/example/{name}'
...
Add the variable in your method and use it
<?php
class ExampleController {
// ...
public function content($name) {
// Name is a string value.
// Do something with $name.
}
}
?>

How to make a PHP function with array of arguments

Hi I'm new with PHP usually I work with Java, how actually the right way to write an array of many arguments/parameters in this insertSQL function as I have a lot SQL objects have to be inserted. Thank you
//Store User into MySQL DB
$res = $db->insertSQL(
$data[$i]->id,
$data[$i]->location_id,
$data[$i]->section_id,
$data[$i]->inspection_date,
$data[$i]->photo_entire_path,
$data[$i]->photo_isolator_path,
$data[$i]->pole_no,
$data[$i]->pole_iron,
$data[$i]->pole_iron,
$data[$i]->pole_iron);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->id;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->id;
$b["status"] = 'no';
array_push($a,$b);
}
Right now it looks like this
$res = $db->insertSQL(
$data[$i]->id,
$data[$i]->location_id,
$data[$i]->section_id,
$data[$i]->inspection_date,
$data[$i]->photo_entire_path,
$data[$i]->photo_isolator_path,
$data[$i]->pole_no,
$data[$i]->pole_iron,
$data[$i]->pole_concrete,
$data[$i]->pole_wood,
$data[$i]->pole_condition_broken,
$data[$i]->pole_condition_tilt,
$data[$i]->pole_condition_shift,
$data[$i]->cros_arm_twist,
$data[$i]->cross_arm_rust,
$data[$i]->cross_arm_tilt,
$data[$i]->arm_tie_repair,
$data[$i]->arm_tie_rust,
$data[$i]->arm_tie_brace,
$data[$i]->isolator_fulcrum_r_leak,
$data[$i]->isolator_fulcrum_r_broken,
$data[$i]->isolator_fulcrum_s_leak,
$data[$i]->isolator_fulcrum_s_broken,
$data[$i]->isolator_fulcrum_t_leak,
$data[$i]->isolator_fulcrum_t_broken,
$data[$i]->isolator_pull_r_leak,
$data[$i]->isolator_pull_r_broken,
$data[$i]->isolator_pull_s_leak,
$data[$i]->isolator_pull_s_broken,
$data[$i]->isolator_pull_t_leak,
$data[$i]->isolator_pull_t_broken,
$data[$i]->arrester_r_broken,
$data[$i]->arrester_s_broken,
$data[$i]->arrester_t_broken,
$data[$i]->conductor_r_buyer,
$data[$i]->conductor_r_loose,
$data[$i]->conductor_s_buyer,
$data[$i]->conductor_s_loose,
$data[$i]->conductor_t_buyer,
$data[$i]->conductor_t_loose,
$data[$i]->connector_pg_r_35mm,
$data[$i]->connector_pg_r_70mm,
$data[$i]->connector_pg_r_150mm,
$data[$i]->connector_pg_s_35mm,
$data[$i]->connector_pg_s_70mm,
$data[$i]->connector_pg_s_150mm,
$data[$i]->connector_pg_t_35mm,
$data[$i]->connector_pg_t_70mm,
$data[$i]->connector_pg_t_150mm,
$data[$i]->bending_wire_r,
$data[$i]->bending_wire_s,
$data[$i]->bending_wire_t,
$data[$i]->ultrasonic_r,
$data[$i]->ultrasonic_s,
$data[$i]->ultrasonic_t,
$data[$i]->gws_exist,
$data[$i]->gws_not_exist,
$data[$i]->tree_exist,
$data[$i]->tree_not_exist,
$data[$i]->longitude,
$data[$i]->latitude,
$data[$i]->suggestion,
$data[$i]->descr
);
If I understand you correctly, this is what your function should look like:
function insertSQL(Array $sqlData)
{
Extract the values from the $sqlData variable here.
}
Try the following solution using call_user_func_array, func_get_args, json_encode and json_decode functions (to deal with an array of arguments):
...
$encoded = json_encode($data[$i]);
$fields_arr = json_decode($encoded, true); // to get an array of object properties with values.
// Also you should, probably, check the order of fields
$fields_arr['id'] = false;
$fields_arr = array_filter($fields_arr); // for removing the 'id' field
$args = ['id' => $data[$i]->id]; // first argument
call_user_func_array(array($db, 'insetSQL'), array_merge($args, $fields_arr)); // it also may require your current Namespace in the first arg
...
// Then, the 'insetSQL' method should process the arguments in the following manner:
function insetSQL($fields = []) {
$fields = func_get_args();
$id = $fields[0];
// adjusting the rest of fields ($fields[1], $fields[2] ...)
...
}
Although, I also would suggest to pass the initial object $data[$i] right into the insetSQL method as parameter and get the needed fields for sql INSERT statement
Create a JSON object as
$named_array = array(
"longitude" => "12.2"
"latitude" => "12.2"
);
$named_array = json_encode($named_array);
This $named_array can be array of fields.
You can pass $named_array object to other function as an argument.
Then use
$named_array = json_decode($named_array)
echo $named_array->longitude
You can access any Key Value pair as $named_array->latitude

undefined variable when testing the store() using phpunit in laravel-4

SOLVED
I have route that does a POST route towards store() in the controller.
I'm trying to test if the action is working properly.
Controller:
public function store() {
$d= Input::json()->all();
//May need to check here if authorized
$foo= new Foo;
$d = array();
$d['name'] = $d['name'];
$d['address'] = $d['address'];
$d['nickname'] = $d['nickname'];
if($foo->validate($d))
{
$new_foo= $foo->create($d);
return Response::json(Foo::where('id','=',$new_foo->id)->first(),200);
}
else
{
return Response::json($foo->errors(),400);
}
}
Now I'm trying to test this using a new class called FooTest.php
Here is the function i'm currently trying to do to make the check work:
public function testFooCreation()
{
$jsonString = '{"address": "82828282", "email": "test#gmail.com", "name":"Tester"}';
$json = json_decode($jsonString);
$this->client->request('POST', 'foo');
$this->assertEquals($json, $this->client->getResponse());
}
when I run phpunit in my cmd, I get an error stating that "name" is undefined. I know i'm not actually passing anything to the request so I'm positive that nothing is actually being checked, but my question is how do I actually pass my json strings to check?
Everytime I put the $json inside the client request, it asks for an array, but when I convert my json string to an array, json_decode wants a string.
UPDATE
I was messing around with the passing of input data and I came across this:
$input = [
'name' => 'TESTNAME',
'address' => '299 TESTville',
'nickname' => 't'
];
Input::replace($input);
Auth::shouldReceive('attempt')
->with(array('name' => Input::get('name'),
'address' => Input::get('address'),
'nickname' => Input::get('nickname')))
->once()
->andReturn(true);
$response = $this->call('POST', 'foo', $input);
$content = $response->getContent();
$data = json_decode($response->getContent());
But whenever I run the test, i still get "name:undefined" It's still not passing the input i've created.
$d= Input::json()->all();
The above statement gets Input in $d.
$d = array();
Now the last statement again initialises $d as an empty new array.
So there is no: $['name'] . Hence, Undefined.
I think, that's the problem with the above code.
Hope it helps :)
I was able to pass the input into a POST route from the test.
public function testFooCreation(){
$json = '{"name":"Bar", "address":"FooLand", "nickname":"foobar"}';
$post = $this->action('POST', 'FooController#store', null, array(), array(), array(), $json);
if($this->assertTrue($this->client->getResponse()->isOk()) == true && $this->assertResponseStatus(201)){
echo "Test passed";
}
}
Turns out that in order for me to actually pass input into the controller through test POST, I have to pass it through the 7th parameter.
I hope this helps others.
of course you get an error , just look at your code
$aInputs = Input::json()->all();
//May need to check here if authorized
$foo= new Foo;
$d = array();
$d['name'] = $d['name'];
$d['address'] = $d['address'];
$d['nickname'] = $d['nickname'];
your assigning the array to it self, which is empty

Slim PHP and GET Parameters

I'm using Slim PHP as a framework for a RESTful API.
How do I grab GET params from the URL in Slim PHP?
For example, if I wanted to use the following:
http://api.example.com/dataset/schools?zip=99999&radius=5
You can do this very easily within the Slim framework, you can use:
$paramValue = $app->request()->params('paramName');
$app here is a Slim instance.
Or if you want to be more specific
//GET parameter
$paramValue = $app->request()->get('paramName');
//POST parameter
$paramValue = $app->request()->post('paramName');
You would use it like so in a specific route
$app->get('/route', function () use ($app) {
$paramValue = $app->request()->params('paramName');
});
You can read the documentation on the request object
http://docs.slimframework.com/request/variables/
As of Slim v3:
$app->get('/route', function ($request, $response, $args) {
$paramValue = $request->params(''); // equal to $_REQUEST
$paramValue = $request->post(''); // equal to $_POST
$paramValue = $request->get(''); // equal to $_GET
// ...
return $response;
});
For Slim 3/4 you need to use the method getQueryParams() on the PSR 7 Request object.
Citing Slim 3 / Slim 4 documentation:
You can get the query parameters as an associative array on the
Request object using getQueryParams().
I fixed my api to receive a json body OR url parameter like this.
$data = json_decode($request->getBody()) ?: $request->params();
This might not suit everyone but it worked for me.
Slim 3
$request->getQueryParam('page')
or
$app->request->getQueryParam('page')
IF YOU WANT TO GET PARAMS WITH PARAM NAME
$value = $app->request->params('key');
The params() method will first search PUT variables, then POST variables, then GET variables. If no variables are found, null is returned. If you only want to search for a specific type of variable, you can use these methods instead:
//--- GET variable
$paramValue = $app->request->get('paramName');
//--- POST variable
$paramValue = $app->request->post('paramName');
//--- PUT variable
$paramValue = $app->request->put('paramName');
IF YOU WANT TO GET ALL PARAMETERS FROM REQUEST WITHOUT SPECIFYING PARAM NAME,
YOU CAN GET ALL OF THEM INTO ARRAY IN FORMAT KEY => VALUE
$data = json_decode( $app->request->getBody() ) ?: $app->request->params();
$data will be an array that contains all fields from request as below
$data = array(
'key' => 'value',
'key' => 'value',
//...
);
Hope it helps you!
Use $id = $request->getAttribute('id'); //where id is the name of the param
In Slim 3.0 the following also works:
routes.php
require_once 'user.php';
$app->get('/user/create', '\UserController:create');
user.php
class UserController
{
public function create($request, $response, array $args)
{
$username = $request->getParam('username'));
$password = $request->getParam('password'));
// ...
}
}
Not sure much about Slim PHP, but if you want to access the parameters from a URL then you should use the:
$_SERVER['QUERY_STRING']
You'll find a bunch of blog posts on Google to solve this. You can also use the PHP function parse_url.
Inside your api controller function write the following code of line:
public function your_api_function_name(Request $request, Response $response)
{
$data = $request->getQueryParams();
$zip = $data['zip'];
$radius = $data['radius'];
}
The variable $data contains all the query parameters.
Probably obvious to most, but just in case, building on vip's answer concerning Slim 3, you can use something like the following to get the values for the parameters.
$logger = $this->getService('logger');
$params = $request->getQueryParams();
if ($params) {
foreach ($params as $key => $param) {
if (is_array($param)) {
foreach ($param as $value) {
$logger->info("param[" . $key . "] = " . $value);
}
}
else {
$logger->info("param[" . $key . "] = " . $param);
}
}
}

Categories