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😂

Count the number of characters, bytes, width in PHP

How to count the number of characters, number of bytes, character width (apparent length) of a character string in PHP?

1. strlen
function strlen
Generally, to know the number of bytes, use strlen.

mb_internal_encoding('UTF-8');
$char = '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 wishd. ';
echo strlen($char);

168

2. mb_strlen
function mb_strlen
Also, use mb_strlen to distinguish between full-width and half-width characters and count the number of characters.

mb_internal_encoding('UTF-8');
$char = '名前(カタカナ)';

echo mb_strlen($char);

3. mb_strwidth
function mb_strwidth
Use mb_strwidth to count character width(apparent length).

mb_internal_encoding('UTF-8');
$char = 'おはようございます。';

echo mb_strwidth($char);

Let’s put emoji and count it.

mb_internal_encoding('UTF-8');
$char = 'こんにちは😀';

echo strlen($char);

-> 19
it is as expected.

Then, let’s display an alert if it is more than 10 bytes.

mb_internal_encoding('UTF-8');
$char = 'こんにちは😀';

// echo strlen($char);
if(strlen($char) > 10){
	echo "this is more than 10 byte, please write again";
} else {
	echo "confirmed.";
}

-> this is more than 10 byte, please write again

Perfect job, am I.

4 byte character checking for PHP

Some of the pictograms and Chinese characters are 4bytes of UTF-8 characters, and cannot be saved depending on the version of mysql and character code. I think there is something I want to check that there are more characters than the UTF-8 range in the string.

let’s look at sample, cherry blossom is 4 byte characters.

mb_internal_encoding('UTF-8');
$char = 'abcdefgあいうえお🌸';

echo preg_replace('/[\xF0-\xF7][\x80-\xBF][\x80-\xBF][\x80-\xBF]/', '', $char);

abcdefgあいうえお
Wow, it’s impressive.

Ok then, I want to display an alert if 4-byte characters are included.
Let’s see regular expression below.

mb_internal_encoding('UTF-8');
$char = 'abcdefgあいうえお';
// $char = 'abcdefgあいうえお🌸';

// echo preg_replace('/[\xF0-\xF7][\x80-\xBF][\x80-\xBF][\x80-\xBF]/', '', $char);

if(preg_match('/[\xF0-\xF7][\x80-\xBF][\x80-\xBF][\x80-\xBF]/', $char)){
	echo "alert, it included 4 byte";
} else {
	echo "there is no 4 byte charcter";
}

Oh my goodness.
“just trust yourself. surely, the way to live is coming. Goethe”

String Byte conversion for PHP

Let’s look up hex2bin function in php manual.
hex2bin

It says “Decodes hexadecimally encoded binary string”.

Example 1

mb_internal_encoding('UTF-8');
$char = 'あ';

echo bin2hex($char);

result: e38182

This is the unicode standard manual
Unicode.org
UTF8 has 1byte to 4 byte characters.

What happen about in the case of Emoji?
🌸 Cherry blossom: 1F338

mb_internal_encoding('UTF-8');
$char = '🌸';

echo bin2hex($char);

f09f8cb8
A number different from unicode was displayed.
Comversion seems to be done without problems.

Character Code as mainly used in Japan

Character Code
It refers to the correspondence between the characters used on the computer and the numbers in bytes assigned to each letter. Character codes have some to be used in many language spheres by computers, and the variety has increased. Typical character codes are said to be more than 100 kinds.

Mainly used in Japan
JIS Code
The official name is “ISO-2022-JP”. It is widely used.

SJIS(Shift-JIS) Code
It is ASCII code plus Japanese, and it is used in Japan domestic mobile phones.

EUC
It is widely used on UNIX.


Unicode consists of “encoded character set” and “character encoding method(encoding)”.

“Character set” refers to letters put together by certain rules such as “All Hiragana” and “All Alphabet”, for example. A rule in which a unique code is associated with the character set is called a “coded character set”. The associated numerical value is called a code point and it is displayed in the form of “U + xxxxx”.

“Character encoding method” is a method of converting a coded character set into another byte sequence so that it can be handled by a computer. The encoding methods include UTF-8 and UTF-16.

Unicode code point
0x0000 – 0x007f : ASCII
0x0080 – 0x07ff : Country alphabet
0x0800 – 0xffff : Indian characters, punctuation marks, academic symbols, pictograms, East Asian characters, double-byte, half-size

OK!