Get file size

Confirm how to get a filesize from php official document.
filesize

$filename = "test.swf";
echo $filename . ": " . filesize($filename) . ' bytes';

want to make the notation of numbers comma separated by 3 digits.

$filename = "test.swf";
echo $filename . ": " . number_format(filesize($filename)) . ' bytes';

戻り値

A function can pass a value using an argument when it is called, but as a result of processing in the function, it can return a value from the function to the caller this time.
For example, functions that perform numerical calculations can return the calculation results to the caller, and functions that process strings can return the processed results.

Use the return statement to return a value from a function.

function mul($num1, $num2){
	$sum = $num1 * $num2;
	return $sum;
}

$sum = mul(10, 9);
print "乗算の結果は". $sum . "です。<br>";

print "乗算2の結果は". mul(7, 14)."です。";

乗算の結果は90です。
乗算2の結果は98です。

なるほど、returnで返しているのが戻り値と言えそうですね。

関数の引数とは?

function outputName($name){
	echo "私の名前は".$name. "です。<br>";
}
outputName("坂本");
outputName("五十嵐");
outputName("熊田");

私の名前は坂本です。
私の名前は五十嵐です。
私の名前は熊田です。

関数で引数を取る。
引数は複数も可。

function outputName($last_name, $first_name, $area){
	echo "私の名前は".$last_name.$first_name. $area ."出身です。<br>";
}
outputName("坂本","幸子","沖縄");
outputName("五十嵐","義男","山口");
outputName("熊田","ひろむ","長野");

私の名前は坂本幸子沖縄出身です。
私の名前は五十嵐義男山口出身です。
私の名前は熊田ひろむ長野出身です。

SplFileObject

$file = new SplFileObject(__DIR__ . '/a.txt', 'r');
$file->setFlags(SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);

foreach($file as $n => $line){
	if($line === false) continue;
	echo "$n $line", PHP_EOL;
}

csvファイルを作ります。
コード 名称
4592 サンバイオ
4596 窪田製薬ホールディングス
4588 オンコリスバイオファーマ
4563 アンジェス
4579 ラクオリア創薬

$csv = new SplFileObject(__DIR__ . '/a.csv', 'r');
$csv->setFlags(SplFileObject::READ_CSV);

$header = [];
foreach ($csv as $row){
	if ($row === [null]) continue;
	if(empty($header)){
		$header = $row;
		continue;
	}
	$data[] = array_combine($header, $row);
}
var_dump($data);

array(5) { [0]=> array(2) { [“コード”]=> string(4) “4592” [“名称”]=> string(15) “サンバイオ” } [1]=> array(2) { [“コード”]=> string(4) “4596” [“名称”]=> string(36) “窪田製薬ホールディングス” } [2]=> array(2) { [“コード”]=> string(4) “4588” [“名称”]=> string(36) “オンコリスバイオファーマ” } [3]=> array(2) { [“コード”]=> string(4) “4563” [“名称”]=> string(15) “アンジェス” } [4]=> array(2) { [“コード”]=> string(4) “4579” [“名称”]=> string(21) “ラクオリア創薬” } }

ぎゃああああああああああああああああああああああああ

File Access

file_get_contents()
Want to read the whole file

readfile()
Want to output the entire contents of the file

file()
want to read line-by-line text file as an array

fopen() + fread()
Want to read the file byte by byte

SplFileObject class
want to read CSV

SplFileObject class
want to operate object-oriented

サンプルのjsonデータを使ってみます。

{
    "glossary": {
        "title": "example glossary",
		"GlossDiv": {
            "title": "S",
			"GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
					"SortAs": "SGML",
					"GlossTerm": "Standard Generalized Markup Language",
					"Acronym": "SGML",
					"Abbrev": "ISO 8879:1986",
					"GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
						"GlossSeeAlso": ["GML", "XML"]
                    },
					"GlossSee": "markup"
                }
            }
        }
    }
}
$json = file_get_contents(__DIR__ . '/sample.json');
if($json === false){
	echo ('file not found.');
} else {
	$data = json_decode($json, true);
	var_dump($data);
}

file_get_contents() は、使用頻度高いです。

What is bind?

Bind variables are variables used in SQL statements, which are languages that perform writing and query to a database.

When making similar processing requests repeatedly while changing only a certain number to the database, if you re-set the number of the SQL statement each time, many types of SQL statements will be processed, which is inefficient. In such a case, if the bind variable is used, the database recognizes that “the same SQL statement is repeated processed under another condition”, so that the processing time can be efficiently improved and the processing time can be shortened.

In the case of Oracle Database, bind variables are represented by adding a colon(:) to the beginning of the variable name(e.g :number)


$sql = ‘select name, breed, weight from animals where weight > ? and weight < ?'; $conn = db2_connect($database, $user, $password); $stmt = db2_prepare($conn, $sql); $lower_limit = 1; db2_bind_param($stmt, 1, "lower_limit", DB2_PARAM_IN); db2_bind_param($stmt, 2, "upper_limit", DB2_PARAM_IN); $upper_limit = 15.0; if(db2_execute($stmt)){ while ($row = db2_fetch_array($stmt)){ print "{$row[0]}, {$row[1]}, {$row[2]}\n"; } } [/php]

About significant changes in PHP 7.3

The following changes in PHP 7.3

– Flexible Heredoc syntax and Nowdoc syntax
– End comma can be used in function call JSON_THROW_ON_ERROR
– Can use reference passing with list () is_countable function
– array_key_first(), array_key_last()
– Argon2 Password Hash Enhancement

Flexible description of heredoc/nowdoc statement
You can now indent the end markers and the text you insert.

if(TRUE){
	print<<<EOS
	foo
	EOS;
}
&#91;/php&#93;

The indent of the string is determined relative to the end marker's position(indent). This allows you to easily control the number of spaces inserted etc. Note that mixing blanks and tabs in a string is not permitted, as it is controlled by indenting, and an error will occur.

<b>mbstring case conversion is enhanced</b>
The mbstring extension was originally developed to handle multi-byte strings, but it is actually used by many PHP programmers, including single-byte users, as extensions for string processing. As of PHP 7.3, upper and lower-case conversion mainly used in single-byte range is enhanced.

[php]
echo mb_strtoupper("Straße");

Allow commas to be inserted at the end of function arguments
Previously, in PHP 7.2 and earlier versions, although it was possible to write a comma at the end of the last element of the array, it was not possible to insert a comma at the end of function arguments. For example, when creating a function definition automatically by a script, putting a comma at the end may make writing code easier. In such cases, new features are useful.

$a = [1,2];
$b = [3,4];
$c = array_merge($a,$b,[5,6],);

is_countable(), array_key_*() function added
As of PHP 7.3, the is_countable() function has been added to check for countable functions. It can be used for purposes such as checking the functions that can be specified in the count() function.

if(is_countable($foo)){
	//$fooはカウント可
}

$a = ['one'=>'First','two'=>'Second','three'=>'Thred'];
echo array_key_first($a); // one
echo array_key_last($a); // three

Support for Same-site Cookie
A PHP session supports the Same-site Cookie(suggested as RFC 6265) that is said to be effective for cross-site request forgery(CSRF) protection as a security related function imrovement. When the SameSite attribute is specified, corss-site requests are limited and supported by major we browsers such as Google Chrome.

zipからダウンロード

set_time_limit(0);

$zip_name = 'create_zip_'.date('Ymd').'.zip';
$zip_tmp_dir = dirname(__FILE__).'/tmp_zip/'; 

$zip_obj = new ZipArchive();

$result = $zip_obj -> open($zip_tmp_dir.$zip_name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
if(!$result){
    echo 'error code : '.$result;
    exit();
}

$files[] = [
	'zip_path' => 'building.jpg',
	'file_path' =>  dirname(__FILE__)."/".'building.jpg'
];

foreach ($files as $file)
{
    //ファイルを追加する場合
    $zip_obj -> addFile($file['file_path'], $file['zip_path']);
}

$zip_obj -> addFromString('test.txt', 'test');
$zip_obj -> close();

header('Content-Type: application/force-download;');
header('Content-Length: '.filesize($zip_tmp_dir.$zip_name));
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_tmp_dir.$zip_name);

$files[] = [
	'zip_path' => ['building.jpg', 'monkey.jpg'],
	'file_path' =>  ['building.jpg', 'monkey.jpg']
];

foreach ($files as $file)
{
    //ファイルを追加する場合
    $zip_obj -> addFile( dirname(__FILE__)."/".$file['file_path'], $file['zip_path']);
}

[Sun Apr 7 16:33:50 2019] PHP Notice: Undefined index: /home/vagrant/local/app/test/file_path in /home/vagrant/local/app/test/index.php on line 24
[Sun Apr 7 16:33:50 2019] PHP Warning: ZipArchive::addFile() expects parameter 2 to be string, array given in /home/vagrant/local/app/test/index.php on line 24

うん、まー要するに配列で渡せば、zipで複数ダウンロードできるってわけね。
チェックボックスなら、POSTで対象ファイルを渡せばOK

phpのzip機能

Check if PHP has Zip extension

[vagrant@localhost test]$ php -m

bz2
calendar
Core
ctype
curl
date
dom
exif
fileinfo
filter
ftp
gd
gettext
hash
iconv
intl
json
libxml
mbstring
mysqli
mysqlnd
openssl
pcntl
pcre
PDO
pdo_mysql
pdo_sqlite
Phar
readline
Reflection
session
SimpleXML
sockets
SPL
sqlite3
standard
tokenizer
wddx
xml
xmlreader
xmlwriter
xsl
zip
zlib

うん、ありますね。

phpでファイルダウンロード

$file_name = "building.jpg";
$file_path = dirname(__FILE__)."/".$file_name;

$download_file_name = "building.jpg";

header('Content-Type: application/force-download;');
header('Content-Length: '.filesize($file_path));
header('Content-Disposition: attachment; filename="'.$file_name.'"');

readfile($download_file_name);

特に問題なし

うーん、複数のファイルをDLしたいです。