shell_exec not working with dynamic commands - php

<?php
ini_set('max_execution_time', 864000);
$seq = "D:/Ractip/Sequence.txt";
$mir = "D:/Ractip/mirhominid.txt";
$shandle = fopen($seq, 'r');
$sdata = fread($shandle, filesize($seq));
$mhandle = fopen($mir, 'r');
$mdata = fread($mhandle, filesize($mir));
$sexp = explode(">", $sdata);
$mexp = explode(">", $mdata);
$i = 1;
$a = 1;
$count = count($sexp);
while($i < $count)
{
$name = explode("\n", $mexp[$a]);
$name = explode(" ", $name[0]);
$name1 = explode("\n", $sexp[$i]);
$file2 = "D:\Ractip\mir\\"."$name[1]".".txt";
$file1 = "D:\Ractip\sequence\\"."name1[0]".".txt";
if ($i == 1){
mkdir("D:/Ractip/Interactions/"."$name[1]", 0777);
}
$file = "D:/Ractip/Interactions/"."$name[1]"."/"."$name1[0]"."+"."$name[1]".".txt";
$fhandle = fopen($file, 'w');
$query = "ractip "."$file1"." "."$file2";
$exec = shell_exec($query);
print $exec;
fwrite($fhandle, $exec);
fclose($fhandle);
if ($i == $count){
$i = 1;
$a++;
}else{
$i++;
}
}
?>
This is the script. I am basically using a tool to get results of roughly 37.5 million combinations, so as you can understand it isn't something I can do on my own, therefore came along this script, previously I separated all candidates into individual files and so that is the explanation for the $name variables I'm calling them that way.
The problem is the shell_exec command, a preliminary Google search really did not explain why it is behaving this way, but shell_exec refuses to process dynamic commands, instead if I were to make a static command like ractip xy.txt zy.txt it will process that, what I need to do is build the command and then make the shell_exec process it, which it unfortunately isn't doing, it would be really helpful if someone can explain why this command behaves this way and if there is a workaround to this glitch.
I've finally gotten around to understanding what a guy on a forum meant when he said that these are just some things php doesn't do very well.
Oh yes, and I am deploying it through the browser, dunno if that is any help.

On both Windows and Linux, you'll be better off by keeping all slashes like "/".
Also, looks like you forgot a $ in $file1:
$file2 = "D:/Ractip/mir/" . $name[1] . '.txt';
$file1 = "D:/Ractip/sequence/" . $name1[0] . ".txt";
Finally, just in case, for clarity, I'd write
$query = "ractip '$file1' '$file2'";
or
$query = 'ractip ' . $file1 . ' ' . $file2 ;
You don't really need to quote a single string variable, i.e. $string and "$string" are the same thing. I did quote $file1 and $file2 with single quotes /inside/ $query, because, if the names contain spaces, the ractip utility would get confused as to where one filename stops and another starts. Maybe it's not your case here, but anyway...

What I observed in your code is that in the file names you are passing, the slashes are not properly escaped:
$file2 = "D:\\Ractip\\mir\\"."$name[1]".".txt";
$file1 = "D:\\Ractip\\sequence\\"."name1[0]".".txt";
This might be causing the command to search for a wrong file

Related

php program cannot change the values of text file

I'm making a unique visitors counter for my website and I went for many tutorials, until I found this easy code but the problem is that the program never adds new ips or counts new visits . The values of ip.txt and count.txt never change :(
Here is the whole code :
<?php
function hit_count() {
$ip_address = $_SERVER ['REMOTE_ADDR'];
$ip_file = file ('ip.txt');
foreach($ip_file as $ip) {
$ip_single = ($ip);
if ($ip_address==$ip_single){
$found = true;
break;
} else {
$found = false;
}
}
if ($found==true){
$filename = 'count.txt';
$handle = fopen ($filename, 'r');
$current = fread($handle, filesize($filename));
fclose($handle);
$current_inc = $current = 1;
$handle = fopen($filename, 'w');
fwrite($handle, $current_inc);
fclose($handle);
$handle = fopen('ip.txt', 'a');
fwrite($handle, $ip_address."\n");
fclose($handle);
}
}
?>
This code is full of mistakes. It will never work.
Mistake number #1:
$ip_file = file('ip.txt');
Each element on $ip_file ends with a newline symbol, so even if your IP is in the list it will never match $_SERVER ['REMOTE_ADDR']. file() must be run with the FILE_IGNORE_NEW_LINES flag.
Mistake number #2:
if ($found==true){
The counter will only increase and try to add the IP in the list if it was already found in the list. If the list is empty it will never do jack. Invert this logic!
Mistake number #3:
$current_inc = $current = 1;
It will never count beyond 1.
Besides that, you must make sure that the PHP script has permission to change those files. Usually the scripts don't have permission to edit the site files for security reasons.
All that said, your script should be changed to something more like this:
if (!in_array($_SERVER['REMOTE_ADDR'], file('ip.txt', FILE_IGNORE_NEW_LINES)))
{
file_put_contents('ip.txt', $_SERVER['REMOTE_ADDR'] . "\n", FILE_APPEND);
$count = file_get_contents('count.txt');
$count++;
file_put_contents('count.txt', $count);
}
Clean, simple, direct. But you still have to make sure the PHP script has permission to edit those files.

PHP fwrite writing empty file

I'm trying to make this save a file and it creates the file, but it's always empty. This is the code for it:
<?php
$code = htmlentities($_POST['code']);
$i = 0;
$path = 'files/';
$file_name = '';
while(true) {
if (file_exists($path . strval($i) . '.txt')) {
$i++;
} else {
$name = strval($i);
$file_name = $path . $name . '.txt';
break;
}
}
fopen($file_name, 'w');
fwrite($file_name, $code);
fclose($file_name);
header("location: index.php?file=$i");
?>
I echoed out $code to make sure it wasn't empty, and it wasn't. I also tried replacing
fwrite($file_name, $code);
with this:
fwrite($file_name, 'Test');
and it was still empty. I have written to files a couple of times before in PHP, but I'm still really new to PHP and I have no idea whats wrong. Could someone tell me what I'm doing wrong or how to fix this? Thanks
Reading/Writing to/from a file or stream requires a resource handle:
$resource = fopen($file_name, 'w');
fwrite($resource, $code);
fclose($resource);
The resource handle $resource is essentially a pointer to the open file/stream resource. You interact with the created resource handle, not the string representation of the file name.
This concept also exists with cURL as well. This is a common practice in PHP, especially since PHP didn't have support for OOP when these methods came to be.
Take a look of the samples on php.net

Simple Site Stat script not gathering data from file, I have an almost exact script that works

I made a script a while ago that wrote to a file, I did the same thing here, only added a part to read the file and write it again. What I am trying to achive is quite simple, but the problem is eluding me, I am trying to make my script write to a file basically holding the following information
views:{viewcount}
date-last-visited:{MM/DD/YYYY}
last-ip:{IP-Adress}
Now I have done a bit of research, and tried several methods to reading the data, none have returned anything. My current code is as follows.
<?php
$filemade = 0;
if(!file_exists("stats")){
if(!mkdir("stats")){
exit();
}
$filemade = 1;
}
echo $filemade;
$hwrite = fopen("stats/statistics.txt", 'w');
$icount = 0;
if(filemade == 0){
$data0 = file_get_contents("stats/statistics.txt");
$data2 = explode("\n", $data0);
$data1 = $data_1[0];
$ccount = explode(":", data1);
$icount = $ccount[1] + 1;
echo "<br>icount:".$icount."<br>";
echo "data1:".$data1."<br>";
echo "ccount:".$ccount."<br>";
echo "ccount[0]:".$ccount1[0]."<br>";
echo "ccount[1]:".$ccount1[1]."<br>";
}
$date = getdate();
$ip=#$REMOTE_ADDR;
fwrite($hwrite, "views:" . $icount . "\nlast-viewed:" . $date[5] . "/" . $date[3] . $date[2] . "/" . $date[6] . "\nlast-ip:" . $ip);
fclose($hwrite);
?>
the result is always:
views:1
last-viewed://
last-ip:
the views never go up, the date never works, and the IP address never shows.
I have looked at many sources before finally deciding to ask, I figured I'd get more relevant information this way.
Looking forward to some replies. PHP is my newest language, and so I don't know much.
What I have tried.
I have tried:
$handle_read = fopen("stats/statistics.txt", "r");//make a new file handle in read mode
$data = fgets($handle_read);//get first line
$data_array = explode(":", $data);//split first line by ":"
$current_count = $data_array[1];//get second item, the value
and
$handle_read = fopen("stats/statistics.txt", "r");//make a new file handle in read mode
$pre_data = fread($handle_read, filesize($handle_read));//read all the file data
$pre_data_array = explode("\n", $pre_data);//split the file by lines
$data = pre_data_array[0];//get first line
$data_array = explode(":", $data);//split first line by ":"
$current_count = $data_array[1];//get second item, the value
I have also tried split instead of explode, but I was told split is deprecated and explode is up-to-date.
Any help would be great, thank you for your time.
Try the following:
<?php
if(!file_exists("stats")){
if(!mkdir("stats")) die("Could not create folder");
}
// file() returns an array of file contents or false
$data = file("stats/statistics.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if(!$data){
if(!touch("stats/statistics.txt")) die("Could not create file");
// Default Values
$data = array("views:0", "date-last-visited:01/01/2000", "last-ip:0.0.0.0");
}
// Update the data
foreach($data as $key => $val){
// Limit explode to 2 chunks because we could have
// IPv6 Addrs (e.x ::1)
$line = explode(':', $val, 2);
switch($key){
case 0:
$line[1]++;
break;
case 1:
$line[1] = date('m/d/Y');
break;
case 2:
$line[1] = $_SERVER['REMOTE_ADDR'];
break;
}
$data[$key] = implode(':', $line);
echo $data[$key]. "<br />";
}
// Write the data back into the file
if(!file_put_contents("stats/statistics.txt", implode(PHP_EOL, $data))) die("Could not write file");
?>

PHP get array of words from txt file

I have a text file with spam words. I want to have an array filled with those words.
I've tried doing:
$fp = #fopen("../files/spam.txt",'rb');
$words = fgetcsv($fp,100,"\n");
but it doesn't work (words only has the first letter of the txt file in it first cell).
do you how to do this?
EDIT:
the .txt file looks like this:
yahoo
google
msn
blah
blah
EDIT:
I DONT KNOW WHAT IS A CSV FILE! THIS IS A TEXT FILE! I JUST GIVE AN EXAMPLE.
please could some1 help me it looks really easy, i just dont understand.
That is not a CSV file. CSV stands for comma separated values. You have no commas!
$spam_words = file('../files/spam.txt', FILE_IGNORE_NEW_LINES);
All you need to do is:
$words = file('./files/spam.txt',FILE_IGNORE_NEW_LINES);
$artic = array(); //create a array
$directory = "/var/www/application/store/"; //define path
$files1 = scandir($directory); //scan the directory
$c = count($files1); //count the files the directory
print $c; //print it
for($i = 2; $i < $c; $i++) {
print "<br />" . $files1[$i];
$f = $directory . $files1[$i];
print $f . "<br />";
$h = fopen($f, 'r') or die("cannot open a file!!". $f);
$line1 = fgets($h);
list($id, $idval) = explode("\t\t", $line1);
print "$id";
}
How about splitting the string you read from the file into an array?
split() function definition.
$string = "Niagara Becks Corn";
$array = split(" ", $string);
# ["Niagara", "Becks", "Corn"]
Use the 'file' function to read a PHP file from the disk into an array. See the manual here: http://php.net/manual/en/function.file.php
Try this
$file = file_get_contents('spam.txt');
$file_words = explode(" ", $file);
$file_count = count($file_words);
for ($i=0; $i < $file_count; $i++){
echo $file_words[$i] . "<br />";
}
Your spam.txt file should look like this:
yahoo msn google

PHP write to file

below is some code I am using to "translate" a map array into SQL code so I can easily update my database when I have updated my game map. As you can see it prints out the SQL code onto the screen so I can copy and paste it.
As my maps will get bigger this will become inefficient as it will crash the browser due to mass output, so instead I am wondering if it is possible to make it create a .txt file and write all of the data to it instead of printing onto the screen?
<?php
if (isset($_POST['code'])){
$map = $_POST['code'];
$map = preg_replace("/,\\s*}/i", "}", $map);
$map = str_replace("{", "[", $map);
$map = str_replace("}", "]", $map);
$map = json_decode('[' . $map . ']');
$arrayCount1 = 0;
$arrayCount2 = -1;
$H = sprintf('%05d', 00000);
$V = sprintf('%05d', 00000);
$id = 1;
echo "INSERT INTO `map` (`id`, `horizontal`, `verticle`, `image`) VALUES" . "<br />";
for ($count1 = 0; $count1 < sizeof($map[0]); $count1++){
$arrayCount2++;
$arrayCount1 = 0;
$V = sprintf('%05d', $V + 1);
$H = sprintf('%05d', 00000);
for ($count2 = 0; $count2 < sizeof($map); $count2++){
echo "(" . $id . ", '" . $H . "', '" . $V . "', '" . $map[$arrayCount1][$arrayCount2] . "')," . "<br />";
$arrayCount1++;
$id++;
$H = sprintf('%05d', $H + 1);
}
}
}
?>
That should be quite simple. Add
// second parameter 'a' stands for APPEND
$f = fopen('/path/to/the/file/you/want/to/write/to', 'a');
to the beginning of your script.
Add
fclose($f);
to the end fo your script to cleanly close the file handle (good pratice even though handles would be closed the the terminating script automatically).
And the change all your echo's and prints to
fwrite($f, '<<your string>>');
EDIT:
That way you can even compress the data on the fly using a compression stream wrapper if amnount of data gets really large.
There is an even simpler approach:
ob_start();
# Your code here ...
file_put_contents('yourfile.txt', ob_get_clean());
If this is something you plan on writing on a regular interval or by different scripts, look at using flock() to lock the file and prevent data corruption.
$fp = fopen("/tmp/lock.txt", "w+");
if (flock($fp, LOCK_EX)) { // do an exclusive lock
fwrite($fp, "Write something here\n");
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't lock the file !";
}
fclose($fp);
$str = <<<your string comes here>>>
if( $fh = #fopen( "myfile.txt", "a+" ) ) {
fputs( $fh, $str, strlen($str) );
fclose( $fh );
}
this should do...
write all the lines and then send the file to the client.
Check this post for further instructions
+my 2 cents:
You may check your database servers mass data loading features, as most of them can load files in batch faster than performing thousands of inserts.

Categories