Getting syntax error while using fopen and fread - php

$file = "status.txt";
$open = fopen($file, "r");
$size = filesize($file);
$count = fread($open, $size);
if($count == 1) {
header('Location: http://www.google.com/');
} else {
echo "Status is unavailable";
}
Hello, I am trying to read a text file.
I get the error Parse error: syntax error, unexpected T_STRING while doing this.
I am trying to read status.txt and if it has 1 it will redirect else it will say Status is unavailable.
Any ideas?

I must point out that for simple files like this, that file_get_contents is much easier than fopen, fread, fclose (which you omitted), etc.
The code that you posted does not appear to have any issues by itself. Perhaps you messed something up before that whole block? Try and comment things out to isolat the bug. This is a debugging skill you will need to acquire.

The error is not in those lines for sure! please include the whole PHP script, there're must be something wrong before or after those lines.
Please try this code out!
<?php
$file = 'status.txt';
$contents = file_get_contents($file);
if ((strlen($contents)-1) == 1) {
header('Location: http://www.google.com');
} else {
echo 'Status is unavailable';
}
?>
The (-1) in the compression because of the new line character count at the last line.

If you're talking about the content of "status.txt" please put the '1' between quotes. if it is just a TRUE or FALSE statement just use if($count){ ... }else{ ...}

Related

PHP Script ,php://input check for empty File

Hello i need help with my PHP script.
The Upload function works great, but many files are empty.
Can you help me please to check first IF file is empty or < 1 byte. and Ignore them.
<?php
$vist_page = "post2.php";
include "logger.php";
file_put_contents("outputfile.txt".uniqid(), file_get_contents("php://input"));
?>
Thanks ;)
One way to do that would be to use strlen() to check the length of the string, which could be done by replacing
file_put_contents("outputfile.txt".uniqid(), file_get_contents("php://input"));
with
$content = file_get_contents("php://input");
if (strlen($content)) {
file_put_contents("outputfile.txt".uniqid(), $content);
}
else {
// Your error response here
}
$filename = 'somefile.txt';
if (filesize($filename) < 1) {
//ignore
} else {
//do stuff here
}
filesize returns the file size in bytes
https://www.php.net/manual/en/function.filesize.php
this may be more effecient:
$filename = 'somefile.txt';
if (filesize($filename) > 0) {
//do stuff here
}

Perform a mathematical operation after retrieving from another file

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];
}

PHP: Missing records when writing to file

My telecom vendor is sending me a report each time a message goes out. I have written a very simple PHP script that receive values via HTTP GET. Using fwrite I write the query parameter to a CSV file.The filename is report.csv with the current date as a prefix.
Here is the code :
<?php
error_reporting(E_ALL ^ E_NOTICE);
date_default_timezone_set('America/New_York');
//setting a the CSV File
$fileDate = date("m-d-Y") ;
$filename = $fileDate."_Report.csv";
$directory = "./csv_archive/";
//Creating handle
$handle = fopen($filename, "a");
//These are the main data field
$item1 = $_GET['item1'];
$item2 = $_GET['item2'];
$item3 = $_GET['item3'];
$mydate = date("Y-m-d H:i:s") ;
$pass = $_GET['pass'];
//testing the pass
if (isset($_GET['pass']) AND $_GET['pass'] == "password")
{
echo 'Login successful';
// just making sure the function could write to it
if (!$handle = fopen($directory.$filename, 'a')){
echo "Cannot open file ($filename)";
exit;
}
//writing the data I receive through query string
if (fwrite($handle, "$item1,$item2,$item3,$mydate \n") === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
fclose($handle);
}
else{
echo 'Login Failure please add the right pass to URL';
}
?>
The script does what I want, but the only problem is inconsistency, meaning that a good portion of the records are missing (about half the report). When I log to my account I can get the complete report.
I have no clue of what I need to do to fix this, please advice.
I have a couple of suggestions for this script.
To address Andrew Rhyne's suggestion, change your code that reads from each $GET variable to:
$item1 = (isset($_GET['item1']) && $_GET['item1']) ? $_GET['item1'] : 'empty';
This will tell you if all your fields are being populated.
I suspect you problem is something else. It sounds like you are getting a seperate request for each record that you want to save. Perhaps some of these requests are happening to close together and are messing up each other's ability to open and write to the file. To check if this is happening, you might try using the following code check if you opened the file correctly. (Note that your first use of 'fopen' in your script does nothing, because you are overwriting $handle with your second use of 'fopen', it is also opening the wrong file...)
if (!$handle = fopen($directory.$filename, 'a')){
$handle = fopen($directory.date("Y-m-d H:i:s:u").'_Record_Error.txt', 'a');
exit;
}
This will make sure that you don't ever lose data because of concurrent write attempts. If you find that this is indeed you issue, you can delay subsequent write attempts until the file is not busy.
$tries = 0;
while ($tries < 50 && !$handle = fopen($directory.$filename, 'a')){
sleep(.5);//wait half a second
$tries++;
}
if($handle){
flock($handle);//lock the file to prevent other requests from opening the file until you are done.
} else {
$handle = fopen($directory.date("Y-m-d H:i:s:u").'_Record_Error.txt', 'a');//the 'u' is for milliseconds
exit;
}
This will spend 25 seconds, trying to open the file once every half second and will still output your record to a unique file every time you are still unable to open the file to write to. You can then safely fwrite() and fclose() $handle as you were.

PHP not writing to file from one source

I have an issue I can't seem to find the solution for. I am trying to write to a flat text file. I have echoed all variables out on the screen, verified permissions for the user (www-data) and just for grins set everything in the whole folder to 777 - all to no avail. Worst part is I can call on the same function from another file and it writes. I can't see to find the common thread here.....
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
if (!$Handle = fopen($File, 'w')) {
return "Cannot open file ($File)";
exit;
}/*
if(!flock($Handle, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain file lock';
exit(-1);
}*/
if (fwrite($Handle, $NewContents) === FALSE) {
return "Cannot write to file ($File)";
exit;
}else{
return $NewContents;
}
}else{
return "<p align=\"center\">There was an issue saving your settings. Please try again. If the issue persists contact your provider.</p>";
}
}
Try with...
$Handle = fopen($File, 'w');
if ($Handle === false) {
die("Cannot open file ($File)");
}
$written = fwrite($Handle, $NewContents);
if ($written === false) {
die("Invalid arguments - could not write to file ($File)");
}
if ((strlen($NewContents) > 0) && ($written < strlen($NewContents))) {
die("There was a problem writing to $File - $written chars written");
}
fclose($Handle);
echo "Wrote $written bytes to $File\n"; // or log to a file
return $NewContents;
and also check for any problems in the error log. There should be something, assuming you've enabled error logging.
You need to check for number of characters written since in PHP fwrite behaves like this:
After having problems with fwrite() returning 0 in cases where one
would fully expect a return value of false, I took a look at the
source code for php's fwrite() itself. The function will only return
false if you pass in invalid arguments. Any other error, just as a
broken pipe or closed connection, will result in a return value of
less than strlen($string), in most cases 0.
Also, note that you might be writing to a file, but to a different file that you're expecting to write. Absolute paths might help with tracking this.
The final solution I ended up using for this:
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
return $NewContents;
}else{
return "<p align=\"center\">There was an issue saving your settings.</p>";
}
}
function WriteNewConfigToFile($File2WriteName, $ContentsForFile){
file_put_contents($File2WriteName, $ContentsForFile, LOCK_EX);
}
I did end up using absolute file paths and had to check the permissions on the files. I had to make sure the www-data user in Apache was able to write to the files and was also the user running the script.

Fgets stops after 130 lines PHP

$done=0;
$filename = "raw_urls.txt";
if(! ($fhandle = fopen($filename, "r")))
{ echo "File failed to open";
Exit; }
//
// main loop reads sitemap url list
//
while($url_full_raw = fgets($fhandle,4096))
{
print (mysql_error());
$url_full= preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $url_full_raw);
if(strlen($url_full) > 3)
{
$url_stat++;
// Echo ' tp1 Url from sitemap:',$url_stat,' - ' ,$url_full,'<br>';
$end_st = strlen($url_full)-29;
$s_url= substr($url_full,29,$end_st);
//Echo 'short:',$s_url,'<br>';
$url_full_raw= '';
}
else{
$done++;
Echo '----------- short string ---------------';
}
//
// Check for url
//
$res1=sql("SELECT * FROM `spy3` WHERE `Landingpage` LIKE '%$s_url%' LIMIT 0, 30 ",$o);
if($row=mysql_fetch_array($res1))
{
$lp=$row[6];
$found++;
// Echo '------->Url from sitemap:',$url_full,'<br>';
}
else{
Echo 'Not Found:-> ',$s_url,'<br>';
$nfound++;
}
sql("insert into sitemap (url, stat_url,nf, s_recno)
values (
'$url_full',
'$lp',
'$nfound',
'$url_stat'
)", $o);
print (mysql_error());
$found=0;
$nfound=0;
}
So the code works great. Except for one problem, after about 130 lines, it stops. It exits the program with no error. Yes full error reporting is on. PHP.ini memory is huge.
If I edit the txt file and take out some lines, no difference. I have been working on this for many hours.
Try doing it like they do in their example... with !== false. i.e,
while(($url_full_raw = fgets($fhandle,4096))!==false) {
I'm guessing your content is evaluating to false for whatever reason. That just happens to be at 130 lines (throw the 130 lines into a text file and see if the file size is close to 4 KB).
Also, you might want to fix your formatting for next time. Makes it very hard for us to read and help you.

Categories