How to export logs to view? - laravel-4

I am building out an admin page for a Laravel 4.1 application and would like a way to easily access the log file(s).
I tried this:
Route::get('logs', function() {
$logfile = storage_path() . '/logs/laravel.log';
$logs = file_get_contents($logfile);
return Response::json(array('logs' => $logs));
});
But it throws the following error:
{"error":{"type":"UnexpectedValueException","message":"The Response content must be a string or object implementing __toString(), \"boolean\" given.","file":"\/var\/www\/html\/myApp\/vendor\/symfony\/http-foundation\/Symfony\/Component\/HttpFoundation\/Response.php","line":421}}

Related

Cannot send file from Postman to Laravel API

I am trying to send an image to my laravel APIs from postman.
I added the file(280KB) on the request body like so:
On the server side I am trying to catch the file and save it, but it returns that there is no file.
public function uploadImage(Request $request)
{
//returns false
$request->hasFile('profile_image');
//returns profile_image is required
$request->validate(['profile_image' => 'required|image:jpeg,png,jpg,gif,svg']);
//returns null
$request->file('profile_image');
}
I am calling the function from api.php like so:
Route::put('/creators/{id}/upload_image',[CreatorController::class,'uploadImage']);
I thought maybe I shouldn't put the file in Body, but couldn't find an alternative.
Also I am finally trying to send the file from a vue client, but I had the same Issue when trying to send the file from there.
How do I get the server to catch the file?
Edit: adjusted typo in example code
new code sample
I changed the method from put to post, since I wanted to test the post method as well. I also tried _method put in postman beforehand.
Here is the code sample on Laravel:
//api.php
Route::put('/creators/{id}/upload_image',[CreatorController::class,'uploadImage']);
//CreatorController.php
public function uploadImage(Request $request)
{
if($request->hasFile('profile_image')){
$allowedfileExtension=['gif','jpg','png'];
$file = $request->file('profile_image');
$extension = $file->getClientOriginalExtension();
if(in_array($extension,$allowedfileExtension)) {
$path = $file->store('public/images/profile');
$path_url = $path;
return ["image_url" => $path_url, "image" => $request->file('profile_image')];
}
return false;
}
}
The $request->hasFile('profile_image') returns true, but then $request->file('profile_image') returns null, failing to save the image.
My vue client side code (if it might turn useful):
if(this.profile_image != null){
let data = new FormData();
data.append('profile_image', this.profile_image)
axios
.post('http://localhost:8000/api/creators/'+uid+'/upload_image', data, head)
.then(
response => (
//successfully receives the image_url
this.creatorData.image_url = response.data.image_url,
console.log(response.data)
),
)
.catch(
error => (
localStorage.setItem('error', error),
console.log(error.response)
),
this.loading = false,
)
}
The client side actually receives the "image_url" but the image is not saved on laravel.
laravel dose not support put method directly.
you must use post method then pass _method to your laravel project
like this picture

laravel api with vue 2 js not returning data - could 'localhost:8000' (or '127.0.0.1:8000') be the issue?

I am using the repo https://github.com/mschwarzmueller/laravel-ng2-vue/tree/03-vue-frontend so I have 100% confidence in the reliability of the code. I can post through the laravel api endpoint through the very simple Vue client, and also through Postman. Through Postman I can retrieve the table data array, but not so in the client app. In POSTMAN:
localhost:8000/api/quotes
works just fine.
IN THE vue 2 js CLIENT APP:
methods: {
onGetQuotes() {
axios.get('http://localhost:8000/api/quotes')
.then(
response => {
this.quotes = (response.data.quotes);
}
)
.catch(
error => console.log(error)
);
}
returns nothing. returning the response to Console.log returns nothing. The Network/XHR tab shows the table data rows, but I am not sure what that means.
I know for sure that this code works for others with their unique api endpoints, which I assume may not use localhost or '127:0.0.1:1080.
Edit: in response to request for more info
public function getQuotes()
{
$quotes = Quote::all();
$response = [$quotes];
return response()->json($response, 200);
}
and the relevant route:
Route::get('/quotes', [
'uses' => 'QuoteController#getQuotes'
]);
Just to confirm: I am using verified github repo code in which the ONLY change is my api endpoint addressas mentioned in the first line of the body of this question. . Note that the Laravel back end is also derived from a related repo in Max's fine tutorial. The running code can be seen at
So I really don't think this is a coding error- but is it a configuration error due to me using local host??
EDIT: It WAS a coding error in the laravel controller as shown below
The reason your code isn't working if because you haven't provided a key for your $quotes in your controller but you're looking for it in your vue file (response.data.quotes).
[$quotes] is essentially [0 => $quotes] so when the json response comes through it be 0: [...] not quotes: [...].
To get this to work you just need to change:
$response = [$quotes];
to:
$response = ['quotes' => $quotes];
Furthermore, just an FYI, you don't need to provide the 200 in response->json() as it's the default and you can just return an array and Laravel automatically return the correct json response e.g.:
public function getQuotes()
{
$quotes = \App\Models\Artist::all();
return compact('quotes'); //<-- This is just another way of writting ['quotes' => $quotes]
}
Obviously, you don't have to if you don't want to.
Hope this helps!

How to protect image from public view in Laravel 5?

I have installed Laravel 5.0 and have made Authentication. Everything is working just fine.
My web site is only open for Authenticated members. The content inside is protected to Authenticated members only, but the images inside the site is not protected for public view.
Any one writes the image URL directly can see the image, even if the person is not logged in to the system.
http://www.somedomainname.net/images/users/userImage.jpg
My Question: is it possible to protect images (the above URL example) from public view, in other Word if a URL of the image send to any person, the individual must be member and login to be able to see the image.
Is that possible and how?
It is possible to protect images from public view in Laravel 5.x folder.
Create images folder under storage folder (I have chosen storage folder because it has write permission already that I can use when I upload images to it) in Laravel like storage/app/images.
Move the images you want to protect from public folder to the new created images folder. You could also chose other location to create images folder but not inside the public folder, but with in Laravel folder structure but still a logical location example not inside controller folder. Next you need to create a route and image controller.
Create Route
Route::get('images/users/{user_id}/{slug}', [
'as' => 'images.show',
'uses' => 'ImagesController#show',
'middleware' => 'auth',
]);
The route will forward all image request access to Authentication page if person is not logged in.
Create ImagesController
class ImagesController extends Controller {
public function show($user_id, $slug)
{
$storagePath = storage_path('app/images/users/' . $user_id . '/' . $slug);
return Image::make($storagePath)->response();
}
}
EDIT (NOTE)
For those who use Laravel 5.2 and newer. Laravel introduces new and better way to serve files that has less overhead (This way does not regenerate the file as mentioned in the answer):
File Responses
The file method can be used to display a file, such as an image or
PDF, directly in the user's browser instead of initiating a download.
This method accepts the path to the file as its first argument and an
array of headers as its second argument:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
You can modify your storage path and file/folder structure as you wish to fit your requirement, this is just to demonstrate how I did it and how it works.
You can also added condition to show the images only for specific members in the controller.
It is also possible to hash the file name with file name, time stamp and other variables in addition.
Addition: some asked if this method can be used as alternative to public folder upload, YES it is possible but it is not recommended practice as explained in this answer. So the same method can be also used to upload images in storage path even if you do not intend to protect them, just follow the same process but remove 'middleware' => 'auth',. That way you won't give 777 permission in your public folder and still have a safe uploading environment. The same mentioned answer also explain how to use this method with out authentication in case some one would use it or giving alternative solution as well.
In a previous project I protected the uploads by doing the following:
Created Storage Disk:
config/filesystems.php
'myDisk' => [
'driver' => 'local',
'root' => storage_path('app/uploads'),
'url' => env('APP_URL') . '/storage',
'visibility' => 'private',
],
This will upload the files to \storage\app\uploads\ which is not available to public viewing.
To save files on your controller:
Storage::disk('myDisk')->put('/ANY FOLDER NAME/' . $file, $data);
In order for users to view the files and to protect the uploads from unauthorized access. First check if the file exist on the disk:
public function returnFile($file)
{
//This method will look for the file and get it from drive
$path = storage_path('app/uploads/ANY FOLDER NAME/' . $file);
try {
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
} catch (FileNotFoundException $exception) {
abort(404);
}
}
Serve the file if the user have the right access:
public function licenceFileShow($file)
{
/**
*Make sure the #param $file has a dot
* Then check if the user has Admin Role. If true serve else
*/
if (strpos($file, '.') !== false) {
if (Auth::user()->hasAnyRole(['Admin'])) {
/** Serve the file for the Admin*/
return $this->returnFile($file);
} else {
/**Logic to check if the request is from file owner**/
return $this->returnFile($file);
}
} else {
//Invalid file name given
return redirect()->route('home');
}
}
Finally on Web.php routes:
Route::get('uploads/user-files/{filename}', 'MiscController#licenceFileShow');
I haven't actually tried this but I found Nginx auth_request module that allows you to check the authentication from Laravel, but still send the file using Nginx.
It sends an internal request to given url and checks the http code for success (2xx) or failure (4xx) and on success, lets the user download the file.
Edit: Another option is something I've tried and it seemed to work fine. You can use X-Accel-Redirect -header to serve the file from Nginx. The request goes through PHP, but instead of sending the whole file through, it just sends the file location to Nginx which then serves it to the client.
if I am understanding you it's like !
Route::post('/download/{id}', function(Request $request , $id){
{
if(\Auth::user()->id == $id) {
return \Storage::download($request->f);
}
else {
\Session::flash('error' , 'Access deny');
return back();
}
}
})->name('download')->middleware('auth:owner,admin,web');
Every file inside the public folder is accessible in the browser. Anyone easily gets that file if they find out the file name and storage path.
So better option is to store the file outside the public folder eg: /storage/app/private
Now do following steps:
create a route (eg: private/{file_name})
Route::get('/private/{file_name}', [App\Http\Controllers\FileController::class, 'view'])->middleware(['auth'])->name('view.file');
create a function in a controller that returns a file path. to create a controller run the command php artisan make:controller FileController
and paste the view function in FileController
public function view($file)
{
$filePath = "notes/{$file}";
if(Storage::exists($filePath)){
return Storage::response($filePath);
}
abort(404);
}
then, paste use Illuminate\Support\Facades\Storage; in FileController for Storage
And don't forget to assign middleware (in route or controller) as your requirement(eg: auth)
And now, only those who have access to that middleware can access that file through a route name called view.file

response::download is doing nothing

I am having problems getting files to download outside of the public folder. Here is the Scenario:
These files cannot be accessed from anywhere but through this application and these downloads must go through access control. So a user can't download the file if they are not logged in and have permission to.
I have a route defined with a get variable. This ID goes into the controller and the controller calls the method below:
public static function downloadFile($id){
$file = FileManager::find($id);
//PDF file is stored under app/storage/files/
$download= app_path().substr($file->location,6);///home/coursesupport/public_html/app/storage/files/fom01/7-2/activities-and-demos.pdf
$fileName = substr($download,strrpos($download,'/')+1);//activities-and-demos.pdf
$mime = mime_content_type($download);//application/pdf
$headers = array(
'Content-Type: '.$mime,
"Content-Description" => "File Transfer",
"Content-Disposition" => "attachment; filename=" . $fileName
);
return Response::download($download, $fileName, $headers);
}
the problem is it does nothing, just opens a blank page. Am I missing something? oh yeah, and the link to the route mentioned above opens a blank tab.
I appreciate any help. Thanks!
It should work by doing only this:
public static function downloadFile($id)
{
$file = FileManager::find($id);
$download= app_path().substr($file->location,6);
$fileName = substr($download,strrpos($download,'/')+1);
return Response::download($download, $fileName);
}
Make sure your route is actually returning the returned response. Eg:
Route::get('download', function()
{
return DownloadHandler::downloadFile(1);
});
Without the return in the route the IlluminateResponse will do nothing.

How to get Facebook user detail from Access Token using Codeigniter?

I'm really struggling to understand what's happening here. I can get a Users details fine in the OpenGraph tester or just hitting the URL https://graph.facebook.com/me?access_token=VALID_TOKEN or using file_get_contents, but when trying the Codeigniter Facebook Library I get error "An active access token must be used..." and if I just try a CURL GET I get no output. I know the access_token is valid so why aren't they working? The overall objective is to get an access_token from iOS App and use this to do a Like via the web server using og.likes.
My test function:
function me_test(){
$access_token = "VALID_TOKEN";
$url = 'https://graph.facebook.com/me?access_token=';
$url_full = $url.$access_token;
$result = file_get_contents($url_full);
echo $result;
// Try Codeigniter Facebook Library
try {
$user = $this->facebook->api('/me?access_token='.$access_token);
} catch (Exception $e) {
print_r($e);
}
// Codeigniter CURL Library
$this->load->library('curl');
echo $this->curl->simple_get($url_full);
$info = $this->curl->info;
print_r($info);
}
I have also faced this issue and find the alternate way to get userdata. You can try this
function me_test(){
$userId = $this->facebook->getUser(); //This will return the current user id
// Try Codeigniter Facebook Library
try {
$user = $this->facebook->api('/'.$userId);
//When you pass the userid you dont need to provide access token
} catch (Exception $e) {
print_r($e);
}
}

Resources