Running PHP Script from terminal with parameters
I try to get parameters and run php script from terminal. If one of the parameters is not exists, I want to thrown an exception. I used getopt function. But I could not figure out how to thrown exception. And when I call the script
php myscript.php --file: file1.csv --unique-combinations: file2.csv
it's not working.
<?php
$files = getopt("file:unique-combinations:");
if(!files["file"]) {
echo "Please provide a CSV file with parameter file";
} else if(!files["unique-combinations"]) {
echo "Please provide a file name to save unique combinations with parameter unique-combinations";
} else {
$datas = array_count_values(file(files["file"]));
$fp = fopen(files["unique-combinations"], 'w');
foreach($datas as $data => $value) {
fputcsv($fp, $data);
}
fclose($fp);
}
?>
Could someone help me to figure out this.
Answer
Solution:
Issues
- Passed long options arguments but trying to get short options https://www.php.net/manual/en/function.getopt.php
- Use
=
instead of:
in the command - Invalid variable syntax. missing
$
- Incomplete logic
Command
php myscript.php --file=file1.csv --unique-combinations=file2.csv
Working Code
<?php
$files = getopt("", ["file:", "unique-combinations:"]);
if (!isset($files["file"])) {
echo "Please provide a CSV file with parameter file";
} else if (!isset($files["unique-combinations"])) {
echo "Please provide a file name to save unique combinations with parameter unique-combinations";
} else {
$datas = array_count_values(file($files["file"]));;
$fp = fopen($files["unique-combinations"], 'w');
foreach ($datas as $data => $value) {
fputcsv($fp, explode(',', trim($data)));
}
fclose($fp);
}
Source