技術情報
- 2021年04月16日
- 技術情報
Creating downloadable CSV file in PHP
This time I would like to share you how to automatically download CSV file using PHP.
To download CSV file, the header() function and the php://output parameter must be used.
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=myCSV.csv');
header("Content-Transfer-Encoding: UTF-8");
Setting the header is importance when downloading files automatically. In the first line of code, the content-type option is that HTTP header telling the browser that the MIME type of the content is application/csv.
Other particularly important option is in the second line of code, the filename option. This is where we want to name the file that will be generated and downloaded.
The other importance line of code is content transfer encoding ,this encoding method will transform binary email message data into the US-ASCII plain text format.
For populating CSV, fopen() giving us access to PHP’s output buffer. This line of code is that the file pointer connected to the output stream.
$f = fopen('php://output', 'a');
Writing data to the Csv and we can define column headings like this:
fputcsv($f, array('Column 1', 'Column 2', 'Column 3'));
We can fetch data and loop over the rows of data and output them.
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');
while ($row = mysql_fetch_assoc($rows)) fputcsv($f, $row);
By Ami
asahi at 2021年04月16日 10:00:06
- 2021年04月09日
- 技術情報
Prohibited Validation Rules in Laravel
Sometimes we wish to forcefully prevent some of the fields in the request.
Now we just got that. Laravel 8 has three validation added for prohibited fields. Let’s walk through a few examples of where the prohibited validation rules might be useful and look at each one in more detail.
Prohibited Validation Rule
The “prohibited” rule checks if the field under validation must be empty or not present or throw an error otherwise.
// PUT /api/licenses/123-456
// {"name":"hello-world", "key":"random-key"}
$validated = $request->validate([
'name' => 'required|max:255',
'key' => 'prohibited',
]);
// Response: 422
// The key field is prohibited
The above is where a user might expect to update an API key by sending a PUT request to a resource. That field is likely ignored during the request. However, a successful response might lead to the user to believe they were able to update the key when in reality, the API ignored it.
If prohibited validation rule registers, the key field is present in the request it will terminate the request with 422 HTTP code response code and throw the error with the message The key field is prohibited.
Prohibited If and Unless Rules
The “prohibited_if ” rule checks if the field under validation must be empty or not present if the another field is equal to any value.
Validator::validate([
‘is_minor’ => true,
‘tos_accepted’ => true
], [
‘tos_accepted’ => ‘prohibited_if:is_minor, true’
]);
The above example is we’re expecting tos_accepted field will be forbidden if is_minor filed accepts true value. This example means someone accepting terms of service that has identified as a minor. Perhaps the application requires a parental registration to consent on their behalf.
The basic idea of “Prohibited_unless” rule is that a given filed should be prohibited from having data unless another field is equal to any value.
Validator::validate([
‘is_deceased’ => false,
‘date_of_death’ => ‘2021-03-09’
], [
‘date_of_death’ => ‘prohibited_unless:is_deceased,true’
]);
The above example might be initially the is_deceased filed set to false value.If we’re expecting the date_of_death field not to be forbidden, the is_deceased’ field set to true value.The example illustrates perfectly how to use this rule to explicitly prevent contradictory input.
By Ami
asahi at 2021年04月09日 10:00:12
- 2021年04月05日
- 技術情報
Compressing images for your website
Sometimes, we have to deal with large size images in our website that cause the loading time longer. We need to manage that issue by compressing the images to a smaller without affecting largely the image resolution on the other hand.
Furthermore, we can use lazy loading to load our images on the website apart from compressing images. Firstly I will guide to some websites which provide multiple images’ compression and talk about lazy loading.
Jpeg Compression
As for the jpg and jpeg images compression, you can go to this website which allows only jpg formats images for compression that is available up to 20 images per time. After compression work, there will be a zip file of your compressed images.
Jpg & Png Compression
You have png files instead of jpg, you can use this website which allows not only jpg but also png for compression. The limitation is 20 like above one and there is one more limitation of image size 5MB. After compression work, there will also be a zip file of your compressed images.
Lazy Loading
Image lazy loading means loading images to websites asynchronously, that is, after the content in the top half of the page is fully loaded, or even conditionally, only when they appear in the browser’s viewport. This means that if users don’t scroll all the way down, the images at the bottom of the page won’t even load.
There are many types of lazy loading but I will talk about native browser lazy loading but you can also use other third parties JavaScript libraries.
<img loading = lazy> is compatible with the most popular Chromium-powered browsers (Chrome, Edge, Opera) and Firefox. WebKit (Safari) implementation is in progress. caniuse.com has detailed information on cross-browser compatibility. Browsers that don’t support the loading attribute just ignore it with no side effects.
As I said above, you are welcome to use other libraries like Lozad.js or Intersection_Observer_API also.
Yuuma
yuuma at 2021年04月05日 11:00:53
- 2021年04月02日
- 技術情報
Laravel Session
Sessions provide a way to store information about the user across multiple requests. Session configuration file is stored at config/session.php. Laravel provide various drivers like file, cookie, database, mechace / redis, dynamodb, array. By default, Laravel is configured to use file session driver.
Interaction with the Session
Retrieving Data
There are two primary ways to access the session data in laravel: the global session helper and via a Request instance.
To access the session data via HTTP Request, we can use the get() method, which will take one argument, key to get the session data.
$request->session()->get('key');
When we retrieve an item from the session, we may also pass a default value as the second argument to the get method.
$request->session()->get('key', 'default');
To retrieve all the data in the session, we may use the all method:
$data = $request->session()->all();
To determine if an item is present in the session, we may use the has method:
if ($request->session()->has('users')) {
//
}
Pushing To Array Session Value
The push method may use to push a new value onto a session value that is an array.
$request->session()->push('user.teams', 'developers');
Retrieving & Deleting An Item
The pull method may used to retrieve and delete an item form the session in a single statement:
$value = $request->session()->pull('key', 'default');
If session data contains an integer we may wish to increment or decrement, we may use the increment and decrement methods.
$request->session()->increment('count');
$request->session()->decrement('count');
We may wish to store in the session for the next request. We may use the flash method.
$request->session()->flash('status', 'Task was successful!');
To remove a piece of data from the session. We may use forget method.
$request->session()->forget('name');
We may wish to remove multiple keys:
$request->session()->forget(['name', 'status']);
The Global Session Helper
You may also use the global session PHP function to retrieve and store data in the session.
Route::get('/home', function () {
// Retrieve a piece of data from the session...
$value = session('key');
// Specifying a default value...
$value = session('key', 'default');
// Store a piece of data in the session...
session(['key' => 'value']);
});
By Ami
asahi at 2021年04月02日 10:00:56
- 2021年03月29日
- 技術情報
Local Storage Issues
We use LocalStorage often in our web application to store data. But there are still some issues relating with local storage and you should consider a few facts before using this.
LocalStorage is a web storage object for storing data on the client, or local, or user’s computer. Locally stored data has no expiration date and remains until it is deleted. Local storage has caught the attention of developers as a lightweight solution for storing data that does not include databases or even a server.
But there are some down sides also to consider.
XSS vulnerabilities
Local storage has many similarities with cookies, including the same security risks. One of them makes it easy to do site scripting, which by stealing cookies allows a user to create a login session for a site. Storing something sensitive, such as a password, in a local storage file makes the process really easier for a hacker; Because they do not need to put cookies in their own browser.
Less Control
With local storage, there is no server-side storage or database that the developer can control. This can be a problem for several reasons. One is that once the code or information is saved, there is no way for the developer to update the code or information. The user has to delete the file manually and has to find the file. Alternatively, you need to clear your browser’s cache to lose all the stored data.
User might clear the storage
Clearing your browser’s cache on a regular basis will help browsers work more effectively. This is usually the first step you should take when troubleshooting browser issues such as pages not loading properly. This is a problem when using local storage to support the functionality of your site. When the user clears the browser cache, that information is completely lost.
As an alternative to local storage, there are several ways to handle this. For example – server side sessions, DB, and third party storage services etc.
Yuuma
yuuma at 2021年03月29日 11:02:42