How can I get the S3 bucket Object URL after pointing my subdomain? - amazon-s3

I have created a AWS S3 bucket where I am storing PDF files. Now I am fetching the object URL properly like below:
https://bucketnametest.s3.amazonaws.com/sample.pdf.
Now, I have pointed the AWS S3 bucket URL to my custom subdomain. So, I can directly hit the browser with https://customdomain.com/sample.pdf and I am getting the PDF as well. But the problem is, I am not getting the object URL like "https://customdomaintest.com/sample.pdf". Can anyone help how to fetch the bucket object URL like "https://customdomain.com/sample.pdf".?
Using the below code, I am getting the object URL like "https://bucketname.s3.amazonaws.com/sample.pdf". But I want it like "https://customdomain.com/sample.pdf".
<?php
require 'vendor/autoload.php';
$s3 = new Aws\S3\S3Client([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => [
'key' => "xxxxxxxxxxxxxxxx",
'secret' => "xxxxxxxxxxxxxxxxxxxx",
]
]);
$source = 'pdf/document91.pdf';
$uploader = new Aws\S3\MultipartUploader($s3, $source, [
'bucket' => 'bucketname',
'key' => "document91.pdf",
'Body' => "",
'ACL' => 'public-read',
]);
try {
$result = $uploader->upload();
echo "Upload complete: {$result['ObjectURL']}\n";
} catch (MultipartUploadException $e) {
echo $e->getMessage() . "\n";
}

Related

how to send a file from one web system to another using guzzle client in laravel

i want to send an image from one web system(A) to another web system(B).the image is saved in system(A) and then sent to system(B).am using guzzle http client to achieve this.my api in system (B) works very well as i have tested it in postman.the part i have not understood why its not working is in my system(A) where i have written the guzzle code.i have not seen any error in my system(A) log file but the file isnt sent to system (B).
here is my image save function is system(A).
public function productSavePicture(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'product_id' => 'required',
]);
$product_details = product::where('systemid', $request->product_id)->first();
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension(); // getting image extension
$company_id = Auth::user()->staff->company_id;
$filename = ('p' . sprintf("%010d", $product_details->id)) . '-m' . sprintf("%010d", $company_id) . rand(1000, 9999) . '.' . $extension;
$product_id = $product_details->id;
$this->check_location("/images/product/$product_id/");
$file->move(public_path() . ("/images/product/$product_id/"), $filename);
$this->check_location("/images/product/$product_id/thumb/");
$thumb = new thumb();
$dest = public_path() . "/images/product/$product_id/thumb/thumb_" . $filename;
$thumb->createThumbnail(
public_path() . "/images/product/$product_id/" . $filename,
$dest,
200);
$systemid = $request->product_id;
$product_details->photo_1 = $filename;
$product_details->thumbnail_1 = 'thumb_' . $filename;
$product_details->save();
// push image to system(B)
$imageinfo = array(
'file' => $filename,
'product_id' => $product_details->id,
);
$client = new \GuzzleHttp\Client();
$url = "http://systemb/api/push_h2image";
$response = $client->request('POST',$url,[
// 'Content-type' => 'multipart/form-data',
'multipart' => [
[
'name' => 'imagecontents',
'contents' => fopen(public_path() . ("/images/product/$product_id/") . $filename, 'r'),
// file_get_contents(public_path("/images/product/$product_id/thumb/thumb_" . $filename)),
'filename' =>$filename
],
[
'name' => 'imageinfo',
'contents' => json_encode($imageinfo)
],
]
]);
}
}
}
i have followed every step in the documentation but still the process isnt working.where might i be making a wrong move?the laravel version of my project is 5.8 and the version of the guzzle http client is 7.4.1

Rest Unknown Error while uploading image on wordpress media using guzzle

Rest Unknown Error while uploading image on wordpress media using guzzle:
Actually m trying to upload image using guzzle but the wordpress is giving server error that rest upload unknown error ... Please tell what i am doing wrong???
public function store(Request $request)
{
//
$image_path = $request->file('image')->getPathname();
$image_mime = $request->file('image')->getmimeType();
$image_org = $request->file('image')->getClientOriginalName();
$username = '####';
$password = '#######';
$http = new \GuzzleHttp\Client;
$response = $http->POST('websitenameurl/wp2/wp-json/wp/v2/media/',
[
'headers'=>[
'Authorization'=> 'Basic ' . base64_encode( $username . ':' . $password),
'Content-Type' => 'Application/json'
],
'multipart' => [
[
'name' => 'image',
'filename' => $image_org,
'Mime-Type'=> $image_mime,
'contents' => fopen($image_path, 'r' ),
],
],
]);
$result = json_decode((string)$response->getBody(),true);
return $result;
}

File upload using http request in Extbase, TYPO3 CMS

We want to upload file using http request to some api endpoint in TYPO3 9.
File upload can be done using \TYPO3\CMS\Core\Http\RequestFactory in
TYPO3
$filePath = '/var/www/html/MyTypo3Project/Image.png';
$username = 'test';
$password = 'test';
$multipart = [
// File Parameter
[
'name' => 'Image', //Api side parameter name
'contents' => fopen(realpath($filePath), 'r'),
'filename' => 'MyCustomName.png' // Custom filename
],
//Other Parameters
[
'name' => 'custom_param',
'contents' => 'custom_param_value'
]
];
// Request options along with auth header
$additionalOptions = [
'auth' => [$username, $password],
'multipart' => $multipart,
];
$requestFactory = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Http\RequestFactory::class);
$response = $requestFactory->request(
$url, // Api Endpoint Url
'POST',
$additionalOptions // Passing the additional options
);

API returning 400 Bad Request response

I have built an API and an application that uses that API. Everything was working but now, for some reason, I get a 400 Bad Request response. I am not sure if I changed something in the code so I wanted to double check it was correct.
So my API call is this
$client = new GuzzleHttp\Client();
$jsonData = json_encode($data);
$req = $client->request('POST', 'https://someurl.com/api/v1/createProject', [
'body' => $jsonData,
'headers' => [
'Content-Type' => 'application/json',
'Content-Length' => strlen($jsonData),
]
]);
$output = $req->getBody()->getContents();
The API has a route set up correctly which uses post. The function it calls is correct, and I have changed it for testing to simply return
return response()->json(["Success", 200]);
When I test the API out within Postman, I can see that Success is returned. When I test the API within the other application I have built, I dont even see a POST request within the console, I am just displayed a Laravel error 400 Bad Request.
What could be the cause of this issue?
Thanks
Update
I have changed the request to this
$data= json_encode($data);
$req = $client->post('https://someurl.com/api/v1/createProject', [
'body' => $data
]);
If I output $data after it has been encoded, I get something like this
{
"projectName":"New Project",
"clientName":"Test Client",
}
Within the controller function of the API that is being called, I simply do
return response()->json(['name' => $request->input('clientName')]);
The 400 error has now gone, but I now get null returned to me
{#326 ▼
+"name": null
}
Request is being injected into the function as it should be. Should I be returning the data in a different way?
Thanks
Probably you did $ composer update and Guzzle updated.
So if you are using newest Guzzle (guzzlehttp/guzzle (6.2.2)) you do POST request:
$client = new GuzzleHttp\Client();
$data = ['name' => 'Agent Smith'];
$response = $client->post('http://example.dev/neo', [
'json' => $data
]);
You do not need to specify headers.
To read response you do following:
$json_response = json_decode($response->getBody());
My full example (in routes file web.php routes.php)
Route::get('smith', function () {
$client = new GuzzleHttp\Client();
$data = ['name' => 'Agent Smith'];
$response = $client->post('http://example.dev/neo', [
'json' => $data,
]);
$code = $response->getStatusCode();
$result = json_decode($response->getBody());
dd($code, $result);
});
Route::post('neo', function (\Illuminate\Http\Request $request) {
return response()->json(['name' => $request->input('name')]);
});
or you could use following (shortened), but code above is "shorter"
$json_data = json_encode(['name' => 'Agent Smith']);
$response = $client->post('http://example.dev/neo', [
'body' => $json_data,
'headers' => [
'Content-Type' => 'application/json',
'Content-Length' => strlen($json_data),
]
]);
note: If you are running PHP5.6, change always_populate_raw_post_data to -1 (or uncomment the line) in php.ini and restart your server. Read more here.
In my case I was using public IP address in BASE_URL while I should have been using the private IP. From mac you can get your IP by going into system preferences -> network.
This is with Android + Laravel (API)

Github api Login - get user

I have a problem with Github api.
I parse the access_token but when i try to get the user I get the following error:
Warning: file_get_contents(https://api.github.com/user?access_token=mplamplampla): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
When I try to get the contents through address bar in my browser is working!
My code:
//Get the access token
$postdata = http_build_query(
array(
'client_id' => 'mplamplaID',
'client_secret' => 'mplamplaSECRET',
'code' => trim($_GET['code']),
'redirect_uri' => 'http://vlingos.com/github.php'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$vip = file_get_contents('https://github.com/login/oauth/access_token',false,$context);
parse_str($vip);
//Get the User
$json = file_get_contents('https://api.github.com/user?access_token='.$access_token);
if(isset($json) and (is_array($json)===true or is_object($json)===true)){
$jsonIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode($json, TRUE)),RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
$git_user[$key] = $val;
}
print_r($git_user);
}else{
echo "can't get user";
}
Can someone propose something?
kindest regards
Enable your token is correct. generate new token, refer to:https://help.github.com/articles/creating-an-access-token-for-command-line-use/
test it:
curl https://api.github.com/user?access_token=your token