PHP Script That Creates File Suddenly Stops Working - php

I made a script to create a file, it was working fine until i think my host changed the script when I asked them what was wrong with it (I fixed it after but now its not working)
Here is the script:
$rand = substr(md5(microtime()),rand(0,26),5);
$seed = str_split('abcdefghijklmnopqrstuvwxyz'
.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.'0123456789!##$%^&*()' . 'ǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏ01D0ǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟ01E0ǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯ01F0ǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿ
0200ȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏ0210ȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟ0220ȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯ0230ȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿ0240ɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏ0250ɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟ0260ɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯ0270ɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿ0280ʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏ0290ʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟ02A0ʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯ02B0ʰʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿ02C0ˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏ02D0ːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟02E0ˠˡˢˣˤ˥˦˧˨˩˪˫ˬ˭ˮ˯02F0˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾˿0300̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏0310̛̖̗̘̙̜̝̞̟̐̑̒̓̔̕̚0320̡̢̧̨̠̣̤̥̦̩̪̫̬̭̮̯0330̴̵̶̷̸̰̱̲̳̹̺̻̼̽̾̿0340͇͈͉͍͎̀́͂̓̈́͆͊͋͌ͅ͏0350͓͔͕͖͙͚͐͑͒͗͛͘͜͟͝͞0360ͣͤͥͦͧͨͩͪͫͬͭͮͯ͢͠͡0370ͰͱͲͳʹ͵Ͷͷ͸͹ͺͻͼͽ;Ϳ0380΀΁΂΃΄΅Ά·ΈΉΊ΋Ό΍ΎΏ0390ΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟ03A0ΠΡ΢ΣΤΥΦΧΨΩΪΫάέήί03B0ΰαβγδεζηθικλμνξο03C0πρςστυφχψωϊϋόύώϏ03D0ϐϑϒϓϔϕϖϗϘϙϚϛϜϝϞϟ03E0ϠϡϢϣϤϥϦϧϨϩϪϫϬϭϮϯ03F0ϰϱϲϳϴϵ϶ϷϸϹϺϻϼϽϾϿ
'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 50) as $k) $rand .= $seed[$k];
$current = "";
fputs($rand, "[Server]: Welcome To Your New Chat Server");
echo $rand;
Its meant to create a random file and show the user the name of that file
I always get an error:
ec-2017 08:52:43 UTC] PHP Warning: fputs() expects parameter 1 to be
resource, string given in /public_html/rechat/nokeep.php

fputs is expecting a resource ( as the error points out) this should be the handle from fopen()...
$fh = fopen($rand, 'w');
fputs($fh, "[Server]: Welcome To Your New Chat Server");
fclose($fh);
You could alternatively use file_put_contents() which would do this all in one step...
file_put_contents($rand, "[Server]: Welcome To Your New Chat Server");

Related

Shared access: How to fix "fread(): Length parameter must be greater than 0"?

When I run this function on multiple scripts one script generated warning:
fread(): Length parameter must be greater than 0
function test($n){
echo "<h4>$n at ".time()."</h4>";
for ($i = 0; $i<50; $i++ ){
$fp = fopen("$n.txt", "r");
$s = fread($fp, filesize("$n.txt") );
fclose($fp);
$fp = fopen("$n.txt", "w");
$s = $_SERVER['HTTP_USER_AGENT'].' '.time();
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
fwrite($fp, $s);
// fflush($fp);// flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
}
}
I try to write reading of the file for multiple users, but only one user can write the file. I know that when I use fwrite with flock - LOC_EX, next scripts must wait till the write is finished. But here it seems like filesize doesn't wait till the write operation is finished. My opinion is that it tries to reach the file when the file size is 0, and as a result this produces the problem: 0 bytes will be read from the file, when it is written by original script.
Is it possible to fix this for fread function?
Purpose of this script is to test fread with some limit and to check the data which I read later, if the data are really written when I did not used fflush.
function test($n){
echo "<h4>$n at ".time()."</h4>";
for ($i = 0; $i<50; $i++ ){
$start = microtime(true);
$fp = fopen("$n.txt", "r");
if(filesize($n.txt) > 0)
{
$s = fread($fp, filesize($n.txt) );
fclose($fp);
$fp = fopen("$n.txt", "w");
$s = $_SERVER['HTTP_USER_AGENT'].' '.time();
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
fwrite($fp, $s);
// fflush($fp);// flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
}
else
{
echo "Filesize must be greater than 0";
}
}
}
please change $s variables name its use same things two time
$fp = fopen("$n.txt", "r");
$s = fread($fp, filesize("$n.txt") );
fclose($fp);
The error occurs in the middle line of the above three lines.
Firstly, these three lines could be rewritten into a single line as follows:
$s = file_get_contents("$n.txt");
However, these isn't necessary, as these three lines are entirely redundant in your code. They don't do anything useful.
What they do is open a file, store its contents to $s and then close it.
But you are then immediately setting $s to a different value, thus throwing away the previous value, and making it pointless to have read it from the file in the first place.
If you need to keep the original contents of the file, then use file_get_contents() and make sure you don't overwrite the contents of the variable.
If you don't need the original contents of the file, then just delete those three lines from your code.
Incidentally, this error highlights a couple of good coding practices that you should take on board: Firstly, never re-use a variable for two different things, and secondly always give your variables (and functions) good names. $s is not a good name; $previousFileContents would be a better name; it would have made the error much more obvious.

how can i fill an array from a text file using a delimitor?

I am writing a program in php to check ip's , now I know that are easier ways to do so, but i want to do it my way. This is what i have written so far
<?php
if($_POST) {
$file=fopen("names.txt","a") or exit("Unable to open file!");
$ipadres=fopen("ip.txt","a") or exit("Unable to open file!");
$name = $_POST['username'];
$file_content = $name. "|";
$ipadres_content = $_SERVER["REMOTE_ADDR"] . "|";
$iparray = array();
$i=0;
fputs($file,$file_content);
fputs($ipadres,$ipadres_content);
while(!feof($ipadres))
{
$iparray = explode("|", fgets($file));
}
fclose($file);
fclose($ipadres);
}
?>
As you can see i tried using a while loop to put the ip-adresses in to an array to check. but when I try to run it it just keeps running until it finally crashes in to this error= Fatal error: Maximum execution time of 30 seconds exceeded.Oh and yes i tried to put the max crash limit up a bit but still no sign of succes.
Your while loop is faulty:
while(!feof($ipadres))
{
$iparray = explode("|", fgets($file));
}
You're checking for feof($ipadres) and using fgets($file)
i.e. you keep checking end of file with file pointer $ipadres but reading from file pointer $file which will cause infinite loop and program will crash eventually.
Probably you meant:
while(!feof($ipadres)) {
$iparray = explode("|", fgets($ipadres));
}
OR else use file function which returns all the lines of a file in an array.

PHP - Export CSV to FTP rather than download in browser

I have been trying for a few hours now to no avail. I have successfully output my CSV as a download in the browser using:
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
However I want that output to now go to an FTP server instead, I have got the connection and temp file part sorted but cannot seem to edit the file to output my results.
// create empty variable to be filled with export data
$csv_export = '';
for($i = 0; $i < $field; $i++) {
$csv_export.= mysql_field_name($query,$i).',';
}
// newline (seems to work both on Linux & Windows servers)
$csv_export.= '
';
// loop through database query and fill export variable
while($row = mysql_fetch_array($query)) {
// create line with field values
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysql_field_name($query,$i)].'",';
}
$csv_export.= '
';
}
Above is the part that gets the query data and puts it into the CSV, I have tried incorporating both fputs and fputcsv in the loops to write the rows to the file.
//Upload the temporary file to server
ftp_fput($ftpstream, '/httpdocs/.../abandoned.csv', $temp, FTP_ASCII);
$fp = fopen('var/www/vhosts/.../abandoned.csv', 'w');
fputs($fp, '$csv_export');
fclose($fp);
echo($csv_export);
So, echoing the output works absolutely fine - all I want is that echo'd data written into a CSV file and uploaded to the FTP.
The error I've been given is:
Array ( [type] => 2 [message] => fclose() expects parameter 1 to be resource,
boolean given
So the fp is causing the problem... is it at the open stage or at the writing of csv_export?
Thanks in advance.
Try this
//Write the contents to the temp file
fputs($temp, $csv_export);
//upload the temp file
ftp_fput($ftpstream, '/httpdocs/.../abandoned.csv', $temp, FTP_ASCII);
//close the temp file
fclose($temp);
Your current code is creating an empty file, uploading it, and then creating a separate file. Even if you get it working on a local server, it is an unnecessary step.
Try this, not tested:
$filename = 'abandoned.csv';
$content = $csv_export;
$host = 'yourhost';
$user = 'youruser';
$password = 'yourpass';
//open connection to your ftp server
$stream = stream_context_create(array('ftp' => array('overwrite' => true)));
//authenticate to your ftp server, normal uri syntax
$uri = sprintf('ftp://%s:%s#%s/%s', $user, $password, $host, $filename);
file_put_contents($uri, $content, 0, $stream);
In phpinfo(); you can look for Registered PHP Streams and just use this in most of any cases:
file_put_contents('ftp://user:password#server/your/directory/file.csv', $csvData);
ftp_fput is a right way here.
But you have to prepare FTP connection and authenticate first. Assuming you have $csv_export string in memory:
// connect
$ftp_conn = ftp_connect('ftp.yourserver.net');
// authenticate
$login_result = ftp_login($conn_id, 'ftp_username', 'password');
// prepare output stream
$stream = fopen('data://text/plain,' . $csv_export, 'r');
// try to upload
if (ftp_fput($ftp_conn, '/httpdocs/.../abandoned.csv', $stream, FTP_ASCII)) {
echo "Successfully uploaded\n";
} else {
echo "There was a problem while uploading\n";
}
// close the connection and the file handler
ftp_close($ftp_conn);
fclose($stream);
You're receiving that error because fopen is returning false, which indicates that it was unable to open the file.
If I'm understanding your code, you're uploading abandoned.csv (which presumably exists) to the ftp after opening it in $temp. Is $temp pointing at your local copy of abandon.csv? Because if so, you should close the file stream pointing to it before opening a second one with fopen.
If that's not the issue, then abandoned.csv may not actually exist, in which case you may just be trying to fopen a missing file.

Handle errors file_get_contents

I'm writing an application that uses a .php script to get tweets using the twitter search API.
See below code:
<?php
$hashtag = 'hashtag'; // We search Twitter for the hashtag
$show = 25; // And we want to get 25 tweets
// Local path
$cacheFile = '../../_data/tweets.json.cache'; // A cachefile will be placed in _data/
$json = file_get_contents("http://search.twitter.com/search.json?result_type=recent&rpp=$show&q=%23" . $hashtag. "%20-RT") or die("Could not get tweets");
$fp = fopen($cacheFile, 'w');
fwrite($fp, $json);
fclose($fp);
?>
My problem is that I want to make sure that this script runs without fail, or if it does fail at least doesn't keep looping.
The script is going to be run automatically every 1 minute.
Would anyone know a good way to handle errors here?
TL;DR: How do I handle errors on my code?
in simple, use '#' prefix for function. It suppresses errors from displaying. Read More Here
<?php
$hashtag = 'hashtag'; // We search Twitter for the hashtag
$show = 25; // And we want to get 25 tweets
$cacheFile = '../../_data/tweets.json.cache'; // A cachefile will be placed in _data/
$json = #file_get_contents("http://search.twitter.com/search.json?result_type=recent&rpp=$show&q=%23" . $hashtag . "%20-RT");
if (!empty($json)) {
$fp = fopen($cacheFile, 'w');
fwrite($fp, $json);
fclose($fp);
} else {
echo "Could not get tweets";
exit;
}
?>

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.

Categories