I've been at this for a bit now and this is the closest I've gotten to backing up an entire site and database with PHP. The issue is I can't figure out why I continue to receive errors on lines 145 and 154.
Error:Notice: Undefined variable: arr_zip in C:\xampp\htdocs\wordpress\backup.php on line 145
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\wordpress\backup.php on line 145
Notice: Undefined variable: delete_zip in C:\xampp\htdocs\wordpress\backup.php on line 154
<?php
ini_set ("max_execution_time", 0);
$dir = "site-backup-stark";
if(!(file_exists($dir)))
{
mkdir($dir, 0777);
}
$host = "localhost"; //host name
$username = "wordpress_user"; //username
$password = "pasword99"; // your password
$dbname = "wordpress_db"; // database name
$zip = new ZipArchive();
backup_tables($host, $username, $password, $dbname);
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$con = mysql_connect($host,$user,$pass);
mysql_select_db($name,$con);
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$return = "";
//cycle through
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);
$return.= 'DROP TABLE '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "nn".$row2[1].";nn";
while($row = mysql_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = preg_replace("#n#","n",$row[$j]);
if (isset($row[$j]))
{
$return.= '"'.$row[$j].'"' ;
}
else
{
$return.= '""';
}
if ($j<($num_fields-1)) { $return.= ','; }
}
$return.= ");n";
}
$return.="nnn";
}
//save file
$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
if (glob("*.sql") != false)
{
$filecount = count(glob("*.sql"));
$arr_file = glob("*.sql");
for($j=0;$j<$filecount;$j++)
{
$res = $zip->open($arr_file[$j].".zip", ZipArchive::CREATE);
if ($res === TRUE)
{
$zip->addFile($arr_file[$j]);
$zip->close();
unlink($arr_file[$j]);
}
}
}
//get the current folder name-start
$path = dirname($_SERVER['PHP_SELF']);
$position = strrpos($path,'/') + 1;
$folder_name = substr($path,$position);
//get the current folder name-end
$zipname = date('Y/m/d');
$str = "stark-".$zipname.".zip";
$str = str_replace("/", "-", $str);
// open archive
if ($zip->open($str, ZIPARCHIVE::CREATE) !== TRUE)
{
die ("Could not open archive");
}
// initialize an iterator
// pass it the directory to be processed
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("../$folder_name/"));
// iterate over the directory
// add each file found to the archive
foreach ($iterator as $key=>$value)
{
if( strstr(realpath($key), "stark") == FALSE)
{
$zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}
}
// close and save archive
$zip->close();
echo "Archive created successfully.";
if(glob("*.sql.zip") != false)
{
$filecount = count(glob("*.sql.zip"));
$arr_file = glob("*.sql.zip");
for($j=0;$j<$filecount;$j++)
{
unlink($arr_file[$j]);
}
}
//get the array of zip files
if(glob("*.zip") != false)
{
$arr_zip = glob("*.zip");
}
//copy the backup zip file to site-backup-stark folder
foreach ($arr_zip as $key => $value) //error here
{
if (strstr($value, "stark"))
{
$delete_zip[] = $value;
copy("$value", "$dir/$value");
}
}
for ($i=0; $i < count($delete_zip); $i++) //error here
{
unlink($delete_zip[$i]);
}
?>
In this block of code:
//get the array of zip files
if(glob("*.zip") != false)
{
$arr_zip = glob("*.zip");
}
//copy the backup zip file to site-backup-stark folder
foreach ($arr_zip as $key => $value) //error here
If your call to glob("*.zip") returns a 'falsey' value your variable $arr_zip won't be initialised and you'll get an error in the foreach that follows it. Check for false explicitly with
if(glob("*.zip") !== false)
If this continues to fail you need to investigate why glob() is failing. I don't have a suggestion for that.
Later, you haven't initialised $delete_zip at all, somewhere you need
$delete_zip = array();
Related
I'm trying to get the data in the array that came from another function(that function is extracting the data in the csv file) and when i tried calling the two fields from that array it shows an error that it is unidentified variables.
The $this->csv_process(); as shown on the function action() is the function that extracts the data from the csv file and stores it in an array which is successful since I tried checking it on var_dump();
I also named the two fields as $name and $email as shown below:
Function CSV_process()
public function csv_process()
{
/* variables for openning the csv file */
if (!in_array($extension, $allowed_ext)) {
$this->session->set_flashdata("message", "Sorry, CSV file only.");
} else {
if ($filesize > 0) {
$file = fopen($filename, "r");
$toWrite = array();
$error = false;
$col_size = 2;
$skip = 0;
while ($data = fgetcsv($file, 10000, ","))
{
$skip++;
if ($skip == 1) {
continue;
}
$numofcol = count($data);
if ($numofcol != $col_size ) {
$this->session->set_flashdata("message", "Column count exceeded or missing.");
} else {
$name1 = $data[0];
$name = str_replace("'", "''", $name1);
$email1 = $data[1];
$email = str_replace("'", "''", $email1);
$toWrite[] = [
'name' => $name,
'email' => $email
];
}
}
}
}
return $toWrite;
}
Function Action()
function action(){
$toWrite[] = $this->csv_process();
foreach ($toWrite as $arr) {
list($name, $email) = $arr;
//die(var_dump($arr));
$query = $this->db->query("SELECT * FROM import WHERE name ='$name' AND email = '$email'");
if ($query->num_rows() >= 1) {
} else {
if ($name == "" OR $email == "") {
} else {
if ((filter_var($email, FILTER_VALIDATE_EMAIL)) == FALSE ) {
} else {
$this->db->query("INSERT INTO import(name, email, created_date) VALUES('".$name."', '".$email."', '".date("Y-m-d h-i-s")."')");
$this->session->set_flashdata('message', 'SUCCESS YEAY');
redirect('Clean_csv/index');
}
}
}
$query->free_result();
}
}
Listing arrays doesn't seem to work for here, anyone knows how to extract the data array from $arr?
You don't need to extract the values. You can use each $arr in a bound query. It simplifies the syntax for the select query.
For inserting use CodeIgniter's insert() method. Again, the $arr can be used directly by adding the date to it before the insert is attempted.
I think this will work.
function action()
{
$toWrite[] = $this->csv_process();
foreach($toWrite as $arr)
{
$query = $this->db->query("SELECT * FROM import WHERE name=? AND email=?", $arr);
if($query->num_rows() >= 1)
{}
else
{
if($arr['name'] == "" OR $arr['email'] == "")
{}
else
{
if((filter_var($email, FILTER_VALIDATE_EMAIL)) == FALSE)
{}
else
{
$arr['created_date'] = date("Y-m-d h-i-s");
$this->db->insert("import", $arr);
$this->session->set_flashdata('message', 'SUCCESS YEAY');
//??? redirect('Clean_csv/index');
//Are you sure, you may still have more $arr in $toWrite to process - right?
}
}
}
$query->free_result();
}
}
You need to know what a terrible idea it is to repeatedly run database queries inside a loop. Even though you use free_result() it could be a massive drain on server resources. If your csv file has several thousand items you are severely stressing the database and the server.
I wrote a controller action that is supposed to add an element (meeting) to the database here it is:
public function newAction(Request $request){
$meeting = new Meeting();
$meetingUser = new MeetingUser();
$project = new Project();
$projectName = "SocialPro";//$request->get('projectName');
echo($projectName);
$users = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findProjectUser($projectName);
//$form = $this->createForm('SocialPro\MeetingBundle\Form\MeetingType', $meeting);
//$form->handleRequest($request);
//if ($form->isSubmitted() && $form->isValid()) {
$userconn = $this->container->get('security.token_storage')->getToken()->getUser();
echo($userconn->getId());
if ($request->isMethod('POST')) {
echo("message form");
$role = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findUserRole($userconn)[0]['role'];
$date = $request->get('date');
if ($role == "PROJECT_MASTER" || $role == "TEAM_MASTER") {
for ($i = 0; $i < count($users); $i++) {
$meetings = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findMeetingUser($users[$i]['id'], $date);
}
if ($meetings == null || count($meetings) == 0) {
$project = $this->getDoctrine()->getRepository('SocialProProjectBundle:Project')->findBy(array("name" = >$projectName));
$meeting->setDescription($request->get('description'));
$meeting->setDate(new \DateTime($request->get('date')));
$meeting->setTime($request->get('time'));
$meeting->setProjectName($request->get('projectName'));
$meeting->setProject($project[0]);
$meetingUser->setMeetings($meeting);
$meetingUser->setUsers($userconn);
var_dump($meetingUser);
$meeting->setMeetingUser(array($meetingUser));
//$project->setMeetings($meeting->getId());
$em = $this->getDoctrine()->getManager();
$em->persist($meeting);
$em->persist($meetingUser);
$em->flush();
// $meetingUser->setUsers($request->get(''));
return $this->redirectToRoute('reunion_show', array('id' = > $meeting->getId()));
}
else {
echo("Membre indisponible");
}
}
else {
echo("Must be MASTER to create meeting");
}
}
return $this->render('SocialProMeetingBundle::ajoutMeeting.html.twig', array('users' = >$users));
// $em = $this->getDoctrine()->getManager();
//$em->persist($meeting);
//$em->flush($meeting);
// return $this->redirectToRoute('meeting_show', array('id' => $meeting->getId()));
//}
//return $this->render('SocialProMeetingBundle:ajouMeeting', array(
// 'meeting' => $meeting,
//'form' => $form->createView(),
//));
}
When I submit the form it gives me a site not available page. I tested it line by line and everything is working perfectly. Turns out the problem is in the
$em->persist($meeting);
And I have no idea how to fix it.
You must call flush immediately after calling persist like so:
$em->persist( $meeting );
$em->flush();
$em->persist( $meetingUser );
$em->flush();
Then it will persist both.
I am trying to upload the user pictures, but with the following example nothing is getting saved into the database and no errors are given. I know that the validation has to be done and it will once I get the files to be stored.
Here are the snippets from the view file:
<?php
echo $this->Form->create('User', array('enctype' => 'multipart/form-data'));
echo $this->form->input('upload', array('type' => 'file'));
echo $this->Form->end('Submit');
?>
The controller:
public function add() {
if ($this->request->is('post')) {
if(!empty($this->data['User']['upload']['name'])){
$file = $this->data['User']['upload'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/users/' . $file['name']);
$this->data['User']['image'] = $file['name'];
}
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('The employee has been saved');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('The employee could not be saved. Please, try again.');
}
}
}
change your view like this
<?php echo $this->Form->file('Document.submittedfile'); ?>
and your controller like this
public function fileupload() {
if ($this->request->is('post') || $this->request->is('put')) {
//die();
$file = $this->request->data['Document']['submittedfile'];
//$this->pdfadd1->save($this->request->data);
move_uploaded_file($this->data['Document']['submittedfile']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/cakephp3/cakephp1/cakephp/app/webroot/files/' . $this->data['Document']['submittedfile']['name']);
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Thanks for the submission'));
return $this->redirect(array('controller' => 'users','action' => 'index'));
}
}
dnt forget to create a folder in webroot or in any other place(for uploaded files)
Check the following link :
http://www.jamesfairhurst.co.uk/posts/view/uploading_files_and_images_with_cakephp
public function uploadFilesIphone($folder, $formdata, $replace , $itemId = null) {
// setup dir names absolute and relative
$folder_url = WWW_ROOT.$folder;
$rel_url = $folder; //echo
// create the folder if it does not exist
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
// if itemId is set create an item folder
if($itemId) {
// set new absolute folder
$folder_url = WWW_ROOT.$folder.'/'.$itemId;
// set new relative folder
$rel_url = $folder.'/'.$itemId;
// create directory
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
}
// list of permitted file types, this is only images but documents can be added
$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png','application/octet-stream');
// loop through and deal with the files;
$key = array();
$value = array();
foreach($formdata as $key => $value)
{
if($key == is_array($value))
{
$filename = str_replace(".", $replace , $value['name']);
}
// replace spaces with underscores
// assume filetype is false
$typeOK = false;
// check filetype is ok
foreach($permitted as $type)
{
if($key == is_array($value))
{
if($type == $value['type'])
{
$typeOK = true;
break;
}
}
}
// if file type ok upload the file
if($typeOK) {
// switch based on error code
if($key == is_array($value))
{
switch($value['error'])
{
case 0:
// check filename already exists
if(!file_exists($folder_url.'/'.$filename))
{
// create full filename
$full_url = $folder_url.'/'.$filename;
$url = $rel_url.'/'.$filename;
// upload the file
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
else
{
// create unique filename and upload file
// ini_set('date.timezone', 'Europe/London');
$now = date('Y-m-d-His');
$full_url = $folder_url.'/'.$now.$filename;
$url = $rel_url.'/'.$now.$filename;
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
// if upload was successful
if($success)
{
// save the url of the file
$result['urls'][] = $url;
}
else
{
$result['errors'][] = "Error uploaded $filename. Please try again.";
}
break;
case 3:
// an error occured
$result['errors'][] = "Error uploading $filename. Please try again.";
break;
default:
// an error occured
$result['errors'][] = "System error uploading $filename. Contact webmaster.";
break;
}
}
elseif($value['error'] == 4)
{
// no file was selected for upload
$result['nofiles'][] = "No file Selected";
}
else
{
// unacceptable file type
$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png.";
}
}
}
return $result;
}
I get this on my website:
Notice: Undefined offset: 1 in ...
Here is the full code, bolded is the part it refers to i think, basically this scripts should grab list of my channels from ther DB and then display info from the twitch:
<?php
defined('_JEXEC') or die('Direct access to this location is not allowed.');
$userList = $params->get('userlist');
$usersArray = explode(',', $userList);
$userGrab = "http://api.justin.tv/api/stream/list.json?channel=";
$checkedOnline = array ();
foreach($usersArray as $i =>$value){
$userGrab .= ",";
$userGrab .= $value;
}
unset($value);
$json_file = file_get_contents($userGrab, 0, null, null);
$json_array = json_decode($json_file, true);
//used to be $viewer = $json_array[$i]['stream_count'];
**foreach($usersArray as $i =>$value){
$title = $json_array[$i]['channel']['channel_url'];
$array = explode('/', $title);
$member = end($array);
$name = $json_array[$i]['name'];
$game = $json_array[$i]['meta_game'];
$viewer = $json_array[$i]['channel_count'];
$topic = $json_array[$i]['title'];
onlinecheck($member, $viewer, $topic, $game);
$checkedOnline[] = signin($member);
}**
unset($value);
unset($i);
function onlinecheck($online, $viewers, $topic, $game)
{
if ($game == "Counter-Strike: Global Offensive")
{
$igra = "csgo12.jpg";
}
else{
$igra = "online.png";
}
if ($online != null)
{
echo ' <img src="./modules/mod_twitchlist/tmpl/'.$igra.'">';
echo ' <strong>'.$online.'</strong>';
echo ' (' .$viewers.') - ';
echo '<strong>'.$topic.'</strong> </br>';
}
}
function signin($person){
if($person != null){
return $person;
}
else{
return null;
}
}
?>
<!-- <hr> -->
<?php
foreach ($usersArray as $i => $value1) {
foreach($checkedOnline as $ii => $value2){
if($value1 == $value2){
unset($usersArray[$i]);
}
}
}
$broj1 = count($usersArray); //neaktivni korisnici
$broj2 = count($checkedOnline); //ukupno streamova
if ($broj1 == $broj2){
echo '<strong><center>Nijedan stream nije aktivan trenutno!</center></strong>';
}
?>
Any hints?
I'm using this shell script below. I have it in app/console/command/BackupShell.php
When I run the script I get this error:
Fatal error: Class 'ConnectionManager' not found in app/Console/Command/BackupShell.php
What am I doing wrong?
class BackupShell extends Shell {
var $tasks = array('ProgressBar');
public function main() {
//database configuration, default is "default"
if(!isset($this->args[0])){
$this->args[0] = 'default';
}
//rows per query (less rows = less ram usage but more running time), default is 0 which means all rows
if(!isset($this->args[1])){
$this->args[1] = 0;
}
//directory to save your backup, it will be created automatically if not found., default is webroot/db-backups/yyyy-mm-dd
if(!isset($this->args[2])){
$this->args[2] = 'db-backups/'.date('Y-m-d',time());
}
App::import('Core', 'ConnectionManager');
$db = ConnectionManager::getDataSource($this->args[0]);
$backupdir = $this->args[2];
$seleced_tables = '*';
//$tables = array('orders', 'users', 'profiles');
if ($seleced_tables == '*') {
$sources = $db->query("show full tables where Table_Type = 'BASE TABLE'", false);
foreach($sources as $table){
$table = array_shift($table);
$tables[] = array_shift($table);
}
} else {
$tables = is_array($tables) ? $tables : explode(',', $tables);
}
$filename = 'db-backup-' . date('Y-m-d-H-i-s',time()) .'_' . (md5(implode(',', $tables))) . '.sql';
$return = '';
$limit = $this->args[1];
$start = 0;
if(!is_dir($backupdir)) {
$this->out(' ', 1);
$this->out('Will create "'.$backupdir.'" directory!', 2);
if(mkdir($backupdir,0755,true)){
$this->out('Directory created!', 2);
}else{
$this->out('Failed to create destination directory! Can not proceed with the backup!', 2);
die;
}
}
if ($this->__isDbConnected($this->args[0])) {
$this->out('---------------------------------------------------------------');
$this->out(' Starting Backup..');
$this->out('---------------------------------------------------------------');
foreach ($tables as $table) {
$this->out(" ",2);
$this->out($table);
$handle = fopen($backupdir.'/'.$filename, 'a+');
$return= 'DROP TABLE IF EXISTS `' . $table . '`;';
$row2 = $db->query('SHOW CREATE TABLE ' . $table.';');
//$this->out($row2);
$return.= "\n\n" . $row2[0][0]['Create Table'] . ";\n\n";
fwrite($handle, $return);
for(;;){
if($limit == 0){
$limitation = '';
}else{
$limitation = ' Limit '.$start.', '.$limit;
}
$result = $db->query('SELECT * FROM ' . $table.$limitation.';', false);
$num_fields = count($result);
$this->ProgressBar->start($num_fields);
if($num_fields == 0){
$start = 0;
break;
}
foreach ($result as $row) {
$this->ProgressBar->next();
$return2 = 'INSERT INTO ' . $table . ' VALUES(';
$j = 0;
foreach ($row[$table] as $key => $inner) {
$j++;
if(isset($inner)){
if ($inner == NULL){
$return2 .= 'NULL';
}else{
$inner = addslashes($inner);
$inner = ereg_replace("\n", "\\n", $inner);
$return2.= '"' . $inner . '"';
}
}else {
$return2.= '""';
}
if ($j < (count($row[$table]))) {
$return2.= ',';
}
}
$return2.= ");\n";
fwrite($handle, $return2);
}
$start+=$limit;
if($limit == 0){
break;
}
}
$return.="\n\n\n";
fclose($handle);
}
$this->out(" ",2);
$this->out('---------------------------------------------------------------');
$this->out(' Yay! Backup Completed!');
$this->out('---------------------------------------------------------------');
}else{
$this->out(' ', 2);
$this->out('Error! Can\'t connect to "'.$this->args[0].'" database!', 2);
}
}
function __isDbConnected($db = NULL) {
$datasource = ConnectionManager::getDataSource($db);
return $datasource->isConnected();
}
}
Is this 2.x code?
App::import('Core', 'ConnectionManager');
is deprecated/wrong in 2.x and should be
App::uses('ConnectionManager', 'Model');
and also be placed at the top of the file, right after the <?php tag