fwrite problem

 
Post new topic   Reply to topic    Aprelium Forum Index -> PHP
View previous topic :: View next topic  
Author Message
reefbum
-


Joined: 25 May 2007
Posts: 9
Location: FL

PostPosted: Sun Jan 04, 2009 10:16 pm    Post subject: fwrite problem Reply with quote

X2 - WinXP SP3 - PHP5.2.2

I have a php script that I have scheduled to run every hour. This script is used to clean up entries in mysql database. After cleanup is completed it is supposed to then make a backup of the database and save the .sql file into the 'backup' folder on web server.

All steps are working correctly except the database backup. I get this error when running the php script.

WARNING:
fwrite<>: supplied argument is not a valid stream resource in C:\www\htdocs\classes\backup_class.php on line 57

Line 57 is were the php script (db_cron.php) is supposed to save the database backup.sql file to the web server folder 'backups'

I have done quite a few Google searches and everything I can come up with says this error is caused by having the wrong permission settings on the backup folder but I cannot solve this issue.

I can run the exact same script on my Linux box and it works 100%.

Be grateful for any help.
Back to top View user's profile Send private message Yahoo Messenger MSN Messenger
roganty
-


Joined: 08 Jun 2004
Posts: 357
Location: Bristol, UK

PostPosted: Mon Jan 05, 2009 12:00 pm    Post subject: Reply with quote

reefbum

How about posting the code on line 57 so that we can help you

It would also help if you posted the variables for fwrite() and the line where you opened the file with fopen()

Thank you
_________________
Anthony R

Roganty
| Links-Links.co.uk
Back to top View user's profile Send private message Visit poster's website
reefbum
-


Joined: 25 May 2007
Posts: 9
Location: FL

PostPosted: Mon Jan 05, 2009 2:43 pm    Post subject: Reply with quote

Sorry about that, here is the full code for backup_class.php



Code:


<?
class backup{

// Var Declarations

   var $filename;   // File name for backup or restore
   var $linecount;   // Total lines in the .sql file
   var $tablelist;   // Array of DB tables
   var $date;      // Date of backup
   var $time;      // Time of backup
   var $dbname;   // Database Name
   var $string;   // String for containing sql
   var $filecount;   // Total Backup files
   var $filelist;   // Array of Backup Files   

// FUNCTION DECLARATIONS

function create() {
   $this->time=date("His");
   $this->date=date("Ymd");
   $this->linecount=0;
   $this->filename=$this->serverpath.'backups/'.$this->date.'-'.$this->time.'.sql';
   $file = fopen($this->filename,"w");

   $this->tablelist = mysql_list_tables($this->dbname);
   $this->string = NULL;
       while ($table = sql::getarray($this->tablelist)) {   
          $tablename = $table[0];
      $this->string = "DELETE FROM $tablename;\n";
      $tablequery = sql::query("SELECT * FROM `$tablename`");
            $numfields = mysql_num_fields($tablequery);
            while ($fetchrow = sql::getarray($tablequery)) {
             $this->string .= "INSERT INTO $tablename VALUES(";
              $first = TRUE;
              for ($fieldcount=1; $fieldcount<=$numfields; $fieldcount++){
                if (TRUE == $first) {
                     $this->string .= "'".mysql_real_escape_string($fetchrow[($fieldcount - 1)])."'";
                     $first = FALSE;           
                   } else {
                     $this->string .= ", '".mysql_real_escape_string($fetchrow[($fieldcount - 1)])."'";
                   }
              }
              $this->string .= ");\n";
              if ($this->string != ""){
                   $this->linecount++;       
            fwrite($file, $this->string);

                 }
              $this->string = NULL;
               }   
          }

   fclose($file);
     }
 
function load(){
 
     $file = fopen($this->filename,"r");
       $this->linecount = 0;
       while (!feof($file)) {
            $query = '';
            $query = fgets($file);
      if($query!=''){
               sql::query($query) or die("sql not successful: ".mysql_error()." query: ".$query);
         }
          } 
     }

function flist(){

   $this->filecount=0;
   $dir = opendir('backups/');
   while (($file = readdir($dir)) !== false) {
      if($file!='.' && $file!='..'){
         $this->filecount++;
         $this->filelist[$this->filecount]=$file;
         }
      }
   if($this->filecount>0){
      rsort($this->filelist);
      }
    }

function delete(){
   unlink($this->filename);
       }

function savesettings(){

   $sqld="UPDATE config SET `autobackup`='$this->autobackup', `lastbackup`='0', `backupunit`='$this->backupunit', `backuptime`='$this->backuptime' WHERE 1";
   $resultd = @sql::query($sqld) or die("couldn't execute query  $sql.".mysql_error());

   $this->error_message='Backup Settings Saved';

       }

function loadsettings(){

   $sqld="SELECT * FROM config";
   $resultd = @sql::query($sqld) or die("couldn't execute query  $sql.".mysql_error());
   while($rowd = sql::getarray($resultd)) {
      $this->autobackup=$rowd['autobackup'];
      $this->backupunit=$rowd['backupunit'];
      $this->backuptime=$rowd['backuptime'];
      }

   if($this->autobackup=='on'){
      $this->autobackuponchecked='checked';
      } else {
      $this->autobackupoffchecked='checked';
      }

   if($this->emailbackup=='on'){
      $this->emailbackuponchecked='checked';
      } else {
      $this->emailbackupoffchecked='checked';
      }

       }

function savecleansettings(){

   $sqld="UPDATE config SET `autocleanup`='$this->autocleanup', `lastcleanup`='0', `cleanupunit`='$this->cleanupunit', `cleanuptime`='$this->cleanuptime', `cleanupwunit`='$this->cleanupwunit', `cleanupwtime`='$this->cleanupwtime' WHERE 1";
   $resultd = @sql::query($sqld) or die("couldn't execute query  $sql.".mysql_error());

   $this->error_message='Database Cleanup Saved';

       }

function loadcleansettings(){

   $sqld="SELECT * FROM config";
   $resultd = @sql::query($sqld) or die("couldn't execute query  $sql.".mysql_error());
   while($rowd = sql::getarray($resultd)) {
      $this->autocleanup=$rowd['autocleanup'];
      $this->cleanupunit=$rowd['cleanupunit'];
      $this->cleanuptime=$rowd['cleanuptime'];
      $this->cleanupwunit=$rowd['cleanupwunit'];
      $this->cleanupwtime=$rowd['cleanupwtime'];
      }

   if($this->autocleanup=='on'){
      $this->autocleanuponchecked='checked';
      } else {
      $this->autocleanupoffchecked='checked';
      }
       }

function saveradsettings(){

   $sqld="UPDATE config SET `autocleanrad`='$this->autorad', `lastrad`='0', `radunit`='$this->radunit', `radtime`='$this->radtime' WHERE 1";
   $resultd = @sql::query($sqld) or die("couldn't execute query  $sql.".mysql_error());

   $this->error_message='RAD ACCT Cleanup Saved';

       }

function loadradsettings(){

   $sqld="SELECT * FROM config";
   $resultd = @sql::query($sqld) or die("couldn't execute query  $sql.".mysql_error());
   while($rowd = sql::getarray($resultd)) {
      $this->autocleanrad=$rowd['autocleanrad'];
      $this->radunit=$rowd['radunit'];
      $this->radtime=$rowd['radtime'];
      }

   if($this->autocleanrad=='on'){
      $this->autoradonchecked='checked';
      } else {
      $this->autoradoffchecked='checked';
      }
       }
}

Back to top View user's profile Send private message Yahoo Messenger MSN Messenger
reefbum
-


Joined: 25 May 2007
Posts: 9
Location: FL

PostPosted: Mon Jan 05, 2009 2:58 pm    Post subject: Reply with quote

And here is the code that is run each hour from the scheduler.

Code:


<?
// CONNECT PATH

include "connectpath.php";

// Display All Errors

 ini_set('display_errors', 1);
 ini_set('log_errors', 1);
 ini_set('error_log', dirname(__FILE__) . 'error_log.txt');
 error_reporting(E_ALL & ~E_NOTICE);


// SQL CONNECTION

include "classes/sql_class.php";

$sql = new sql();
include "$connectpath";
$sql->connect();

include "classes/backup_class.php";
include "classes/settings_class.php";

$backup = new backup();

$backup->dbname=$sql_db;
$backup->serverpath=$php_dir;

$settings = new settings();

// Reseed security table

if(date("i")==0){
   $settings->reseed_security();
   }

// Get current time for comparison

$time=time();

// Set Results tag to default msg for cron logs

$results="DB Cron Run.\n";

// Check for autobackup / autocleanup enabled

$sqld="SELECT * FROM config";
$resultd = @sql::query($sqld) or die("couldn't execute query  $sql.".mysql_error());
$rowd = sql::getarray($resultd);

$autobackup = $rowd['autobackup']; // Is auto backup on
$lastbackup = $rowd['lastbackup']; // Timestamp for last autobackup run
$backupunit = $rowd['backupunit']; // Unit of time for backup period
$backuptime = $rowd['backuptime']; // Length time for backup period
$emailbackup = $rowd['emailbackup']; // Email Backup files On / Off
$emailbackupemail = $rowd['emailbackupemail']; // Email Backup Email Address

$autocleanup = $rowd['autocleanup']; // Is Auto Cleanup on
$lastcleanup = $rowd['lastcleanup']; // Timestamp for last autocleanup run
$cleanupunit = $rowd['cleanupunit']; // Unit of time for how old to archive users
$cleanuptime = $rowd['cleanuptime']; // Length time for how old to archive users
$cleanupwunit = $rowd['cleanupwunit']; // Unit of time for how often to archive users
$cleanupwtime = $rowd['cleanupwtime']; // Length time for how often to archive users

$autocleanrad = $rowd['autocleanrad']; // Is Auto RAD ACCT Cleanup on
$lastrad = $rowd['lastrad']; // Timestamp for last autoradcleanup run
$radunit = $rowd['radunit']; // Unit of time for how old to archive rad acct
$radtime = $rowd['radtime']; // Length time for how old to archive rad acct


if($autobackup=='on'){

   if($backupunit=='Years'){ $span = 365 * 24 * 3600; } // Generate length of a year
   if($backupunit=='Months'){ $span = 30 * 24 * 3600; } // Generate length of a month
   if($backupunit=='Weeks'){ $span = 7 * 24 * 3600; } // Generate length of a week
   if($backupunit=='Days'){ $span = 24 * 3600; } // Generate length of a day
   if($backupunit=='Hours'){ $span = 3600; } // Generate length of a hour

   $timespan=$span*$backuptime; // Figure out total time span

   if($lastbackup==0 || $lastbackup<$time-$timespan){ // If never run or needs to be run

      $backup->iscron="../";
      $backup->create();
      $filename=$backup->filename;
      $results.="Created SQL Backup $filename. \n";
      echo "Got here";

      $sqld="UPDATE config SET `lastbackup`='$time'";
      $resultd = @sql::query($sqld) or die("couldn't execute query  $sql.".mysql_error());

      if($emailbackup=='on') { // If we are supposed to email the sql file

         $to=$emailbackupemail;
         $subject="SQL BACKUP - $backup->date $backup->time";
         $random_hash = md5(date('r', time()));
         $headers = "From: DATABASE@$hostname\r\nReply-To: DONOTREPLY@$hostname";
         $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
            $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

            $message = "SQL BACKUP: ".date("n-j-Y H:i:s");

               $file = fopen($backup->filename,'rb');
             $data = fread($file,filesize($backup->filename));
             fclose($file);
         $data = chunk_split(base64_encode($data));

               $headers = "From: DATABASE@$hostname\r\n" .
                     "Reply-To: DONOTREPLY@$hostname\r\n" .
                    "MIME-Version: 1.0\r\n" .
                     "Content-Type: multipart/mixed;\r\n" .
                     " boundary=\"{$mime_boundary}\"";

               $message = "This is a multi-part message in MIME format.\n\n" .
                     "--{$mime_boundary}\n" .
                     "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
                     "Content-Transfer-Encoding: 7bit\n\n" .
                     $message . "\n\n";

            $message .= "--{$mime_boundary}\n" .
                     "Content-Type: {$type};\n" .
                   " name=\"".date("njY-His").".sql\"\n" .
                     "Content-Disposition: attachment;\n" .
                     " filename=\"{$fileatt_name}\"\n" .
                     "Content-Transfer-Encoding: base64\n\n" .
                     $data . "\n\n" .
                     "--{$mime_boundary}--\n";

               if (@mail($to, $subject, $message, $headers))
            $results.="Emailed SQL File. \n\n";
               else
            $results.="Emailed Attempt Failed \n\n";
         }
      }
   }

if($autocleanup=='on'){

   if($cleanupwunit=='Years'){ $span = 365 * 24 * 3600; } // Generate length of a year
   if($cleanupwunit=='Months'){ $span = 30 * 24 * 3600; } // Generate length of a month
   if($cleanupwunit=='Weeks'){ $span = 7 * 24 * 3600; } // Generate length of a week
   if($cleanupwunit=='Days'){ $span = 24 * 3600; } // Generate length of a day
   if($cleanupwunit=='Hours'){ $span = 3600; } // Generate length of a hour

   $timespan=$span*$cleanupwtime; // Figure out total time span

   if($lastcleanup==0 || $lastcleanup<$time-$timespan){ // If never run or needs to be run

      if($cleanupunit=='Years'){ $span = 365 * 24 * 3600; } // Generate length of a year
      if($cleanupunit=='Months'){ $span = 30 * 24 * 3600; } // Generate length of a month
      if($cleanupunit=='Weeks'){ $span = 7 * 24 * 3600; } // Generate length of a week
      if($cleanupunit=='Days'){ $span = 24 * 3600; } // Generate length of a day
      if($cleanupunit=='Hours'){ $span = 3600; } // Generate length of a hour

      $timespan=$span*$cleanuptime; // Figure out total time span

      $expiration = date("Y-n-j",$time-$timespan);

        $res = sql::query("INSERT INTO archive_users SELECT * FROM users WHERE expiration<'$expiration' && `admin`='1';")
          or die(mysql_error()."INSERT INTO archive_users SELECT * FROM users WHERE expiration<'$expiration' && `admin`='1';");

      $res = sql::query("DELETE FROM users WHERE expiration<'$expiration' && `admin`='1'") or die("DELETE FROM users WHERE expiration<'$expiration' && `admin`='1'");

      $results.="Archived old expired users. \n";

      $sqld="UPDATE config SET `lastcleanup`='$time'";
      $resultd = @sql::query($sqld) or die("couldn't execute query  $sql.".mysql_error());

      }
   }

if($autocleanrad=='on'){

   if($radunit=='Years'){ $span = 365 * 24 * 3600; } // Generate length of a year
   if($radunit=='Months'){ $span = 30 * 24 * 3600; } // Generate length of a month
   if($radunit=='Weeks'){ $span = 7 * 24 * 3600; } // Generate length of a week
   if($radunit=='Days'){ $span = 24 * 3600; } // Generate length of a day
   if($radunit=='Hours'){ $span = 3600; } // Generate length of a hour

   $timespan=$span*$radtime; // Figure out total time span

   $expiration = date("Y-n-j H:i:s",$time-$timespan);

        $res = sql::query("INSERT INTO archive_radacct SELECT * FROM radacct WHERE AcctStopTime<'$expiration' && AcctStopTime>'0000-00-00 00:00:00';")
          or die(mysql_error()."INSERT INTO archive_radacct SELECT * FROM radacct WHERE AcctStopTime<'$expiration && AcctStopTime>'0000-00-00 00:00:00'';");

      $res = sql::query("DELETE FROM radacct WHERE AcctStopTime<'$expiration' && AcctStopTime>'0000-00-00 00:00:00'") or die("DELETE FROM radacct WHERE AcctStopTime<'$expiration' && AcctStopTime>'0000-00-00 00:00:00'");

      $results.="Archived old rad acct data. \n";


      $sqld="UPDATE config SET `lastrad`='$time'";
      $resultd = @sql::query($sqld) or die("couldn't execute query  $sql.".mysql_error());

   }

$sqld="INSERT INTO cronlogs (script,datetime,results) VALUES ('db.php',\"$time\",\"$results\")";
$resultd = @sql::query($sqld) or die("couldn't execute query  $sql.".mysql_error());

echo $sqld;
?>

Back to top View user's profile Send private message Yahoo Messenger MSN Messenger
roganty
-


Joined: 08 Jun 2004
Posts: 357
Location: Bristol, UK

PostPosted: Mon Jan 05, 2009 6:50 pm    Post subject: Reply with quote

Have you tried echoing the variable $this->filename to see what it outputs?

This is just a hunch, but I think it might be to do with windows using the back slah (\) character instead of the usual forward slash (/)

The back slash is also used as an escape character, so this might be the problem!
_________________
Anthony R

Roganty
| Links-Links.co.uk
Back to top View user's profile Send private message Visit poster's website
Display posts from previous:   
Post new topic   Reply to topic    Aprelium Forum Index -> PHP All times are GMT + 1 Hour
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB phpBB Group