banner

[Rule] Rules  [Home] Main Forum  [Portal] Portal  
[Members] Member Listing  [Statistics] Statistics  [Search] Search  [Reading Room] Reading Room 
[Register] Register  
[Login] Loginhttp  | https  ]
 
Forum Index Thảo luận hệ điều hành Windows Auto Backup DB và gửi vào email chọn trước với Cronjob  XML
  [Article]   Auto Backup DB và gửi vào email chọn trước với Cronjob 30/06/2009 06:51:29 (+0700) | #1 | 185004
BigballVN
Elite Member

[Minus]    0    [Plus]
Joined: 12/06/2005 07:25:21
Messages: 610
Offline
[Profile] [PM]
Với những ai làm Web có DB thì việc mất DB thật sự là một thảm họa. Nhưng cũng có cách để hạn chế điều đó, đơn giản nhất là backup DB thường xuyên. Nhưng hiếm ai đủ thời gian để làm việc đó manually. Nên chúng ta có thể kết hợp 1 đoạn script PHP + CronJob làm việc này tự động. Đầu tiên ta có thể dùng đoạn script sau:
Code:
<?php
/*
* Backup script on server.
*
* Runs on the server, called by Cron. Connects to the mySQL
* database and creates a backup file of the whole database.
* Saves to file in current directory.
*
* @author Cow <cow@invisionize.com>
* @version 0.2
* @date 18/08/2004
* @package Backup Server
* Upgraded Ver 2.0 (sending sql backup as attachment
* as email attachment, or send to a remote ftp server by
* @co-authors Cool Surfer<Coolsurfer@gmail.com> and
* Neagu Mihai<neagumihai@hotmail.com>
*/

set_time_limit(0);
$date = date("mdy-hia");
$dbserver = "localhost";
$dbuser = "user";
$dbpass = "pass";
$dbname = "database_name";
$file = "Blog-$date.sql.gz";
$gzip = TRUE;
$silent = TRUE;

function write($contents) {
if ($GLOBALS['gzip']) {
gzwrite($GLOBALS['fp'], $contents);
} else {
fwrite($GLOBALS['fp'], $contents);
}
}

mysql_connect ($dbserver, $dbuser, $dbpass);
mysql_select_db($dbname);

if ($gzip) {
$fp = gzopen($file, "w");
} else {
$fp = fopen($file, "w");
}

$tables = mysql_query ("SHOW TABLES");
while ($i = mysql_fetch_array($tables)) {
$i = $i['Tables_in_'.$dbname];

if (!$silent) {
echo "Backing up table ".$i."\n";
}

// Create DB code
$create = mysql_fetch_array(mysql_query ("SHOW CREATE TABLE ".$i));

write($create['Create Table'].";\n\n");

// DB Table content itself
$sql = mysql_query ("SELECT * FROM ".$i);
if (mysql_num_rows($sql)) {
while ($row = mysql_fetch_row($sql)) {
foreach ($row as $j => $k) {
$row[$j] = "'".mysql_escape_string($k)."'";
}

write("INSERT INTO $i VALUES(".implode(",", $row).");\n");
}
}
}

$gzip ? gzclose($fp) : fclose ($fp);

// Optional Options You May Optionally Configure

$use_gzip = "yes"; // Set to No if you don't want the files sent in .gz format
$remove_sql_file = "yes"; // Set this to yes if you want to remove the sql file after gzipping. Yes is recommended.
$remove_gzip_file = "no"; // Set this to yes if you want to delete the gzip file also. I recommend leaving it to "no"

// Configure the path that this script resides on your server.

$savepath = ""; // Full path to this directory. Do not use trailing slash!

$send_email = "yes"; /* Do you want this database backup sent to your email? Yes/No? If Yes, Fill out the next 2 lines */
$to = "email_can_gui_den@domain.com"; // Who to send the emails to, enter ur correct id.
$from = "email_gui_di@domain.com"; // Who should the emails be sent from?, may change it.

$senddate = date("j F Y");

$subject = "MySQL Database Backup - $senddate"; // Subject in the email to be sent.
$message = "Your MySQL database has been backed up and is attached to this email"; // Brief Message.

$use_ftp = "no"; // Do you want this database backup uploaded to an ftp server? Fill out the next 4 lines
$ftp_server = "ftp.diendanpascal.com"; // FTP hostname
$ftp_user_name = "mutsu"; // FTP username
$ftp_user_pass = "leauwater"; // FTP password
$ftp_path = "/"; // This is the path to upload on your ftp server!

// Do not Modify below this line! It will void your warranty <img src="http://bigball.info/wp-includes/images/smilies/icon_biggrin.gif" alt=":-D" class="wp-smiley"> !

$date = date("mdy-hia");
$filename = "$savepath/$dbname-$date.sql";

if($use_gzip=="yes"){
$filename2 = $file;
} else {
$filename2 = "$savepath/$dbname-$date.sql";
}

if($send_email == "yes" ){
$fileatt_type = filetype($filename2);
$fileatt_name = "".$dbname."-".$date."_sql.tar.gz";

$headers = "From: $from";

// Read the file to be attached ('rb' = read binary)
echo "Openning archive for attaching:".$filename2;
$file = fopen($filename2,'rb');
$data = fread($file,filesize($filename2));
fclose($file);

// Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

// Add the headers for a file attachment
$headers .= "\nMIME-Version: 1.0\n" ."Content-Type: multipart/mixed;\n" ." boundary=\"{$mime_boundary}\"";

// Add a multipart boundary above the plain message
$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";

// Base64 encode the file data
$data = chunk_split(base64_encode($data));

// Add file attachment to the message
echo "|{$mime_boundary}|{$fileatt_type}|{$fileatt_name}| {$fileatt_name}|{$mime_boundary}|<BR>";
$message .= "--{$mime_boundary}\n" ."Content-Type: {$fileatt_type};\n" ." name=\"{$fileatt_name}\"\n"."Content-Disposition: attachment;\n" ." filename=\"{$fileatt_name}\"\n" ."Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" ."--{$mime_boundary}--\n";
//$message.= "--{$mime_boundary}\n" ."Content-Type: {$fileatt_type};\n" ." name=\"{$fileatt_name}\"\n" "Content-Disposition: attachment;\n" ." filename=\"{$fileatt_name}\"\n" ."Content-Transfer-Encoding: base64\n\n" .
// $data . "\n\n" ."--{$mime_boundary}--\n";

// Send the message
$ok = @mail($to, $subject, $message, $headers);
if ($ok) {
echo "<h4><center><bg color=black><font color= blue>Database backup created and sent! File name $filename2 </p>
Idea Conceived By <a href="mailto:coolsurfer@gmail.com">coolsurfer@gmail.com</a>
Programmer email: <a href="mailto:neagumihai@hotmail.com">neagumihai@hotmail.com</a></p>
This is our first humble effort, pl report bugs, if U find any...</p>
Email me at <>coolsurfer@gmail.com nJoY!! <img src="http://bigball.info/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley">
</color></center></h4>";

} else {
echo "<h4><center>Mail could not be sent. Sorry!</center></h4>";
}
}

if($use_ftp == "yes"){
$ftpconnect = "ncftpput -u $ftp_user_name -p $ftp_user_pass -d debsender_ftplog.log -e dbsender_ftplog2.log -a -E -V $ftp_server $ftp_path $filename2";
shell_exec($ftpconnect);
echo "<h4><center>$filename2 Was created and uploaded to your FTP server!</center></h4>";

}

if($remove_gzip_file=="yes"){
exec("rm -r -f $filename2");
}
?>

Script này mình tìm được trên net. Các bạn thay thế user + pass + db name + email email mà DB sẽ được gửi đến + email gửi đi cho phù hợp. Save lại thành backup.php và sau đó up lên host test thử. http://domaincuaban.com/backup.php. Vào mail kiểm tra nếu thấy DB được gửi về là mọi chuyện đã Ok. Xong được 50%.

Tiếp thao là phần Cronjob:
Vì ko phải hosting nào cũng hỗ trợ nên đơn giản nhất là chúng ta dùng 1 cronjob của service nào đó trên net. Mình đang dùng http://cronless.com. Vào đó reg 1 acc xong login vào. Tiến hành setup cronjob.
Chọn Create New Job


Nhận tên của Job vào (tùy ý)

Nhập đường dẫn file backup (ở đây là http://domaincuaban.com/backup.php)

Intraval chọn tùy ý (có thể là 2 lần 1 ngày, 1 lần 1 ngày, 10 phút 1 lần) theo mình nên chọn 1 ngày 1 lần là hợp lý.

Start Date thì chọn Now (hoặc nhu cầu)

Bấm Create Job.

Thế là xong rồi. DB sẽ được backup hàng ngày và sẽ được gửi về mail của bạn. Khỏi sợ sự cố hosting nữa nhé (hack, suspend, error,...).

Chúc thành công!
[Up] [Print Copy]
  [Article]   Auto Backup DB và gửi vào email chọn trước với Cronjob 30/06/2009 07:23:17 (+0700) | #2 | 185012
phanledaivuong
Member

[Minus]    0    [Plus]
Joined: 23/05/2008 17:34:21
Messages: 315
Location: /dev/null
Offline
[Profile] [PM] [WWW]
xếp cho hỏi cái với những trang data nó thuộc loại khủng như kiểu hva, ddth, softvnn thì có cách nào hay hơn ko ví dụ lần sau nó send thêm phần thêm hoặc thay đổi cho mình chứ send hết thế này thì chắc chả có mail nào chứa nổi smilie
[Up] [Print Copy]
  [Article]   Auto Backup DB và gửi vào email chọn trước với Cronjob 06/07/2009 07:53:15 (+0700) | #3 | 185515
jforum3000
Member

[Minus]    0    [Plus]
Joined: 26/08/2007 02:53:39
Messages: 1172
Offline
[Profile] [PM]
Đã thử qua một số dạng script auto backup như thế này (Backup script on server, MySQL database backup ...), nhưng đều bị lỗi như sau

Fatal error: Allowed memory size of 25165824 bytes exhausted (tried to allocate 15700421 bytes) 


Kiểm tra lại file php.ini trên host đang dùng thì thấy memory_limit = 24 MB.

Search thông báo lỗi trên google, có thử qua 4 cái thủ thuật này rồi, nhưng không cách nào xài được cả.

To fix the problem, there are 4 actions that you can take...

Fix 1.
If you have access to the php.ini configuration file on your server, you can simply edit the php.ini directive that set the amount of memory to allocate to your php scripts, you would need to edit the line that reads...

memory_limit = 8M
or
memory_limit = 16M

to...

memory_limit = 24M
or
memory_limit = 32M

(note: add the line to the php.ini file if it is missing)
Editing the main php.ini file will probably require a restart of your webserver (apache?)


Fix 2.
If your server allows you to create a php.ini file in your webspace, you can create a simple text file called 'php.ini' with the line 'memory_limit = 24M' in it.
you can upload this file to your webserver into the web document root, eg. public_html or ht_docs folder (where your php script is / html files etc) however it would be better to place it outside of your web document root for security reasons, so uploading it to the parent folder of your web document root folder would be better, and please remember to set the file permissions on it to read only (chmod 644)

Fix 3.
If you do not have access to php.ini but your webspace is able to handle ".htaccess" files then you should be able to set it by adding the following line to your .htaccess file (create a .htaccess file if you don't have one)...

php_value memory_limit 24M

The .htaccess file should be located in your web document root folder. (although it can also be located 'higher' up the server file system)

Fix 4.
At the top of your php script file you can add the following line right after the opening '< ? php' tag...

ini_set("memory_limit","24M");

The above line is a built in php function which will allow you to set the memory size allocated to your php script.

You will only need to use one of the Fixes, not all of them ! 


Nguồn
http://www.codingforums.com/showthread.php?t=157152

Có bạn nào biết cách giải quyết khác không?
[Up] [Print Copy]
  [Article]   Auto Backup DB và gửi vào email chọn trước với Cronjob 06/07/2009 22:59:40 (+0700) | #4 | 185574
lenhan555
Member

[Minus]    0    [Plus]
Joined: 01/07/2009 18:14:30
Messages: 6
Offline
[Profile] [PM]
cái này nguy hiểm lắm đừng dùng nha mún tím hiểu thì vào http://vietvbb.vn hay http://hoiquantinhoc.com mà coi đừng tin cái bạn này
[Up] [Print Copy]
  [Article]   Auto Backup DB và gửi vào email chọn trước với Cronjob 07/07/2009 00:10:15 (+0700) | #5 | 185583
jforum3000
Member

[Minus]    0    [Plus]
Joined: 26/08/2007 02:53:39
Messages: 1172
Offline
[Profile] [PM]
lenhan555, mình xem code thấy có chỗ nào gọi là "nguy hiểm" đâu?
[Up] [Print Copy]
[digg] [delicious] [google] [yahoo] [technorati] [reddit] [stumbleupon]
Go to: 
 Users currently in here 
1 Anonymous

Powered by JForum - Extended by HVAOnline
 hvaonline.net  |  hvaforum.net  |  hvazone.net  |  hvanews.net  |  vnhacker.org
1999 - 2013 © v2012|0504|218|