Check data before fwrite - php

I have simple script to get data from another server, run every 1 minutes.
<?php
$html = file_get_contents('http://google.com/data.php');
$myfile = fopen("data.html", "w") or die("Unable to open file!");
fwrite($myfile, $html);
fclose($myfile);
?>
But sometime, script write blank data to data.html. I think because connection problem between my server and remote server, or target file just blank sometime.
I wonder if i check data after get, if received data not blank then write, if data blank then exit. Please help me how to do. Thank!

file_get_contents returns false on error, so you can directly check it using === or !== as
<?php
$html = file_get_contents('http://google.com/data.php');
if($html !== false){
$myfile = fopen("data.html", "w") or die("Unable to open file!");
fwrite($myfile, $html);
fclose($myfile);
}
?>
if you want to merely test whether the output is empty, you can use for example the comparison $html !== false && $html !== ''

Related

creating a custom redirecting page

I want to make a page like
www.example.com/redirect.php
above page must redirect to another page like
www.google.com
But whenever I open www.example.com/redirect.php?changeurl=www.yahoo.com
from now onwards www.example.com/redirect.php
page should start redirecting to yahoo.com
if changeurl=youtube.com
from now onwards
the page www.example.com/redirect.php must star redirecting to youtube.com
How can I do that without using SQL database, only by using a single file "redirect.php"
Please ask if you need more information about this question
First off you should at least have some code already written.
But try using this:
redirect.php:
<?php
if(!file_exists("redirect_url.txt")) {
$createfile= fopen("redirect_url.txt", "w") or die("Unable to open file!");
$txt = "https://www.google.com";
fwrite($createfile, $txt);
fclose($createfile);
}
if(isset($_GET['changeurl'])) {
$editfile= fopen("redirect_url.txt", "w") or die("Unable to open file!");
$txt = $_GET['changeurl'];
fwrite($editfile, $txt);
fclose($editfile);
header("Location: " . $_GET['changeurl']);
} else {
$myfile = fopen("redirect_url.txt", "r") or die("Unable to open file!");
$url = fgets($myfile);
fclose($myfile);
header("Location: " . $url);
}
?>
Also make sure in the ?changeurl You always use http:// or https://, Since you are not using a database you can use a .txt file.

PHP - Cant save string variable to text file, gets corrupted

New to PHP and im reading a textfile into a string variable, removing double quotes and writing the contents back to a textfile. The problem is that the textfile, after saving, just consists of junk like this:
^#2^#0^#1^#0^#-^#1^#1^#-^#2^#0^#
^#1^#3^#:^#5^#5^#,^#^#H^#K^#L^#M^#\^#S^#o^#f...
I am obviously doing something very wrong here..
Here is the code:
function replacequotes("myCommaSeparatedFile.csv")
{
$rfile = fopen($filename, "r") or die("Unable to open file!");
$outputfile = fopen("test2.csv", "w") or die("Unable to open file!");
$readtext = fread($rfile, filesize($filename));
$textoutput = str_replace('"', '', $readtext);
echo $textoutput; // <- this shows ok on screen
fwrite($outputfile, $textoutput);
fclose($inpufile);
fclose($outputfile);
}
Can someone help me out please, thanks.
Problem solved. dos2unix was a useful command. Thanks again Ali for the code cleaning!

How can I make the PHP write to the file automaticly?

I want to save a web page to a text file automatically or at least every second. So I wrote a PHP file like that :
<?php
$homepage = file_get_contents('www.example.com');
echo $homepage;
$myfile = fopen("file.txt", "w") or die("Unable to open file!");
while(true) {
fwrite($myfile, $homepage);
}
fclose($myfile);
?>
But it did not work
The file will not be written until the while loop will stop.
Can someone help me with that ? I need the PHP to run all the time or at least for a few minute. How can I do that ?
I'd go for something like this (not tested though)
<?php
header("Refresh:30"); // The page will be refreshed every 30 seconds
// To avoid max_execution_time errors
$myfile = "file.txt";
for ($i=0; $i < 30; $i++) {
$homepage = file_get_contents("http://www.example.com");
echo $homepage;
file_put_contents($myfile, $homepage);
sleep(1); // Do it every second
}
If a second is too much time, you could use usleep instead
That's because you don't close the file in the loop. And you should add some delay too. Change it to this:
<?php
$homepage = file_get_contents('www.example.com');
echo $homepage;
while(true) {
$myfile = fopen("file.txt", "w") or die("Unable to open file!");
fwrite($myfile, $homepage);
fclose($myfile);
sleep(1);
}
?>
Note that if you're running this on a webserver, it will exceed the time limit.
First off, maybe you should consider using sleep inside your loop to minimise performance impact. After every write you should invoke flush to persist data onto disk. There is also a risk of overloading target site in a form of DOS attack, so you should be mindful of the consequences.
This is not tested but should word... But honestly your better of using Ajax with a timer to do this.
header("Refresh:60");
function writeToPage($page,$file){
$content = file_get_contents($page);
file_put_contents($file,$content);
}
$page = "www.example.com";
$file = "file.txt";
$write = true;
while( $write === true ) {
sleep(5);
writeToPage($page,$file);
}

Trying to build a file in PHP and use fwrite to file

trying to figure out how i can make a and save a file while including default info from another file. i tried include but it did not work. any suggestion on how to build this file?
<?php
$wrtID = $_POST["fileID"];
SQL statement here to get relevant info
mkdir("CNC/$wrtID", 0770, true);
?>
<?php
$batfile = fopen("CNC/$wrtID/$wrtID.bat", "w") or die("Unable to open file!");
$txt = "
#ECHO OFF
#ECHO **** Run NC-Generator WOODWOP 4.0 ****
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-sl.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-sr.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-tb.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-dc.mpr
#ECHO **** Done ****
";
fwrite($batfile, $txt);
fclose($batfile);
?>
<?php
$slfile = fopen("CNC/$wrtID/$wrtID-sl.mpr", "w") or die("Unable to open file!");
$txt = "
include("defaultcnc.php");
if ( additional file pats needed ) {
include("component-1.php");
}
";
fwrite($slfile, $txt);
fclose($slfile);
?>
I don't see a problem in the first block of code.
On the second block, the interpreter will consider the second double quotes to mean the end of the string $txt = " include(". So everything after that would produce a PHP error.
But even if you escape those the mpr file will have the string include("defaultcnc,php"); but not the actual contents of that file. For that you should do file_get_contents("defaultcnc.php").
something like:
<?php
$slfile = fopen("CNC/$wrtID/$wrtID-sl.mpr", "w") or die("Unable to open file!");
// set params to pass to defaultcnc.php
$value1 = 1;
$value2 = "I'm a text string";
$file = urlencode("defaultcnc.php?key1=".$value1."&key2=".$value2);
$txt = file_get_contents($file);
if ( additional file pats needed ) {
$txt .= file_get_contents("component-1.php");
}
fwrite($slfile, $txt);
fclose($slfile);
?>
I assume additional file pats needed means something to you. It should be a condition evaluating either true or false.

Using php, how to insert text without overwriting to the beginning of a text file

I have:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
but it overwrites the beginning of the file. How do I make it insert?
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?
To insert text without over-writing the beginning of the file, you'll have to open it for appending (a+ rather than r+)
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
If you're trying to write to the start of the file, you'll have to read in the file contents (see file_get_contents) first, then write your new string followed by file contents to the output file.
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
The above approach will work with small files, but you may run into memory limits trying to read a large file in using file_get_conents. In this case, consider using rewind($file), which sets the file position indicator for handle to the beginning of the file stream.
Note when using rewind(), not to open the file with the a (or a+) options, as:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
A working example for inserting in the middle of a file stream without overwriting, and without having to load the whole thing into a variable/memory:
function finsert($handle, $string, $bufferSize = 16384) {
$insertionPoint = ftell($handle);
// Create a temp file to stream into
$tempPath = tempnam(sys_get_temp_dir(), "file-chainer");
$lastPartHandle = fopen($tempPath, "w+");
// Read in everything from the insertion point and forward
while (!feof($handle)) {
fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);
}
// Rewind to the insertion point
fseek($handle, $insertionPoint);
// Rewind the temporary stream
rewind($lastPartHandle);
// Write back everything starting with the string to insert
fwrite($handle, $string);
while (!feof($lastPartHandle)) {
fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);
}
// Close the last part handle and delete it
fclose($lastPartHandle);
unlink($tempPath);
// Re-set pointer
fseek($handle, $insertionPoint + strlen($string));
}
$handle = fopen("file.txt", "w+");
fwrite($handle, "foobar");
rewind($handle);
finsert($handle, "baz");
// File stream is now: bazfoobar
Composer lib for it can be found here
You get the same opening the file for appending
<?php
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
If you want to put your text at the beginning of the file, you'd have to read the file contents first like:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
$existingText = file_get_contents($file);
fwrite($file, $existingText . $_POST["lastname"]."\n");
}
fclose($file);
?>

Categories