Perform a mathematical operation after retrieving from another file - php

I have a text file (math.txt) in which any kind of arithmetic operation could be written. I have to read the file using PHP and determine the output. I am using the below mentioned code to read the content of the file.
$file = 'math.txt'; // 2+3 is written in math.txt
$open = fopen($file, 'r');
$read = fgets($open);
$close = fclose($open);
Using the above code, i am getting the content. But echoing the content is displaying the original content (i.e 2+3) rather than displaying the output(i.e 5). I am not understanding what should i do in this case.
Any help on this will be appreciated. Thanks in advance.

But echoing the content is displaying the original content (i.e 2+3)
rather than displaying the output(i.e 5).
This is completely expected behaviour. You read a string from a file. How should PHP know that you want it to calculate the expression?
You have to implement a simple parser (or search one on the Internet) which analyses the expression and caulates the result.
dave1010 provided a very nice function in one of his posts:
function do_maths($expression) {
eval('$o = ' . preg_replace('/[^0-9\+\-\*\/\(\)\.]/', '', $expression) . ';');
return $o;
}
echo do_maths('1+1');
But note that this can still halt your script execution if the input contains a syntax error!
Here is a better library which uses a real parser: https://github.com/stuartwakefield/php-math-parser

read the file parse according to operator
like file=2*5;
$open = fopen($file, 'r');
$read = fgets($open);
$key = preg_split("/[*+-\/]+/", $read);
$operator= substr($a, strpos($a,$key[1])-1,1);
if($operator=='+')
{
echo $key[0]+ $key[1];
}
else if($operator=='-')
{
echo $key[0]- $key[1];
}
else if($operator=='*')
{
echo $key[0]* $key[1];
}
else if($operator=='/')
{
echo $key[0]/$key[1];
}

Related

How to assign SplFileObject::fpassthru output to variable

I'm currently writing some data to an SplFileObject like this:
$fileObj = new SplFileObject('php://text/plain,', "w+");
foreach($data as $row) {
$fileObj->fputcsv($row);
}
Now, I want to dump the whole output (string) to a variable.
I know that SplFileObject::fgets gets the output line by line (which requires a loop) but I want to get it in one go, ideally something like this:
$fileObj->rewind();
$output = $fileObj->fpassthru();
However, this does not work as it simply prints to standard output.
There's a solution for what I'm trying to achieve using stream_get_contents():
pass fpassthru contents to variable
However, that method requires you to have direct access to the file handle.
SplFileObject hides the file handle in a private property and therefore not accessible.
Is there anything else I can try?
After writing, do a rewind() then you can read everything. The example is for understanding:
$fileObj = new SplFileObject('php://memory', "w+");
$row = [1,2,'test']; //Test Data
$fileObj->fputcsv($row);
$fileObj->rewind();
//now Read
$rowCopy = $fileObj->fgetcsv();
var_dump($row == $rowCopy);//bool(true)
$fileObj->rewind();
$strLine = $fileObj->fgets(); //read as string
$expected = "1,2,test\n";
var_dump($strLine === $expected); //bool(true)
//several lines
$fileObj->rewind();
$fileObj->fputcsv(['test2',3,4]);
$fileObj->fputcsv(['test3',5,6]);
$fileObj->rewind();
for($content = ""; $row = $fileObj->fgets(); $content .= $row);
var_dump($content === "test2,3,4\ntest3,5,6\n"); //bool(true)
If you absolutely have to fetch your content with only one command then you can do this too
// :
$length = $fileObj->ftell();
$fileObj->rewind();
$content = $fileObj->fread($length);
getSize() doesn't work here.
In the absence of an inbuilt function I've decided to do php output buffering as #CBroe had suggested.
...
$fileObj->rewind();
ob_start();
$fileObj->fpassthru();
$buffer = ob_get_clean();
See #jsplit's answer for a better method using SplFileObjects inbuilt functions

Fwrite PHP - How to output full loop to file?

I have created a script that's working great, but I want to take it to the next level and create a file for this information automatically. The problem is that when I add my looped elements to using fwrite, it only writes the first entry to the file.
Sample code:
$totallines=count($lines);
$i=0;
foreach($lines as $line) {
$i=$i;
$trimmed = trim($line);
$linesgetdomain = explode('/',$trimmed);
$domain = $linesgetdomain[2];
$qmark = "?";
$front301qmark = "Front Part ";
$end301qmark = " End Part";
$lastpartqmark = "Last Part $domain";
if (strpos($trimmed,$qmark) !== false) {
strstr($trimmed, '?');
echo $front301qmark;
echo substr(strstr($trimmed, '?'), strlen('?'));
echo $end301qmark;
echo "<br>";
echo $lastpartqmark;
echo "<br>";
} else {
What I tried (placing this before } else {):
$fpqmark = fopen('test.txt', 'w');
fwrite($fpqmark, $front301qmark);
fwrite($fpqmark, substr(strstr($trimmed, '?'), strlen('?')));
fwrite($fpqmark, $end301qmark);
fwrite($fpqmark, PHP_EOL);
fwrite($fpqmark, $lastpartqmark);
fwrite($fpqmark, PHP_EOL);
fclose($fpqmark);
How can I write the entire loop to a file instead of just the first line? The output displays properly in normal format, but not when writing to a file.
Apologizes beforehand if this is a basic question. I'm new to PHP and my understandings of certain concepts are a bit vague. Sort of surprised I even managed to get this script to work. (This is only a small part of it, but if I can learn how to do this, I should be able to do the rest).
instead of using write,
$fpqmark = fopen('test.txt', 'w');
Use apend,
$fpqmark = fopen('test.txt', 'a');
The it will resolve your problem.

How to read a csv file with php code inside?

i searched Google but found nothing what fits for my problem, or i search with the wrong words.
In many threads i read, the smarty Template was the solution, but i dont wont use smarty because its to big for this little project.
My problem:
I got a CSV file, this file contents only HTML and PHP code, its a simple html template document the phpcode i use for generating dynamic imagelinks for example.
I want to read in this file (that works) but how can i handle the phpcode inside this file, because the phpcode shown up as they are. All variables i use in the CSV file still works and right.
Short Version
how to handle, print or echo phpcode in a CSV file.
thanks a lot,
and sorry for my Bad english
Formatting your comment above you have the following code:
$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
$zeile = fgets($userdatei);
echo $zeile;
}
fclose($userdatei);
// so i read in the csv file and the content of csv file one line:
// src="<?php echo $bild1; ?>" ></a>
This is assuming $bild1 is defined somewhere else, but try using these functions in your while loop to parse and output your html/php:
$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
$zeile = fgets($userdatei);
outputResults($zeile);
}
fclose($userdatei);
//-- $delims contains the delimiters for your $string. For example, you could use <?php and ?> instead of <?php and ?>
function parseString($string, $delims) {
$result = array();
//-- init delimiter vars
if (empty($delims)) {
$delims = array('<?php', '?>');
}
$start = $delims[0];
$end = $delims[1];
//-- where our delimiters start/end
$php_start = strpos($string, $start);
$php_end = strpos($string, $end) + strlen($end);
//-- where our php CODE starts/ends
$php_code_start = $php_start + strlen($start);
$php_code_end = strpos($string, $end);
//-- the non-php content before/after the php delimiters
$pre = substr($string, 0, $php_start);
$post = substr($string, $php_end);
$code_end = $php_code_end - $php_code_start;
$code = substr($string, $php_code_start, $code_end);
$result['pre'] = $pre;
$result['post'] = $post;
$result['code'] = $code;
return $result;
}
function outputResults($string) {
$result = parseString($string);
print $result['pre'];
eval($result['code']);
print $result['post'];
}
Having PHP code inside a CSV file that should be parsed and probably executed using eval sounds pretty dangerous to me.
If I get you right you just want to have dynamic parameters in your CSV file right? If thats the case and you don't want to implement an entire templating language ( like Mustache, Twig or Smarty ) into your application you could do a simple search and replace thing.
$string = "<img alt='{{myImageAlt}}' src='{{myImage}}' />";
$parameters = [
'myImageAlt' => 'company logo',
'myImage' => 'assets/images/logo.png'
];
foreach( $parameters as $key => $value )
{
$string = str_replace( '{{'.$key.'}}', $value, $string );
}

parse remote csv-file with PHP on GAE

I seem to be in a catch-22 with a small app I'm developing in PHP on Google App Engine using Quercus;
I have a remote csv-file which I can download & store in a string
To parse that string I'd ideally use str_getcsv, but Quercus doesn't have that function yet
Quercus does seem to know fgetcsv, but that function expects a file handle which I don't have (and I can't make a new one as GAE doesn't allow files to be created)
Anyone got an idea of how to solve this without having to dismiss the built-in PHP csv-parser functions and write my own parser instead?
I think the simplest solution really is to write your own parser . it's a piece of cake anyway and will get you to learn more regex- it makes no sense that there is no csv string to array parser in PHP so it's totally justified to write your own. Just make sure it's not too slow ;)
You might be able to create a new stream wrapper using stream_wrapper_register.
Here's an example from the manual which reads global variables: http://www.php.net/manual/en/stream.streamwrapper.example-1.php
You could then use it like a normal file handle:
$csvStr = '...';
$fp = fopen('var://csvStr', 'r+');
while ($row = fgetcsv($fp)) {
// ...
}
fclose($fp);
this shows a simple manual parser i wrote with example input with qualifed, non-qualified, escape feature. it can be used for the header and data rows and included an assoc array function to make your data into a kvp style array.
//example data
$fields = strparser('"first","second","third","fourth","fifth","sixth","seventh"');
print_r(makeAssocArray($fields, strparser('"asdf","bla\"1","bl,ah2","bl,ah\"3",123,34.234,"k;jsdfj ;alsjf;"')));
//do something like this
$fields = strparser(<csvfirstline>);
foreach ($lines as $line)
$data = makeAssocArray($fields, strparser($line));
function strparser($string, $div = ",", $qual = "\"", $esc = "\\") {
$buff = "";
$data = array();
$isQual = false; //the result will be a qualifier
$inQual = false; //currently parseing inside qualifier
//itereate through string each byte
for ($i = 0; $i < strlen($string); $i++) {
switch ($string[$i]) {
case $esc:
//add next byte to buffer and skip it
$buff .= $string[$i+1];
$i++;
break;
case $qual:
//see if this is escaped qualifier
if (!$inQual) {
$isQual = true;
$inQual = true;
break;
} else {
$inQual = false; //done parseing qualifier
break;
}
case $div:
if (!$inQual) {
$data[] = $buff; //add value to data
$buff = ""; //reset buffer
break;
}
default:
$buff .= $string[$i];
}
}
//get last item as it doesnt have a divider
$data[] = $buff;
return $data;
}
function makeAssocArray($fields, $data) {
foreach ($fields as $key => $field)
$array[$field] = $data[$key];
return $array;
}
if it can be dirty and quick. I would just use the
http://php.net/manual/en/function.exec.php
to pass it in and use sed and awk (http://shop.oreilly.com/product/9781565922259.do) to parse it. I know you wanted to use the php parser. I've tried before and failed simply because its not vocal about its errors.
Hope this helps.
Good luck.
You might be able to use fopen with php://temp or php://memory (php.net) to get it to work. What you would do is open either php://temp or php://memory, write to it, then rewind it (php.net), and then pass it to fgetcsv. I didn't test this, but it might work.

file_get_contents create file is not exists

Is there any alternative to file_get_contents that would create the file if it did not exist. I am basically looking for a one line command. I am using it to count download stats for a program. I use this PHP code in the pre-download page:
Download #: <?php $hits = file_get_contents("downloads.txt"); echo $hits; ?>
and then in the download page, I have this.
<?php
function countdownload($filename) {
if (file_exists($filename)) {
$count = file_get_contents($filename);
$handle = fopen($filename, "w") or die("can't open file");
$count = $count + 1;
} else {
$handle = fopen($filename, "w") or die("can't open file");
$count = 0;
}
fwrite($handle, $count);
fclose($handle);
}
$DownloadName = 'SRO.exe';
$Version = '1';
$NameVersion = $DownloadName . $Version;
$Cookie = isset($_COOKIE[str_replace('.', '_', $NameVersion)]);
if (!$Cookie) {
countdownload("unqiue_downloads.txt");
countdownload("unique_total_downloads.txt");
} else {
countdownload("downloads.txt");
countdownload("total_download.txt");
}
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$DownloadName.'" />';
?>
Naturally though, the user accesses the pre-download page first, so its not created yet. I do not want to add any functions to the pre download page, i want it to be plain and simple and not alot of adding/changing.
Edit:
Something like this would work, but its not working for me?
$count = (file_exists($filename))? file_get_contents($filename) : 0; echo $count;
Download #: <?php
$hits = '';
$filename = "downloads.txt";
if (file_exists($filename)) {
$hits = file_get_contents($filename);
} else {
file_put_contents($filename, '');
}
echo $hits;
?>
you can also use fopen() with 'w+' mode:
Download #: <?php
$hits = 0;
$filename = "downloads.txt";
$h = fopen($filename,'w+');
if (file_exists($filename)) {
$hits = intval(fread($h, filesize($filename)));
}
fclose($h);
echo $hits;
?>
Type juggling like this can lead to crazy, unforeseen problems later. to turn a string to an integer, you can just add the integer 0 to any string.
For example:
$f = file_get_contents('file.php');
$f = $f + 0;
echo is_int($f); //will return 1 for true
however, i second the use of a database instead of a text file for this. there's a few ways to go about it. one way is to insert a unique string into a table called 'download_count' every time someone downloads the file. the query is as easy as "insert into download_count $randomValue" - make sure the index is unique. then, just count the number of rows in this table when you need the count. the number of rows is the download count. and you have a real integer instead of a string pretending to be an integer. or make a field in your 'download file' table that has a download count integer. each file should be in a database with an id anyway. when someone downloads the file, pull that number from the database in your download function, put it into a variable, increment, update table and show it on the client however you want. use PHP with jQuery Ajax to update it asynchronously to make it cool.
i would still use php and jquery.load(file.php) if you insist on using a text file. that way, you can use your text file for storing any kind of data and just load the specific part of the text file using context selectors. the file.php accepts the $_GET request, loads the right portion of the file and reads the number stored in the file. it then increments the number stored in the file, updates the file and sends data back to the client to be displayed any way you want. for example, you can have a div in your text file with an id set to 'downloadcount' and a div with an id for any other data you want to store in this file. when you load file.php, you just send div#download_count along with the filename and it will only load the value stored in that div. this is a killer way to use php and jquery for cool and easy Ajax/data driven apps. not to turn this into a jquery thread, but this is as simple as it gets.
You can use more concise equivalent yours function countdownload:
function countdownload($filename) {
if (file_exists($filename)) {
file_put_contents($filename, 0);
} else {
file_put_contents($filename, file_get_contents($filename) + 1);
}
}

Categories