URI must be a string or UriInterface with Goutte Laravel - laravel-5.4

I am getting the above error when i try to authenticate my proxy with Goutte Plugin in Laravel .
Below is the code :
$client = new Client();
$client->getClient()->setDefaultOption(['proxy' => 'http://x.x.x.x:80']);
$client->getClient()->setDefaultOption(['auth' => ['username', 'pass', 'Basic']]);
$url = 'http://ifconfig.me';
$crawler = $client->request('GET', $url);
$status = $client->getResponse()->getStatus();
dd($status);
any suggestions please . Thank you !

Try something like:
$crawler = $client->request('GET', ['base_uri' => $url]);

Related

Post a not empty file to Dspace with Curl

I am posting a file to dspace through dspace api, I am doing this with an action in php. With postman I send a form-data with the file, filename, bitstream id and token.
I am getting the temp file path with $_FILES and sending it by postfields curl option, but the file uploads empty, or with weird data, without its content.
public function actionSubirBitstream()
{
if (Yii::$app->request->isPost) {
$body = $_POST;
$prefijo = '/rest/items/';
$host = ConfiguracionDspace::find()->where("clave='host'")->one()->valor;
$puerto = ConfiguracionDspace::find()->where("clave='puerto'")->one()->valor;
$token = $body['token'];
$id = $body['id'];
$final = '/bitstreams';
$name = $body['name'];//nombre del archivo sin espacios
$params = "?name=$name";
$url = $host . ':' . $puerto . $prefijo . $id . $final . $params;
$file = $_FILES['file']['tmp_name'];
//$path = $body['path'];
//$file = new CURLFILE("$path");
$headers = array("Content-Type: application/json", 'Accept: application/json', "rest-dspace-token: " . $token);
$curl = curl_init($url);
$options = array(
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('file'=> $file,'name' => $name),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
}
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('photo'=> new CURLFILE('/C:/Users/pfile3.jpeg'),'name' => $name),
this is the example of uploading a file with form key as photo and another key name
in your screen shot you have id and token in form data but in code its not inside POSTFIELDS
in postman you can generate equalent code of request in any language , try generating the PHP equalent code and see if it works:
To do this just click code link under the request url after saving the request
I already post the file by the $_FILE variable, But what I needed to do was to use CURLFILE to create a new file, and give it the temp path of the file in the server
$file = $_FILES['file']['tmp_name'];
and this in the postfields
CURLOPT_POSTFIELDS => array('file'=> new CURLFile("$file"),'name' => $name),
Thanks for the help friends
Here the code:
public function actionSubirBitstream()
{
if (Yii::$app->request->isPost) {
$body = $_POST;
$prefijo = '/rest/items/';
$host = ConfiguracionDspace::find()->where("clave='host'")->one()->valor;
$puerto = ConfiguracionDspace::find()->where("clave='puerto'")->one()->valor;
$token = $body['token'];
$id = $body['id'];
$final = '/bitstreams';
$name = $body['name'];//nombre del archivo sin espacios
$params = "?name=$name";
$url = $host . ':' . $puerto . $prefijo . $id . $final . $params;
$file = $_FILES['file']['tmp_name'];
//$path = $body['path'];
//$file = new CURLFILE("$path");
$headers = array("Content-Type: application/json", 'Accept: application/json', "rest-dspace-token: " . $token);
$curl = curl_init($url);
$options = array(
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('file'=> new CURLFile("$file"),'name' => $name),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
}
The posted files with the rigth size(finally)
The form data I send by Postman, no need to use the field path

Yii2-user Dektrium - how to hash password

i want to do hash password and check that with database ( password_hash )
How can I do it????
$username = $auth['username'];
my password is
$password = $auth['password'];
i want hash that :
$find = \dektrium\user\models\User::findOne(['username' => $username, 'password_hash' => $password]);
You could generate the $hash using
$hash = Yii::$app->getSecurity()->generatePasswordHash($password);
$find = \dektrium\user\models\User::findOne(['username' => $username,
'password_hash' => $hash]);
Th code belowe is from dektrium/yii2-user/helpers/password.php ( the code for hash function ..of dektrium adn as you see the extensions use the generatePasswordHash and a cost
public static function hash($password)
{
return \Yii::$app->security->generatePasswordHash($password,
\Yii::$app->getModule('user')->cost);
}
default cost = 8
I know quite late to answer this, but for those who are still looking.. I recently encountered this issue and after lots of testing below code worked for me:
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => function ($username, $password) {
$user = \dektrium\user\models\User::findOne(['username' => $username]);
if ($user->validate($password)) {
return $user;
}
return null;
}
];

Send JSON from HTTPS to HTTP

I use Request solution for ajax-request, but I get an error:
reqwest.min.js:6 Mixed Content: The page at 'https://...' was loaded
over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://...'. This request has been blocked; the content must be
served over HTTPS.
Server-side code (i'm using wordpress plugin for this):
add_action('wp_ajax_nopriv_wpse144893_search', 'wpse144893_search_data'); // allow logged out users
add_action('wp_ajax_wpse144893_search', 'wpse144893_search_data'); // allow logged in users
function wpse144893_search_data(){
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
$errors = array();
$data = array(
'status' => 'error',
'message' => '',
'result' => array()
);
if(!isset($_REQUEST['term']) || empty($_REQUEST['term']))
$errors[] = 'No search term given!';
if(!isset($_REQUEST['limit']) || empty($_REQUEST['limit']))
$limit = 10;
else
$limit = (int) $_REQUEST['limit'];
if(empty($errors)){
$term = sanitize_text_field($_REQUEST['term']);
// setup query data
$args = array(
'posts_per_page' => $limit,
's' => $term
);
$query = new WP_Query($args); // run query
$results = array();
if($query->have_posts()): while($query->have_posts()): $query->the_post();
$post_item = array(
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'permalink' => get_permalink()
);
$results[] = $post_item;
endwhile;
$data['status'] = 'success';
$data['message'] = 'Results found!';
$data['result'] = $results;
else:
$errors[] = 'No post found!';
$data['message'] = $errors;
endif;
}
echo json_encode($data); // print json
die(); // kill the script
}
Client-side code (request plugin):
reqwest({
url: 'http://...'
, type: 'json'
, method: 'get'
, crossOrigin: true
, withCredentials: true
, error: function (err) { alert('1'); }
, success: function (resp) {
alert('2');
}
})
I tried use this header('Content-type: application/json');header('Access-Control-Allow-Origin: *'); (see in server code above) but it does not solve the problem.
Problem is solved by moving second server to HTTPS...

How to pass params for Vend Api?

I am trying to use VEND API but I have no clue how to pass parameters for doing various things. I found a set of codes in the API doc but can't get through it. Below is what I been up to.
<?php
/**
*
* A class made for utility methods around Vend's API
*
*
*/
class VendApiUtils {
/**
* A simple static method to call Vend API urls
*
* #param string $url
* #param string $username
* #param string $password
* #param array $params <OPTIONAL>
*/
public static function requestVendApiUrl($url, $username, $password, $params = array())
{
// is cURL installed?
if (!function_exists('curl_init')) {
throw new Exception('CURL is not installed!');
}
// Create a new cURL instance
$ch = curl_init();
$opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array('data' => json_encode($params)),
CURLOPT_TIMEOUT => 120,
CURLOPT_FAILONERROR => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_USERPWD => "$username:$password"
);
// Assign the cURL options
curl_setopt_array($ch, $opts);
// Get the response
$response = curl_exec($ch);
print_r($response);
// Close cURL
curl_close($ch);
// Execute the request & get the response
echo $response;
}
}
$your_domain='https://mydomain.vendhq.com';
$your_username='myuser';
$your_password='mypass';
$params = array('GET'=>'/api/stock_movements');
$response = VendApiUtils::requestVendApiUrl($your_domain, $your_username,$your_password, $params);
//echo $response;
?>
Any Help would be highly appreicated.
Regards,
Abnab
I'm not sure why you think the URL needs to go into the $params array; that looks to me like the place for, well, params. I think the function is intended to be used more like this:
// Fixed parts, same for any request
$domain='https://mydomain.vendhq.com';
$username='myuser';
$password='mypass';
// Variable parts, depending on what you want to do
$url = '/api/stock_movements';
$params = array('some_key' => 'some_value');
$response = VendApiUtils::requestVendApiUrl($domain . $url, $username, $password, $params);
Please check pyvend client library.

write custom query with zend framework 2

I want to perform a custom query in zf2. Now I have a Album controller and AlbumTable. Inside AlbumTable, I want to perform an join operation. But I am unable to do this.Please give me some suggation.
below my code:
namespace WebApp\Table;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Sql;
new Zend\Db\Adapter\Adapter;
class UserTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function searchUser($search)
{
$search = "mehedi";
$adapter = new Adapter();
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('foo');
$select->join('profiles', 'user.user_id = profiles.ownerId', array('name'));
$select->where(array('id' => 2));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
return $results;
}
}
The issue is you are trying to instantiate your Adapter with no parameters, when it requires at least a driver :
$adapter = new Adapter(); // Bad
$adapter = new Adapter($driver); // ..
You should use the ServiceManager to get your Adapter, did you start with the Skeleton Application?
It should have already been injected into the TableGateway for you..
$adapter = $this->getAdapter();
An example of instantiating an Adapter:
$config = $serviceLocator->get('Config');
$adapter = new Adapter($config['db']);
where you specify your setup inside your config, local.php will do:
return array(
/**
* Database Config
*/
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=dbname;host=localhost',
'username' => 'root',
'password' => 'password',
),
I got some solution of this problem with helping all of here.
$adapter = $this->tableGateway->getAdapter();
/* $adapter variable is used to fetch Adapter
configuration from serivce manager. */
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('foo');
$select->join('profile', 'foo.skillId = profile.id', array('name'));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
/* if you want you can see your
desired output in here. */
foreach ($results as $person) {
echo "<pre>";
print_r($person);
}
return $results;
It's because the join method expects an array for the join table. Also I personally would prefix the tables in the query, something like this:-
$search = "mehedi";
$adapter = new Adapter();
$sql = new Sql($adapter);
$select = $sql->select();
// PREFIXED THE foo table f
$select->from(array('f' =>'foo'));
// PREFIXED THE profiles table p
$select->join(array('p' => 'profiles'), 'user.user_id = profiles.ownerId', array('name'));
$select->where(array('id' => 2));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
return $results;