What can we do aws monitoring tool “cloud watch”?

What can we do for CloudWatch??

-> CloudWatch is “A fully managed operation monitoring service” provided by AWS, those that monitor various resources of AWS.

In detail and features.
– Can be used without setup
– It detects an abnormal condition and automatically restores it
– Alert notification and action can be set according to metrics.

It can be monitored EC2, EBS, S3, and so on. Cloudwatch have three services.
– CloudWatch : You can make dashboards by graphing multiple items such as CPU and memory.
– CloudWatch Logs:Corresponds to Amazon Linux, RedHat, Windows etc, and by acquiring various logs by putting an agent in the instance. In addtion to OS, application logs are also supported, and you can let alert notice by keyword.
– CloudWatch Events:It is a service that causes some action to be executed by triggering API event.

Other way to watch log is checking access_log, error_log, and monitor_log from Linux.

Laravel5.7 upload file with extension

uploaded a file with a controller, but looked no file extension.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Image;

class ImageIndexController extends Controller
{
    public function index(){
    	return view('imageindex');
    }

    public function store(Request $request){

    	$request->file('image')->move(public_path('item'));
    	return view('imageindex');
    }
}

How come to fix it?

specify the extension with guessExtension method.
ImageIndexController.php

public function store(Request $request){

        $filename = $request->file('image') . "." . $request->file('image')->guessExtension();
    	$request->file('image')->move(public_path('item'), $filename);
    	return view('imageindex');
    }

/image/index

I got it.

I want to display the uploaded image in view.
Before that, you want to make the file name arbitrary, such as date. It seems to be so easy.

$filename = date("YmdHis") . "." . $request->file('image')->guessExtension();

oh, OK.

Laravel5.7 mime type

Use mime type to specify the extension of the image in laravel.

A full listing of MIME types and their corresponding extensions may be found at the following location:
https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

I wonder if this match??

custom request
ImageRequest.php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ImageRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'image' => 'image|mimes:jpg,jpeg,gif,png',
        ];
    }
    public function messages()
    {
        return [
            'image.required' => '画像以外のファイルが指定されています。画像ファイル(png/jpg/jpeg/gif)を指定して下さい',
        ];
    }
}

Upload image with Laravel5.7

Upload images with Laravel5.7.
Configure routing to save images posted from view.

Route::get('/image/index', 'ImageIndexController@index');
Route::post('/image/index', 'ImageIndexController@store');

imageindex.blade.php

@extends('layouts.image')
@section('title', '画像管理')

@section('breadcrumb')
	@@parent
	<ul class="breadcrumb">
      <li itemscope="itemscope" itemtype="http://data-vocabulary.org/Breadcrumb" >
        <a href="/top" itemprop="url">
          <span itemprop="title">ホーム</span>
        </a>
      </li>
      <li itemscope="itemscope" itemtype="http://data-vocabulary.org/Breadcrumb" >
        <a href="/top" itemprop="url">
          <span itemprop="title">画像管理</span>
        </a>
      </li>
    </ul>
@endsection

@section('content')
<h2>画像管理</h2>
      <hr>
      <form action="/image/index" method="POST" enctype="multipart/form-data">
        <div id="drag-drop-area">
         <div class="drag-drop-inside">
          <p class="drag-drop-info">ここにファイルをアップロード</p>
          <p>または</p>
          <!-- <input type="file" value="ファイルを選択" name="image"> -->
          <p class="drag-drop-buttons"><input id="fileInput" type="file" value="ファイルを選択" name="image"></p>
              <!-- <input type="submit" value="送信"> -->
           </div>
          </div>
            

      <div class="button_wrapper remodal-bg">
         <button type="submit" value="送信" id="square_btn" onClick="location.href='#modal'">登録</button>
      </div>
       </form> 

      <!-- remodal -->
      <div class="remodal" data-remodal-id="modal">
        <button data-remodal-action="close" class="remodal-close"></button>
        <h1>保存しますか</h1>
        <p>
          入力した内容で宜しいでしょうか?
        </p>
        <br>
        <button data-remodal-action="cancel" class="remodal-cancel">Cancel</button>
        <button data-remodal-action="confirm" class="remodal-confirm">OK</button>
      </div>
      <!-- /remodal -->

      <script>
      var fileArea = document.getElementById('drag-drop-area');
      var fileInput = document.getElementById('fileInput');

      fileArea.addEventListener('dragover', function(evt){
        evt.preventDefault();
        fileArea.classList.add('dragover');
      });

      fileArea.addEventListener('dragleave', function(evt){
        evt.preventDefault();
        fileArea.classList.remove('dragover');
      });

      fileArea.addEventListener('drop', function(evt){
        evt.preventDefault();
        fileArea.classList.remove('dragenter');
        var files = evt.dataTransfer.files;
        fileInput.files = files;
      });

      </script>
      
@endsection

Upload an image from a form with php

Move the uploaded image with move_uploaded_file to the specified fold.
Then let the image be displayed again in the view.

if(file_exists($_FILES['upfile']['tmp_name'])){
	$ext = substr($_FILES['upfile']['name'], strrpos($_FILES['upfile']['name'],'.') + 1);
	echo $ext."<br>";
	if(strtolower($ext) !== 'png' && strtolower($ext) !== 'jpg' && strtolower($ext) !== 'jpeg' && strtolower($ext) !== 'gif'){
		echo '画像以外のファイルが指定されています。画像ファイル(png/jpg/jpeg/gif)を指定して下さい';
		exit();
	}
	$image = "img/".basename($_FILES['upfile']['tmp_name']).".".$ext;
	if(move_uploaded_file($_FILES['upfile']['tmp_name'], $image)){
		echo "アップロード成功!!";
	} else {
		echo "失敗";
	}
	// insert $image into mysql
}


?>
<div id="content">
<h2>画像管理</h2>
<hr>
<form action="#" method="POST" enctype="multipart/form-data">
<div id="drag-drop-area">
 <div class="drag-drop-inside">
  <p class="drag-drop-info">ここにファイルをアップロード</p>
  <p>または</p>
  <!-- <input type="file" value="ファイルを選択" name="image"> -->
  <p class="drag-drop-buttons"><input id="fileInput" type="file" value="ファイルを選択" name="upfile"></p>
      <input type="submit" value="送信">
   </div>
  </div>
  <img src="<?php echo $image; ?>">
</form>

Before

After

Will implement this in laravel.
Or, in the case of laravel, is there a form to upload images?

Upload the image from the php form to s3

It is necessary to make access right to s3 bucket beforehand with IAM.
Use php library to upload to s3. Here is code.

require 'vendor/autoload.php';

if(file_exists($_FILES['upfile']['tmp_name'])){
	$ext = substr($_FILES['upfile']['name'], strrpos($_FILES['upfile']['name'],'.') + 1);
	echo $ext."<br>";
	if(strtolower($ext) !== 'png' && strtolower($ext) !== 'jpg' && strtolower($ext) !== 'jpeg' && strtolower($ext) !== 'gif'){
		echo '画像以外のファイルが指定されています。画像ファイル(png/jpg/jpeg/gif)を指定して下さい';
		exit();
	}

	$tmpname = str_replace('/tmp/', '', $_FILES['upfile']['tmp_name']);
	echo $tmpname;
	$s3client = new Aws\S3\S3Client([
			'credentials' => [
					'key' => '',
					'secret' => ''
			],
			'region' => 'ap-northeast-1',
			'version' => 'latest',
	]);

	$result = $s3client->putObject([
			'Bucket' => 'zeus-image',
			'Key' => 'test.png',
			'SourceFile' => $_FILES['upfile']['tmp_name'],
			'Content-Type' => mime_content_type($_FILES['upfile']['tmp_name']),
	]);

}


?>
<div id="content">
<h2>画像管理</h2>
<hr>
<form action="#" method="POST" enctype="multipart/form-data">
<div id="drag-drop-area">
 <div class="drag-drop-inside">
  <p class="drag-drop-info">ここにファイルをアップロード</p>
  <p>または</p>
  <!-- <input type="file" value="ファイルを選択" name="image"> -->
  <p class="drag-drop-buttons"><input id="fileInput" type="file" value="ファイルを選択" name="upfile"></p>
      <input type="submit" value="送信">
   </div>
  </div>
</form>

HTML form view

s3

You can confirm that it is being uploaded properly.

Create a read-only user with aws ec2

Create a read-only user on IAM.

Select IAM on the service list page

Select users from the left menu of the IAM dashboard

Click add user button

set username and programmatic access for access type

At this point the user has no permissions.

On the user detail page you just created, open the security crudential tab

Click Access keys to create a new access key and secret key.

Well, finally it’s coming to set permissions. Select add permissions button from the permission tab.

From add user to group, press create group.

In management console Create policy, chose service for EC2 and Access level should be Read.

Put name for read-only-ec2 and create policy.

finally attache user to just created read-only-ec2 policy.

Then, user permission has changed to access EC2.
I explained how to make ReadOnly IAM users using IAM. There are many things IAM can do, such as creating groups, writing policies in detail, and creating Role. I think that AWS is the only cloud that can control privilege so far. Want to make good and secure system.

fixing a word of fgets regular expression

There is a trouble that it is not goes well at reading one line regular expression.
I would like to code if only one dot contained in a line, issue an alert.

$file = fopen("test.txt", "r");

if($file){
	while($line = fgets($file)){

		if(preg_match('/^.$/', $line)){
			echo "please write again.<br>";
		} else {
			echo "OK<br>";
		}

	}
}
fclose($file);

Regular expression does not work well in this code.

add half-width dot in the regular expression

if($file){
	while($line = fgets($file)){

		if(preg_match('/^..$/', $line)){
			echo "please write again.<br>";
		} else {
			echo "OK<br>";
		}

	}
}

A half-size dot in a regular expression means an arbitrary one character.

Starting and ending regular expression

I want to issue an alert when only a dot in a line.
It needs check for starting and ending regular expression.

Is it a character string starting with 〇〇?

preg_match("/^xx/", $char);

Is it a character string ending with 〇〇?

preg_match("/xx$/", $char);

Here is the main theme. When judging whether it is a character string of only dots, combine the above.

$char = '.';

if(preg_match('/^.$/', $char)){
	echo "please write again.";
} else {
	echo "OK";
}

-> please write again.

Yes, it is as expected.
I would like to apply next. Read the file and if there is a line with only dots, it will issue an error.

this is a popular Hamlet.
test.txt

To be, or not to be: that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles,
And by opposing end them? To die: to sleep;
No more; and by a sleep to say we end
The heart-ache and the thousand natural shocks
That flesh is heir to, 'tis a consummation
Devoutly to be wish'd. To die, to sleep;

app.php

$file = fopen("text.txt", "r");

if($file){
	while($line = fgets($file)){

		if(preg_match('/^.$/', $char)){
			echo "please write again.<br>";
		} else {
			echo "OK<br>";
		}

	}
}


It is looks like it is going well😂