Aan Aan -4 years ago 90
PHP Question

fgets() doesn't read the full line

I have a file which has the following long single line random string:

fuzzero^G5%eLz@5?0jzlqCA};iBdi>hSa0Uc"DS{m*JVMPMN),)dBnbwGNKYE#uP$3@WGyV#kjC&(2yW1l`DJ,`3Mz#5gbU}eAUU)uB7N><A"qa;M{y9{mdKW"P?4o`jZI<M?tTElL<f?3aC1JM0&ZKGTewYDk;g$`#UhAcD05S>8#tap'aaUVQr`14rl0I3`oY6Z`JZ'fR3:{em"owN{0"(1}en}Wr*,3>Z<AC(Q8?M64(0siNrjGdkEsIB2)n2?e@%PiRjqH&xLSx<|,j8Fxt{Z|z@YW%P|JyE@3Y6KID9f`25)ldtSGrvw@b9C'YrDa&jeIpY5#(lR`qFaE)#,ecv'oFwihYWsI"G5ija,5wQ'Wa4f}*ec{K6n3DGlfgNXa8#tr>sxo}s,7xe4jsgh?nF"!,e"g#Qq|xTgp0ON{;M5s!aL6r$}On>sm5lD(?$XoB<NBGezC!F%EQuL;cIJzz?WFcds2;3rx;<)C6m<*#Xqw6|riy|S(@ts<HU'CYl)Teordizuzfeid


I wrote php code to read this line:

$myfile = fopen($path, "r") or die("Unable to open file!");
$txt=fgets($myfile);
echo $txt;

fclose($myfile);


the output is part of the random string:

fuzzero^G5%eLz@5?0jzlqCA};iBdi>hSa0Uc"DS{m*JVMPMN),)dBnbwGNKYE#uP$3@WGyV#kjC&(2yW1l`DJ,`3Mz#5gbU}eAUU)uB7N>8#tap'aaUVQr`14rl0I3`oY6Z`JZ'fR3:{em"owN{0"(1}en}Wr*,3>Zsxo}s,7xe4jsgh?nF"!,e"g#Qq|xTgp0ON{;M5s!aL6r$}On>sm5lD(?$XoB


How can I read and show the complete string?

Answer Source

The posted code works fine. It reads 527 bytes from the file.

If you run this PHP script in the browser, the part that you think it misses (<A"qa;M{y9{mdKW"P?4ojZI<M?tTElL<f?3aC1JM0&ZKGTewYDk;g$#UhAcD‌​05S>) looks like an HTML element and it is not displayed by the browser.

Check the Page Source (find in in the menu or in the Developer Tools) to see the exact output produced by the script.

Or, even better, use the PHP header() function to tell the browser the content generated by the script is text, not HTML:

header('Content-Type: text/plain');
$myfile = fopen($path, "r") or die("Unable to open file!");
$txt=fgets($myfile);
echo $txt;

fclose($myfile);

If you want to read the entire content of the file in a single shot then PHP provides the function file_get_contents() specifically for this purpose:

header('Content-Type: text/plain');
$txt = file_get_contents($path);
echo($txt);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download