PHP: How to check if file is complete - php

I would like to generate a csv using PHP but I want to download the file later using file_get_contents when it is complete. Is there a way to check if a file is already complete?

It's ok, but the way you are doing it is wrong (at least "not correct at all").
fgets() returns false, if the end of the file is reached, thus you should test against false instead. It works for you, because you use the "simple" equality operator (==), that will case null to false, when comparing against a boolean.
Returns a string of up to length - 1 bytes read from the file pointed to by handle. If there is no more data to read in the file pointer, then FALSE is returned.
If an error occurs, FALSE is returned.
This means, it have to look like:
while (($c = fgets($f)) !== false) {
doSomethingWith($c);
}

Related

PHP: Error handling with include

$file= #fopen("ssssss.php", r) or die("not found");
(#include("ssssss.php")) or die("not found");
In the first statement we don't put ( ) around #fopen and it is working fine.
But in the second if I didn't put these () it does't show any message.
so why with include I must round it with ( ) ?
I agree with the suggestions in the other answers but the actual answer to your question is this:
In the PHP documentation they say to take care when comparing the return value of include.
That's because it is a special construct and parentheses are not needed.
So when you do this (without wrapping parentheses):
#include("ssssss.php") or die("not found");
You're actually doing this, because or is evaluated first:
#include (("ssssss.php") or die("not found"));
Now, "ssssss.php" is a non empty string that evaluates logically to true.
or is a logical operator that gives true if any of the parameters is true (or both of them).
Also, this operator is short-circuit: if the first parameter is true, php already knows that the operator or will return true, so it doesn't waste time evaluating the second parameter, and die() is not executed.
So finally, or gives true and your sentence becames this:
#include (1);
Php tries to "include 1", and it would raise a warning but it does not because of the #.
Here you have a similar example in php.net.
Your first sentence is not the same case.
$file= #fopen("ssssss.php", r) or die("not found");
fopen is just a regular Php's function with its parentheses. Here you need to have in mind two operators: = and or.
= has higher precedence than or, so, if fopen's result is correctly assigned to $file (and it is), that operation will return true. And, as I explained before, "true or anything else", gives true but die() is not executed because of the short-circuit operator.
You should be using file_exists instead of using the # as the later covers all sorts of issues. A better solution would be...
if (file_exists("ssssss.php")) {
$file= #fopen("ssssss.php", r);
}
and
if (file_exists("ssssss.php")) {
include("ssssss.php");
}
That's not really a good use of include. If you need to include a php file and generate an error on failure, use require or require_once.
If you need to get the contents of the whole file, you could use file_get_contents().
Also, I agree with Nigel Ren about the use of # - it is a dangerous practice and should be avoided.

Need help understanding a sample PHP while

everyone. I saw a PHP while loop example today that I don't quite understand.
Example (Complete code)
// Open XML file
$fp=fopen("note.xml","r");
// Read data
while ($data=fread($fp,4096)) { // Line about which I have questions
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
The expression $data=fread($fp,4096) inside the while loop parentheses doesn't seem to change at all. It is just ONE assignment statement. How does this loop end?
The function xml_parse($parser,$data,feof($fp)) may end when parsing is complete, but I don't see how it will affect the test condition for the while loop. I feel the parsing of the XML file would repeat indefinitely.
Also when there is assignment expression as a test condition for a loop, are we really just looking to see if the RIGHT side of the assignment yields TRUE or FALSE to determine whether to end the loop? I have doubt about this though because then it would produce an infinite loop for this example since $data, once assigned, will always return TRUE.
Thanks
It ends when the fread() function returns false, which does when it reaches the end of the file. You can confirm this in the PHP documentation for fread:
http://php.net/fread
As for your question about the evaluation of the assignment, in PHP when you evaluate an assignment it will return the final value of the variable (different to Javascript for instance, in which the assignment is indeed what becomes evaluated), so you're basically both assigning a value to a variable from a function and evaluating the result of that function (assigned to the variable) without any extra syntax.
Work
while(there is data to read) OR (!EOF)
break when reach (EOF==true) OR no data to read OR return false
* EOF (end of file)
As php manual says, the function fread returns the read string or FALSE on failure.
That means:
$data=fread($fp,4096)
In the above statement the value of $data is either the contents of your file note.xml or false.
As you may know, while loop will continue until the condition is false. This statement is false only when fread($fp,4096) function fails to read data from the file, when there is no data left to read.

PHP stristr versus stripos

I was looking into trying to revise some old code in an application that I work on. Currently the app parses out portions of a response string received from an API to determine if a request is good or if it failed. The response from the API sends back a string that contains the characters "DP" if the request was processed successfully. Right now there's a line of code in the app that is as follows:
if(stripos($result, "DP") !== false)
This is working fine now, but I can foresee an issue coming from this. stripos can return a "falsey" value even when the needle is in fact found within the haystack. Since the haystack string is zero-indexed with stripos the function will return 0 if the characters "DP" are found at the very beginning of the haystack string, which will incorrectly be read as false. This code is working now, but if for any reason the developers who maintain the API we work with decide to reformat their response, we will have problems. I was thinking of changing this to the following:
if(stristr($result, "DP") !== false)
From what I can tell this should be OK because according to php.net stristr only returns false if the needle is not found in haystack. I'm curious though if anybody has seen any problems similar to the one described above occurring with the stristr function.
0 doesn't equal false if you use === (or !==).
See this fiddle for proof: http://phpfiddle.org/main/code/nih-esg
More info on the PHP site here: http://www.php.net/manual/en/language.operators.comparison.php
Since your using !== it is a non issue, since the tripple operators checks both value and type
false != 0 : false
false !== 0 : true
<?php
$result="DP";
if (stripos($result, "DP") !== false)
{
echo stripos($result, "DP");
}
?>
Returns 0 from within brackets.

PHP - is_readable() returns incorrect value

I'm using script like this:
$path = dirname(__FILE__)."/folder/file.ext"
if(is_readable($path)){
$file = fread(fopen($path,"r"), filesize($path));
}else{
//do something else if file can't be opened
}
And surprisingly it generates the following error:
Warning: fread() [function.fread]: Length parameter must be greater than 0
in /nfs/c10/h02/mnt/161920/domains/example.com/html/my-folder/file.php on line 16
I'm wondering why this happens. It happens only on some servers and on others it's fine. What are requirements to use fread successfully? File exists in that location.
As everyone has said, filesize is probably 0.
Either use file_get_contents as suggested, or if you absolutely want/need to use fread(), you could get around it with the following on php 5.3+:
$path = dirname(__FILE__)."/folder/file.ext"
if(is_readable($path)){
$file = fread(fopen($path,"r"), filesize($path) ?: 1);
}else{
//do something else if file can't be opened
}
Notice the ?: 1? It's called a ternary operator. That says, use filesize if it evaluates to true (i.e. it's bigger than 0) or use 1.
Definitely not best practice but fun to point out.
If the file is empty, it can be read. But you cannot read 0 bytes with fread.
Empty file == filesize of 0.
For your usecase you could also use PHP's file_get_contents function.

How can i test if a file write has succeeded in PHP?

Is there any way to test if writing to a file was successfully accomplished? I need a method to obtain the end of time of a writing operation. If so to trigger a callback function.
fwrite() returns the number of bytes written, or FALSE on error.
Check whether fwrite() returns false and you'll know that the write succeeded. Be careful to use the === comparison operator instead of the == operator when checking if the returned value is false.
You can use filemtime() to get the last modification time of a file.

Categories