busy studying php with a book called "php and mysql web development 4th edition". i have trouble with the following code. i am trying to create a text file. i'm testing all code on a live server
i get the following errors:
Warning: fopen(/home/truevvky/public_html/../orders/orders.txt): failed to open stream: No such file or directory in /home/truevvky/public_html/test/processorder.php on line 60
Warning: flock() expects parameter 1 to be resource, boolean given in /home/truevvky/public_html/test/processorder.php on line 62.
the idea is to create a new text file
<?php
//create short variable names
$tireqty = $_POST['tireqty'];
$oilqty = $_POST['oilqty'];
$sparkqty = $_POST['sparkqty'];
$address = $_POST['address'];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$date = date('H:i, jS F Y');
?>
<html>
<head>
<title>Bob's Auto Parts - Order Results</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Order Results</h2>
<?php
echo "<p>Order processed at ".date('H:i, jS F Y')."</p>";
echo "<p>Your order is as follows: </p>";
$totalqty = 0;
$totalqty = $tireqty + $oilqty + $sparkqty;
echo "Items ordered: ".$totalqty."<br />";
if ($totalqty == 0) {
echo "You did not order anything on the previous page!<br />";
} else{
if ($tireqty > 0) {
echo $tireqty." tires<br />";
}
if ($oilqty > 0) {
echo $oilqty." bottles of oil<br />";
}
if ($sparkqty > 0) {
echo $sparkqty." spark plugs<br />";
}
}
$totalamount = 0.00;
define('TIREPRICE', 100);
define('OILPRICE', 10);
define('SPARKPRICE', 4);
$totalamount = $tireqty * TIREPRICE
+ $oilqty * OILPRICE
+ $sparkqty * SPARKPRICE;
$totalamount = number_format($totalamount, 2, '.',' ');
echo "<p>Total of order is $".$totalamount."</p>";
echo "<p>Address to ship to is ".$address."</p>";
$outputstring = $date."\t".$tireqty." tires \t".$oilqty." oil\t"
.$sparkqty." spark plugs\t\$".$totalamount."\t".$address."\n";
// open file for appending
# $fp = fopen("$DOCUMENT_ROOT/../orders/orders.txt", 'ab');
flock($fp, LOCK_EX);
if (!$fp) {
echo "<p><strong> Your order could not be processed at this time.
Please try again later.</strong></p></body></html>";
exit;
}
fwrite($fp, $outputstring, strlen($outputstring));
flock($fp, LOCK_UN);
fclose($fp);
?>
</body>
</html>
I'm working on the same book and found the solution to his problem. I know this is old and maybe he figured this out, but wanted to put my answer for anyone else who encounters this.
for some reason in the book he puts flock before we even know if the file exist that's what is causing the error. flock() just puts a lock so that we can write LOCK_EX and fwrite() then writes whatever we output and LOCK_UN releases the lock.
for $DOCUMENT_ROOT mine with WAMP looked like this "C:/wamp/book/orders/orders.txt" so in the code remove the "..".
// open file for appending
# $fp = fopen("$DOCUMENT_ROOT/orders/orders.txt", 'ab');
if (!$fp) {
echo "<p><strong> Your order could not be processed at this time.
Please try again later.</strong></p></body></html>";
exit;
}
//you move flock down here
flock($fp, LOCK_EX);
fwrite($fp, $outputstring, strlen($outputstring));
flock($fp, LOCK_UN);
fclose($fp);
Opening file for appending works with file that exists. I would personally do something like
$path = "$DOCUMENT_ROOT/../orders/orders.txt";
$content = "Okay here are my contents";
$fp = null;
if(file_exists($path))
{
$fp = fopen($path, 'ab');
}
else
{
$fp = fopen("myText.txt","wb");
}
fwrite($fp,$content);
fclose($fp);
Maybe you did not create "orders" folder in "$DOCUMENT_ROOT/../" path. You should understand fopen('filepath', 'ab') just can create the specific file. If the path was not complete (can't find the "orders" folder), it won't work. So you can make the folder manually first, then test the .php
echo $DOCUMENT_ROOT
you could see your server's root address, mine is D:/AppServ/www.
If you use "$DOCUMENT_ROOT/../orders/orders.txt" you will get address: D:/AppServ/orders/orders.txt. Notice that you should be sure that you have a file folder named orders. So we can see that .. is to mean the parent directory of the document root directory, the parent directory is D:/AppServ.
Please make sure that the web server user can write a file on '/home/truevvky/public_html/../orders/' directory.
The fopen statement should be:
$fp = fopen("$DOCUMENT_ROOT/../orders/orders.txt", 'w');
Your way assumes the file exists.
By the way the 'b' you included in the second argument means you want to write the data in binary. If that's the case then fopen should be:
$fp = fopen("$DOCUMENT_ROOT/../orders/orders.txt", 'wb');
Related
I'm creating a code to display the name of a server with enterprise rules, So for don't use Mysql i try a new things (for me) use php to read and rewrite files, that work perfectly for one part of my code and work perfectly but for the second he only read one time, and when i do a f5 the code don't increment.
He rewrite correctly because my file was at 000 and become 001
I try to use file() but he is disable since 7.0, try to use SplFileObject but it don't want to display anything and i don't like it because i understand nothing when i use it so i come back to fopen(),fread() and fwrite() and that don't work. I'm inPHP 7.3.1
The code that works :
<?php
if ( isset($_POST) AND !empty($_POST) ) {
$nom = "./config.txt";
$filez = fopen($nom, "r") or die("Unable to open file!");
$i = fread($filez,filesize($nom));
$year = getdate();
$idy = substr($year[year], 2);
$fichier = fopen("./resultsrv.txt", "w") or die("Unable to write file!");
for ($z; $z<$_POST['nbr']+1 ; $z++) {
$id = sprintf("%04d", $i+$z);
$nome = $_POST['type'].$_POST['OS'].$idy.$id."<br>" ;
echo $nome;
$nomewout = str_replace("<br>", ";", $nome);
fwrite($fichier,$nomewout);
}
$handle = fopen("./config.txt", "w") or die("Unable to write file!");
fwrite($handle,$id);
fclose($fichier);
fclose($handle);
}
?>
and the one that doesn't work because he doesn't increment :
<?php
if ( isset($_POST) AND !empty($_POST) ) {
$fileName = 'confchass.txt';
$read = fopen($fileName,"r");
$fn = fopen($fileName,"w+");
$i = fread($read,filesize($fileName));
$id = sprintf("%03d", $i+1);
echo "<div align='center'><h1>Le Chassis</h1>";
echo $_POST['Marque'].$_POST['DC'].$id;
echo "</div>";
fwrite($fn,$id);
fclose($read);
fclose($fn);
}
?>
I want he output a thing like XXXXXX001 and when i refresh or do a new POST from my forms he output XXXXXX002 and XXXXXX003 .... But he actualy output only XXXXXX001
The problem is that you open the file for reading and then for writing. But from the manual...
'w+' Open for reading and writing; place the file pointer at the
beginning of the file and truncate the file to zero length. If the
file does not exist, attempt to create it.
So this will blank out the file before you read the value from it.
To fix this (using your current method, you should read the value, then open it for writing and write the new value...
$read = fopen($fileName,"r");
$i = fread($read,filesize($fileName));
fclose($read);
$id = sprintf("%03d", $i+1);
echo "<div align='center'><h1>Le Chassis</h1>";
echo $id;
echo "</div>";
$fn = fopen($fileName,"w+");
fwrite($fn,$id);
fclose($fn);
You could shorten this by using file_get_contents() and file_put_contents().
I have a 197gb text file that I want to read and push the contents into MySql database. I know, I can't put that big file in PHP buffer and read it as whole, So I want to read few hundred lines as a time and keep on reading next and next to read the whole file.
I am trying it with this but the page returns nothing
<?php
$i = 0;
$handle = fopen("./data/200gbfile.txt", "r") or die("Couldn't get handle");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line . "<br />";
if ($i > 100) {
exit;
}
$i++;
}
fclose($handle);
} else {
echo "Error Opeing File!";
}
?>
Is there a limit of the max file size to be handled in php setting?
EDIT: for the 197gb file in question, fopen is failing to return anything and
the output page is just going blank.
You can read the file in chunks to save memory:
For example:
$fd = #fopen("./data/200gbfile.txt", "r");
while (!feof($fd)) {
$data = fread($fd, 1024); // read the file in 1024kb chunks
// handle current data (read line by line for example)
}
fclose($fd);
But no idea if that works with a file with 100Gbytes+.
Edit: # with fopen is required as suggested by Roman.
you can use ini_set('memory_limit','16M'); to set size accordingly but i don't wether it will handle such huge file. never tested that..
I'm trying to create a text file-based sequential url rotator by using the following code (original source):
<?php
$linksfile ="urlrotator.txt";
$posfile = "pos.txt";
$links = file($linksfile);
$numlinks = count($linksfile);
$fp = fopen($posfile, 'r+') or die("Failed to open posfile");
flock($fp, LOCK_EX);
$num = fread($fp, 1024);
if($num<$numlinks-1) {
fwrite($fp, $num+1);
} else {
fwrite($fp, 0);
}
flock($fp, LOCK_UN);
fclose($fp);
header("Location: {$links[$num]}");
?>
After my testing, I found that it keeps appending new position number as a string after the existing content of pos.txt and thus the script only works at the first time.
I tried adding the following line of code before the if else statement in order to clear the existing content of pos.txt before updating it.
file_put_contents($posfile, "");
But then error ocurred at the line of redirection saying Undefined index: ...... .
Where could possibly go wrong?
I believe your problem comes from the mode you are using. When you say
After my testing, I found that it keeps appending new position number as a string after the existing content of pos.txt and thus the script only works at the first time.
it points me to the mode usage of fopen.
The mode you should use is w, as it will "replace" the content of what is inside pos.txt.
$fp = fopen($posfile, 'w') or die("Failed to open posfile");
Doing so will prevent your from accessing what was in pos.txt. So you need to have something like this:
$num = file_get_contents($posfile);
$fp = fopen($posfile, 'w') or die("Failed to open posfile");
flock($fp, LOCK_EX);
if($num<$numlinks-1) {
fwrite($fp, $num+1);
} else {
fwrite($fp, 0);
}
flock($fp, LOCK_UN);
fclose($fp);
<?php
set_time_limit(0);
$myfile = gzopen($constpath . '.gz', 'w');
if (!$myfile){
throw new \UnexpectedValueException('could not open datafeed.gz file');
}
$mystream = gzopen($constURL, 'r');
if (!$mystream){
throw new \UnexpectedValueException('could not open gzip remote file');
}
echo '1<br>';
while (!gzeof($mystream)){
$data = gzread($mystream, 8096);
gzwrite($myfile, $data);
}
echo '4<br>';
gzclose($mystream);
gzclose($myfile);
echo '5<br>';
echo 'down done';
//begin ungzip
$fp = fopen($constpath . '.csv', 'w');
$gz = gzopen($constpath . '.gz', 'r');
if (!$gz){
throw new \UnexpectedValueException(
'could not open gzip file'
);
}
if (!$fp){
gzclose($gz);
throw new \UnexpectedValueException(
'could not open destination file'
);
}
while (!gzeof($gz)) {
fwrite($fp, gzread($gz, 8096));
}
gzclose($gz);
fclose($fp);
echo 'ungzip done';
?>
Hi,
guys so above is my code, it intermittently allows me to download the gz file then unzip it, however it does not seem to be doing this in any sort of pattern or anything else, is there anything i need to know about how to use these functions like maybe is there a limit on the URL length (it's currently about 2.5K characters) but unfortunately not something i can change. what would people recommend on how to debug if there're bugs? or what i can do?
thanks!
EDIT: something i've noticed is that it is taking an absolute age to create a 25kB file, and previous to that it is 0kB, it then stops at 25kB
when i open the file in nano i get
^_�^H^#^#^#^#^#^#^C^#^#^#��^C^#^#^#^#^#^#^#^#^#
but when i unzip and open in windows there is nothing there?
i have this php code:
<?php
echo ("Setting up data...");
$today = date("YmdHi");
$wtoday = $today
$im = $_GET["im"];
$fim = "tips/$today/im.txt";
$fwtoday = "tips/$today/today.txt";
?>
<?php
$fp = fopen ($fwtoday, "w"); # w = write to the file only, create file if it does not exist, discard existing contents
if ($fp) {
fwrite ($fp, $wtoday);
fclose ($fp);
echo ("Today written");
}
else {
echo ("Today was not written");
}
?>
<?php
$fp = fopen ($fim, "w"); # w = write to the file only, create file if it does not exist, discard existing contents
if ($fp) {
fwrite ($fp, $im);
fclose ($fp);
echo ("Im written");
}
else {
echo ("Im was not written");
}
?>
Finaly Today and Im was not written, where is my error ???
i dont think that have to do with file permissions.
i forgot to write about $fwtoday = "tips/$today/today.txt"; in the post, still not working.
Insert these lines to the front of your file, and share given errors:
error_reporting(E_ALL);
ini_set('display_errors','On');
$wtoday = $today
Missing semicolon, parse error.
That asice, you appear to be attempting to open a filename stored in the variable $fwtoday, which you don't seem to have defined anywhere.
I don't see the definition of $fwtoday. Also you don't need to do this:
?>
<?php