Save image (from javascript) in a public folder (through php) - javascript

I am trying to use this package
https://vuejsexamples.com/a-beautiful-vue-component-for-image-cropping-and-uploading/
But then I am wondering how to save my image in a folder.
I am trying to do this in php so that I can use easily the route afterwards, but it could be OK with JS as well if it is easier.
public function uploadfile(Request $request){
$img = $request->img;
$newlocation = $request->newlocation;
$filename = $request->filename;
$img = str_replace('data:image/png;base64,', '', $request->img); //I tried with and without this
return file_put_contents ($newlocation . "/" . $filename , $img );
}
I actually get an image in my public folder but the content is absolutely not what I want :)
The image.jpg contains the text C:\Users\usr\AppData\Local\Temp\phpEE72.tmp

I found this link very helpful when uploading images:
https://hdtuto.com/article/laravel-57-image-upload-with-validation-example
In my controller I have something like this after validation, which allows for different image filetypes like png and jpg:
$name = $request->input('name');
$getimageName = $name.'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('filelocation'), $getimageName);
And in my filesystems.php file:
'disks' = > [
'filelocation' => [
'driver' => 'local',
'root' => public_path().'/foldername',
'url' => env('APP_URL').'/public/foldername',
'visibility' => 'public',
]
]

That's the string of the filename. Behind the scenes PHP handles all files uploaded to the server by putting in a temp directory. It's up to you to move it and process it. All you'd need to do is to read the file's contents first:
file_put_contents ($newlocation . "/" . $filename , file_get_contents($img) )
without your str_replace.
You should consider doing this in a more Laravel way as recommended in https://laravel.com/docs/5.8/filesystem#file-uploads but to answer the immediate question, all you need if file_get_contents.

Related

Access storage directory through JS Laravel

Is there is a way to access the storage directory, which is already linked to the public directory in JS?
I'm trying to make an upload image form.
Validation script:
if ($request->hasFile('photos')) {
$marker->photos = $request->photos->store('uploads');
}
It saves image in /storage/app/uploads/
I can't use this image, because website is in public folder, and can't have access to any other folders, so I did php artisan storage:link to create a sublink to storage folder.
Now, how can I access the image using 1) PHP 2) JS?
Yes, you have to use the public disk to store the file:
if ($request->hasFile('photos')) {
$marker->photos = Storage::disk('public')->putFile('uploads', $request->file('photos'));
}
This syntax, similar to the one you are using, it's also possible to specify 'public' disk:
$marker->photos = $request->file('photos')->store(
'uploads', 'public'
);
Then you'll can access to it by the url.
Laravel:
$url = asset('storage/uploads/filename.png');
$url = asset( Storage::url('uploads/filename.png') );
JS:
let imgSrc = "http://yourdomain/storage/uploads/filename.png";
References:
File Storage File Uploads.
File Storage The Public Disk.
File Storage File URLs.
From PHP, you would use something like this to access your storage/ directory:
if(file_exists('storage/app/uploads/photo.jpg')){
$marker->photo = Storage::disk('local')->get('public/app/uploads/photo.jpg');
// or to get the directory, which you can append ->response('png') to the end...
$marker->photo = public_path('storage/app/uploads/photo.jpg');
}
To serve it from JS, you would do something similar, but have a Controller output the image when receiving an AJAX Request. Easiet method to achieve this without all this, if possible, would be through a blade template:
<img src = "{{asset('/storage/app/uploads/photo.jpg')}}">
which generates a link to the uploaded file by Laravel.

Recursively generate script tags for all JavaScript files within a directory with PHP

I'm building a complex app with lots of JavaScript files in lots of sub-directories. I know I want to include them all (it won't affect performance), but I don't want to manually create a script tag for each. Given that all of my files are children of a "/js" directory, how could I dynamically generate the script tags for each with PHP? Something like this:
// first somehow recursively get all .js files, then:
foreach($files as $file) {
echo '<script src="' . $file->path . '"></script>';
}
Most elegant way is to use SPL in my opinion.
$dirIterator = new RecursiveDirectoryIterator("/path/to/js");
$iterator = new RecursiveIteratorIterator(
$dirIterator,
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
if($file->getExtension() == 'js') {
// You probably have to adjust the full path according to your DOC_ROOT
$url = $file->getPathname();
echo '<script src="' . $url . '"></script>';
}
}
Have a look at http://php.net/manual/en/class.splfileinfo.php to see what else you can do with $file .

write a file on local disk from web app [duplicate]

I am trying to create and save a file to the root directory of my site, but I don't know where its creating the file as I cannot see any. And, I need the file to be overwritten every time, if possible.
Here is my code:
$content = "some text here";
$fp = fopen("myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
How can I set it to save on the root?
It's creating the file in the same directory as your script. Try this instead.
$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT. This means that the path is dynamic, and can be moved between servers without messing about with the code.
<?php
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation,"w");
$content = "Your text here";
fwrite($file,$content);
fclose($file);
?>
This question has been asked years ago but here is a modern approach using PHP5 or newer versions.
$filename = 'myfile.txt'
if(!file_put_contents($filename, 'Some text here')){
// overwriting the file failed (permission problem maybe), debug or log here
}
If the file doesn't exist in that directory it will be created, otherwise it will be overwritten unless FILE_APPEND flag is set.
file_put_contents is a built in function that has been available since PHP5.
Documentation for file_put_contents
fopen() will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.
This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.
Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:
$fp = fopen("myText.txt","wb");
if( $fp == false ){
//do debugging or logging here
}else{
fwrite($fp,$content);
fclose($fp);
}

List files, read files as links, php?

This is a strange request I suppose, but I have a directory full of txt files. For example:
- david_smith_interview.txt -
- beth_martin_interview.txt -
- sally_smithart_interview.txt
The contents of these text files are a link to their interview in an mp3 format, for example, if you open the file david_smith_interview.txt, it is simply this:
http://www.interviews/employees/david_smith.mp3
All of the other text files follow the same format. They are simply links to their mp3 interview.
I am trying to use something like below to list the text files:
<?php
$directory = "/employees/";
$phpfiles = glob($directory . "*.txt");
foreach($phpfiles as $phpfile)
{
echo $phpfile; // This will list the files by name
// How can I output something to reflect this:
// david_smith_interview
}
?>
So I am asking is it possible that the text file can be "read" and used as the actual link?
Any thoughts?
Replace _interview.txt with .mp3
echo "" . str_replace(".txt", "", $phpfile). "\";
Since those are .txt files you can just read them one by one to a variable and then echo the result in a for-loop.
In pseudo:
$paths fetch_paths()
$urls = array();
foreach($paths as $path)
{
$url=fopen($path);
array_push($urls,fgets(url)); // Assuming there's only one link per file and it is on one line.
}
foreach($urls as $url)
{
echo <Your formatted link here>
}

Convert contents of an HTML file to a string

I'd like to know how to input a .html file to a browser, which then takes the contents of said .html file and converts it into one big string so that I can pass it into a JavaScript function to parse it. As I understand it, HTML5 implemented a file API but I'm not entirely sure if it's capable of doing what I want, or how to really use it for all that matter.
You can use the following :
$filename = "yourhtmlfile.html";
$handle = fopen($filename, "r");
// Retrieve the content of HTML file, and stocks it into $contents var
$contents = fread($handle, filesize($filename));
fclose($handle);

Categories

Resources