How to delete all files in folder using php

How to delete all files in folder using php

In this article,I will explain how to delete all files and subfolders in a directory with php script.
php function unlink is used to delete file and same function can be used to delete all the files in a directory. you can use rmdir() php function to delete empty directory.

Following code will delete all the files from a directory.
<?php
/***
  * deleteDir($directory) Function is used to Delete all files in directory.
  *
*/

function deleteDir($directory) {
   if (is_dir($directory))
         $dir = opendir($directory);
   else
      return false;
  
   while($file = readdir($dir)) {
  
      if ($file != "." && $file != "..")
   {
       //chmod($directory.$file, 0777);

         if (!is_dir($directory."/".$file))
            unlink($directory."/".$file);
         else
            deleteDir($directory.'/'.$file);   
      }
   }
   closedir($dir);
   rmdir($directory);
   return true;
}
//I have all my files in a directory called Test, and I need to remove all
files in a directory.
 $directory_name="Test";
 deleteDir($directory_name);

?>

You can also use below php Script to remove all files in a directory.

<php

// For linux
 $remove_directory = "rm -r /test/directory_name/*";
exec($remove_directory); 

 // For windows

 $remove_directory - "del /Q c:\\test\directory_name\*";
exec($remove_directory); 

?>

I hope This script will help you to delete all files and subfolders in a directory with php script.


Bookmark and Share

5+3+2 = 151022 - General Aptitude Question

General Aptitude Question:


5+3+2 = 151022  Then 7+2+5 =   ?

5+3+2 = 151022
9+2+4 = 183652
8+6+3 = 482466
5+4+5 = 202541
Then,
7+2+5 =   ?

Answer:


5+3+2 =(5*3)(5*2)((5*3 + 5*2)-3)=151022
// Formula: a + b + c =  (a*b) (a*c) (a*b+ a*c -b)

7+2+5 =(7*2)(7*5)((7*2 + 7*5)-2)
          =143547.




Bookmark and Share

Regedit – Cannot create value: Error writing to the registry

Regedit – Cannot create value: Error writing to the registry.

I was trying to add a key in the Registry (regedit.exe). I have Windows 7 Ultimate 64 bit, I got an error message saying 'Cannot create value: Error writing to the registry.'

Solution:


Step by Step Procedure:

1.Right click on the key

2.Click on Permissions

SYSTEM =>Full Control
Administrators => Full Control
Users > Read

3.Click Advanced => Owner tab.

4.Click on Administrators, select next to Replace owner on subcontainers and objects.

5.Click OK.

6.Done.


Bookmark and Share

File Handling using Shell Scripts

File Handling using Shell Scripts

In this article,I will explain File Handling using Shell Scripts.

Example: Add line at beginning of file.

Filename: test.sh

#!/bin/bash

read -p "File Name: " file   
if [ ! -e "$file" ]
then   
echo "File $file not found."
exit 50
fi

read -p "Name: " name
cat - $file <<<$name > $file.new
exit 0


Bookmark and Share

How to set up SMTP server on Localhost-Configure php.ini

How to set up SMTP server on Localhost-Configure php.ini

In this tutorial, I will explain how to set up SMTP server on Localhost and how to configure php.ini file.It is very easy to send Email from localhost.I was trying to send a mail via php mail function.The following error comes

Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\wamp\www\php\send_email.php on line 11.

Solution:

You need to configure php.ini file to send email via php send mail function.

1. Open php.ini file.

Default php.ini file settings

[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25


; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = you@yourdomain


; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
;sendmail_path =

these entries are required to send the mail to any mail client from mail server.

2.The following two lines don't exist:

auth_username
auth_password

you need to add them to send mail from a server that requires authentication.

3. change SMTP settings

smtp_server = mail.example.com ///your SMTP server name.
smtp_port = 26 // SMTP port number
auth_username = username@example.com
auth_password = password
sendmail_from = you@example.com // from email address.

4.SAVE php.ini file.

5. Restart Server.

6. DONE.

It's working for me on WAMPSERVER.

Example:

Send_email.php
<php
$to = "rajesh@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "test@example.com";
$headers = "From:" . $from;

if (mail($to,$subject,$message,$headers)) {
   echo("
Message successfully sent!
");
  } else {
   echo("
Message delivery failed...
");
  }


?> 

I hope, this will help you to Send Email from Localhost.


Bookmark and Share

Two dimensional array in pl sql oracle

Two dimensional array in pl sql oracle.
 
In this tutorial,I will explain how to create Two dimensional array in pl sql oracle.In PL/SQL Oracle developers can store information in arrays.

PL/SQL tables have a two properties 
1.Uunbounded
2.Sparse.

Example: Two dimentional array in PL/SQL 

DECLARE
 array2 array2Type;
BEGIN
 array2 := new array2Type(array1( A,B,C,D,E,F,G,H),array1( I,J,K,L,M,N,O,P));
  DBMS_OUTPUT.PUT_LINE('Two dimensional array in pl sql oracle:');
 for a1 in 1..array2.Count
  LOOP
      for a2 in 1..array2(a1).Count
      LOOP
          DBMS_OUTPUT.PUT(rpad(array2(a1)(a2),4));
      END LOOP;
      DBMS_OUTPUT.PUT_LINE('');
 END LOOP;

END;

Output:


Two dimensional array in pl sql oracle:
A B C D E F G H
I J K L M N O P


Bookmark and Share

check the number connections to mysql server-Linux Command

Check the number connections to mysql server using Linux command

In this tutorial, I will explain how to check the number of connections to mysql server using linux command.

check the number of connections to database

Command :netstat -antp | grep :3306 | wc -l  

//3306 is Mysql port Number

Linux command to check the number connections to mysql server

check the number of connections to FTP

Command :netstat -antp | grep :21 | wc -l  

//21 is FTP port number


Bookmark and Share

Access registry from an external hard drive

Access registry from an external hard drive 

In this tutorial,I will explain how to Access registry from an external hard drive.

1.Open REGEDIT

2.Click HKEY_LOCAL_MACHINE

3.Click FILE in the Menu Tab and choose LOAD HIVE.

4.browse the old registry hive.

where 'x:\' is the drive of the external hard drive and 'user' is located in x:\docs and Settings\user\NTUSER.DAT

You can also check other registry hives located at x:\windows\system32\config


Bookmark and Share

Change mysql port in WampServer

Change mysql port in WampServer

In this tutorial,I will explain how to change mysql port in WampServer.WAMP Server is one of the best software package.

Change port 3306 to 3307 on Wampserver

1. Right click on WampServer tray icon

2. Got to Mysql=>my.ini File.

3.Open my.ini File.

4.change the mysql port.

Look for this line

# The MySQL server
[wampmysqld]
port = 3306
#
#
[mysqld]
port=3306

5.Change both instances to another port (i.e. 3307)

6.Save my.ini File,

7.Restart Wamp MYSQL

8.Done.

we have changed the default port for MySQL from 3306 to 3307.


Bookmark and Share

How to get value from url in php

How to get value from url in php.

In this tutorial,I will explain How to get value from url in php.If you are creating website using PHP then programmers use URL to sent data to another page.
In PHP, $_GET variable is used to get values from url in php.Information sent from a url is visible to everyone.

Example: Get value of URL

index.html
<table>
<tbody>
<tr>
<td>
Name: <input name="name" type="text" />
</td>
<td>
Mobile: <input name="mobile" type="text" />
</td>
</tr>
<tr>
<td>
<a href="http://www.blogger.com/example.php?name='Test'">Next</a></td></tr>
</tbody>
</table>


When the user clicks the "Next" link, the URL sent to the server look like this:
http://www.example.com/example.php?name='Test'

Now you can use $_GET variable to Get the value of the previous url in php

Example.php
<?php

$name=$_GET["name"];

echo $name;

?>


Output:Test


Bookmark and Share

How to run a tcl in ns2 (Network Simulator)

How to run a tcl in ns2 (Network Simulator 2)

1. Install NS2

2. Go to Terminal and run ns filename

e.g. ns test.tcl (test.tcl is file name)

3.Run nam tcp.nam

4. Check .tr file to see the performance.



Install ns2 on Ubuntu 9.10 

1. Remove all ns-allinone-2.3x directory.

2. Type following command on terminal and enter:

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys B3F3334F

3. Add following ppa repository

deb http://ppa.launchpad.net/wouterh/ppa/ubuntu karmic main
deb-src http://ppa.launchpad.net/wouterh/ppa/ubuntu karmic main

4. Type following command on terminal and enter

sudo apt-get update

sudo apt-get install ns nam xgraph

5. Go to Terminal and run ns filename

e.g. ns test.tcl (test.tcl is file name)

6.Done


Bookmark and Share

WordPress Error: open_basedir restriction in effect

WordPress Error: open_basedir restriction in effect

 I was trying to upload photo on my WordPress blog and I got the following  error :

Warning: is_dir() [function.is-dir]: open_basedir restriction in effect.File(/) is not within the allowed path(s):


Warning: file_exists() [function.file-exists]: open_basedir restriction in effect.File(/) is not within the allowed path(s):


Solution:

Go to  Settings "Miscellaneous" >Store uploads in this folder:

Change  "/wp-content/uploads" to "wp-content/uploads" 

I hope this will help you.


Bookmark and Share

Javascript: Open new popup window at the center of the screen


Javascript: Open new popup window at the center of the screen

 In this article,I will explain how to open new popup window center on screen using Javascript.
 I have written java script function that opens a new popup window at the center of the screen.We are using window.open method of javascript

Syntax
 window.open([URL], [Window Name],..... );

Example: Center popup Window

<html>
<head>
<script >
function PopupWindowCenter(URL, title,w,h)
{var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
var newWin = window.open (URL, title, 'toolbar=no, location=no,directories=no, status=no, menubar=no, scrollbars=no, resizable=no,copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}
</script>
</head>
<body>
<a href="javascript:void(0);" onClick ="PopupWindowCenter('http://www.example.com', 'PopupWindowCenter',600,700)">Open Center popup Window</a>
</body>
</html>

Now you can open a simple popup window at the center of the screen.


Bookmark and Share

Import mysql dump using php

Import mysql dump using php

In this article,I will explain How to import Mysql database using PHP.I have written php Script to restore a phpMyAdmin MySQL dump.I have mysql dump file(mydb.sql).
Below code will also import Triggers and Stored Procedures.Importing the mysqldump file using php script would be the easiest and fastest solution.

Note: importing a mysqldump file does not import triggers due to some permission problems.Make sure that the user importing the database has the SUPER priveledge.

import.php

define('PMA_CHK_DROP', 1);
function PMA_checkTimeout()
{
    global $timestamp, $maximum_time, $timeout_passed;
    if ($maximum_time == 0) {
        return FALSE;
    } elseif ($timeout_passed) {
        return TRUE;
    
    } elseif ((time() - $timestamp) > ($maximum_time - 5)) {
        $timeout_passed = TRUE;
        return TRUE;
    } else {
        return FALSE;
    }
}


function PMA_detectCompression($filepath)
{
    $file = @fopen($filepath, 'rb');
    if (!$file) {
        return FALSE;
    }
    $test = fread($file, 4);
    $len = strlen($test);
    fclose($file);
    if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
        return 'application/gzip';
    }
    if ($len >= 3 && substr($test, 0, 3) == 'BZh') {
        return 'application/bzip2';
    }
    if ($len >= 4 && $test == "PK\003\004") {
        return 'application/zip';
    }
    return 'none';
}




function PMA_importRunQuery($sql = '', $full = '', $controluser = false)
{
    global $import_run_buffer, $go_sql, $complete_query, $display_query,
        $sql_query, $my_die, $error, $reload,
        $skip_queries, $executed_queries, $max_sql_len, $read_multiply,
        $cfg, $sql_query_disabled, $db, $run_query, $is_superuser;
    $read_multiply = 1;
    if (isset($import_run_buffer)) {
       
        if ($skip_queries > 0) {
            $skip_queries--;
        } else {
            if (!empty($import_run_buffer['sql']) && 
trim($import_run_buffer['sql']) != '') {
                $max_sql_len = max($max_sql_len, 
strlen($import_run_buffer['sql']));
                if (!$sql_query_disabled) {
                    $sql_query .= $import_run_buffer['full'];
                }
                if (!$cfg['AllowUserDropDatabase']
                 && !$is_superuser
                 && preg_match('@^[[:space:]]*DROP[[:space:]]+(IF 
EXISTS[[:space:]]+)?DATABASE @i', $import_run_buffer['sql'])) {
                    $GLOBALS['message'] = 
PMA_Message::error('strNoDropDatabases');
                    $error = TRUE;
                } else {
                    $executed_queries++;
                    if ($run_query && $GLOBALS['finished'] && empty($sql) 
&& !$error && (
                            (!empty($import_run_buffer['sql']) && 
preg_match('/^[\s]*(SELECT|SHOW|HANDLER)/i', $import_run_buffer['sql'])) ||
                            ($executed_queries == 1)
                            )) {
                        $go_sql = TRUE;
                        if (!$sql_query_disabled) {
                            $complete_query = $sql_query;
                            $display_query = $sql_query;
                        } else {
                            $complete_query = '';
                            $display_query = '';
                        }
                        $sql_query = $import_run_buffer['sql'];
                    } elseif ($run_query) {
                        if ($controluser) {
                            $result = 
PMA_query_as_cu($import_run_buffer['sql']);
                        } else {
                            $result = 
PMA_DBI_try_query($import_run_buffer['sql']);
                        }
                        $msg = '# ';
                        if ($result === FALSE) { // execution failed
                            if (!isset($my_die)) {
                                $my_die = array();
                            }
                            $my_die[] = array('sql' => 
$import_run_buffer['full'], 'error' => PMA_DBI_getError());


                            if ($cfg['VerboseMultiSubmit']) {
                                $msg .= $GLOBALS['strError'];
                            }


                            if (!$cfg['IgnoreMultiSubmitErrors']) {
                                $error = TRUE;
                                return;
                            }
                        } elseif ($cfg['VerboseMultiSubmit']) {
                            $a_num_rows = (int)@PMA_DBI_num_rows($result);
                            $a_aff_rows = (int)@PMA_DBI_affected_rows();
                            if ($a_num_rows > 0) {
                                $msg .= $GLOBALS['strRows'] . ': ' . 
$a_num_rows;
                            } elseif ($a_aff_rows > 0) {
                                $msg .= 
sprintf($GLOBALS['strRowsAffected'], $a_aff_rows);
                            } else {
                                $msg .= $GLOBALS['strEmptyResultSet'];
                            }
                        }
                        if (!$sql_query_disabled) {
                            $sql_query .= $msg . "\n";
                        }


                       
                        if ($result != FALSE && 
preg_match('@^[\s]*USE[[:space:]]*([\S]+)@i', $import_run_buffer['sql'], 
$match)) {
                            $db = trim($match[1]);
                            $db = trim($db,';'); 
                            $reload = TRUE;
                        }


                        if ($result != FALSE && 
preg_match('@^[\s]*(DROP|CREATE)[\s]+(IF 
EXISTS[[:space:]]+)?(TABLE|DATABASE)[[:space:]]+(.+)@im', 
$import_run_buffer['sql'])) {
                            $reload = TRUE;
                        }
                    } 
                } 
            } 
            elseif (!empty($import_run_buffer['full'])) {
                if ($go_sql) {
                    $complete_query .= $import_run_buffer['full'];
                    $display_query .= $import_run_buffer['full'];
                } else {
                    if (!$sql_query_disabled) {
                        $sql_query .= $import_run_buffer['full'];
                    }
                }
            }
           
            if (! $go_sql && $run_query) {
                if ($cfg['VerboseMultiSubmit'] && ! empty($sql_query)) {
                    if (strlen($sql_query) > 50000 || $executed_queries > 
50 || $max_sql_len > 1000) {
                        $sql_query = '';
                        $sql_query_disabled = TRUE;
                    }
                } else {
                    if (strlen($sql_query) > 10000 || $executed_queries > 
10 || $max_sql_len > 500) {
                        $sql_query = '';
                        $sql_query_disabled = TRUE;
                    }
                }
            }
        } 
    } 


   
    if (!empty($sql) || !empty($full)) {
        $import_run_buffer = array('sql' => $sql, 'full' => $full);
    } else {
        unset($GLOBALS['import_run_buffer']);
    }
}






function PMA_importGetNextChunk($size = 32768)
{
    global $compression, $import_handle, $charset_conversion, 
$charset_of_file,
        $charset, $read_multiply;
 $compression="none"; 
     if ($read_multiply <= 8) {
        $size *= $read_multiply;
    } else {
        $size *= 8;
    }
    $read_multiply++;


   
    if ($size > $GLOBALS['read_limit']) {
        $size = $GLOBALS['read_limit'];
    }


    if (PMA_checkTimeout()) {
        return FALSE;
    }
    if ($GLOBALS['finished']) {
        return TRUE;
    }


    if ($GLOBALS['import_file'] == 'none') {
       
        if (strlen($GLOBALS['import_text']) < $size) {
            $GLOBALS['finished'] = TRUE;
            return $GLOBALS['import_text'];
        } else {
            $r = substr($GLOBALS['import_text'], 0, $size);
            $GLOBALS['offset'] += $size;
            $GLOBALS['import_text'] = substr($GLOBALS['import_text'], 
$size);
            return $r;
        }
    }


    switch ($compression) {
        case 'application/bzip2':
            $result = bzread($import_handle, $size);
            $GLOBALS['finished'] = feof($import_handle);
            break;
        case 'application/gzip':
            $result = gzread($import_handle, $size);
            $GLOBALS['finished'] = feof($import_handle);
            break;
        case 'application/zip':
            $result = substr($GLOBALS['import_text'], 0, $size);
            $GLOBALS['import_text'] = substr($GLOBALS['import_text'], 
$size);
            $GLOBALS['finished'] = empty($GLOBALS['import_text']);
            break;
        case 'none':
     $result = fread($import_handle, $size);
            $GLOBALS['finished'] = feof($import_handle);
            break;
    }
    $GLOBALS['offset'] += $size;


    if ($charset_conversion) {
        return PMA_convert_string($charset_of_file, $charset, $result);
    } else {
     
        if ($GLOBALS['offset'] == $size) {
            // UTF-8
            if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
                $result = substr($result, 3);
            // UTF-16 BE, LE
            } elseif (strncmp($result, "\xFE\xFF", 2) == 0 || 
strncmp($result, "\xFF\xFE", 2) == 0) {
                $result = substr($result, 2);
            }
        }
        return $result;
    }
}
?>


Example :How to import mysql dump (.sql) into a database using PHP Script?

import_mysql.php


ini_set("display_errors","1");

$user_name = "root";
$password = "";
$database = "mydb";
$server = "localhost";

$conn = mysql_connect($server, $user_name, $password);
mysql_select_db($database);

include("import.php");

$timeout_passed = FALSE;
$error = FALSE;
$read_multiply = 1;
$finished = FALSE;
$offset = 0;
$max_sql_len = 0;
$file_to_unlink = '';
$sql_query = '';
$sql_query_disabled = FALSE;
$go_sql = FALSE;
$executed_queries = 0;
$run_query = TRUE;
$charset_conversion = FALSE;
$reset_charset = FALSE;
$bookmark_created = FALSE;

$import_file='mydb.sql';

$import_handle = @fopen($import_file, 'r');


$memory_limit = trim(@ini_get('memory_limit'));

if (empty($memory_limit)) {
    $memory_limit = 2 * 1024 * 1024;
}

if ($memory_limit == -1) {
    $memory_limit = 10 * 1024 * 1024;
}


if (strtolower(substr($memory_limit, -1)) == 'm') {
    $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
} elseif (strtolower(substr($memory_limit, -1)) == 'k') {
    $memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
} elseif (strtolower(substr($memory_limit, -1)) == 'g') {
    $memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
} else {
    $memory_limit = (int)$memory_limit;
}

$read_limit = $memory_limit / 8; 


$buffer = '';

$sql = '';
$start_pos = 0;
$i = 0;
$len= 0;
$big_value = 2147483647;

$sql_delimiter = ';';


$GLOBALS['finished'] = false;

while (!($GLOBALS['finished'] && $i >= $len) && !$error && 
!$timeout_passed) {
   
    $data = PMA_importGetNextChunk();

if ($data === FALSE) {
       
        $offset -= strlen($buffer);
        break;
    } elseif ($data === TRUE) {
       
    } else {
       
        $buffer .= $data;
       
        unset($data);
      
        if ((strpos($buffer, $sql_delimiter, $i) === FALSE) && 
!$GLOBALS['finished'])  {
            continue;
        }
    }
   
    $len = strlen($buffer);

   
    while ($i < $len) {
        $found_delimiter = false;
       
        $old_i = $i;
        
        if (preg_match('/(\'|"|#|-- |\/\*|`|(?i)DELIMITER)/', $buffer, 
$matches, PREG_OFFSET_CAPTURE, $i)) {
            
            $first_position = $matches[1][1];
        } else {
            $first_position = $big_value;
        }
        
      
        $first_sql_delimiter = strpos($buffer, $sql_delimiter, $i);
        if ($first_sql_delimiter === FALSE) {
            $first_sql_delimiter = $big_value;
        } else {
            $found_delimiter = true;
        }

     
        $i = min($first_position, $first_sql_delimiter);

        if ($i == $big_value) {
         

            $i = $old_i;
            if (!$GLOBALS['finished']) {
                break;
            }
            
            if (trim($buffer) == '') {
                $buffer = '';
                $len = 0;
                break;
            }
          
            $i = strlen($buffer) - 1;
        }

       
        $ch = $buffer[$i];

      
        if (strpos('\'"`', $ch) !== FALSE) {
            $quote = $ch;
            $endq = FALSE;
            while (!$endq) {
                
                $pos = strpos($buffer, $quote, $i + 1);
               
                if ($pos === FALSE) {
                 
                    if ($GLOBALS['finished']) {
                        $endq = TRUE;
                        $i = $len - 1;
                    }
                    $found_delimiter = false;
                    break;
                }
            
                $j = $pos - 1;
                while ($buffer[$j] == '\\') $j--;
               
                $endq = (((($pos - 1) - $j) % 2) == 0);
               
                $i = $pos;

                if ($first_sql_delimiter < $pos) {
                    $found_delimiter = false;
                }
            }
            if (!$endq) {
                break;
            }
            $i++;
            
            if ($GLOBALS['finished'] && $i == $len) {
                $i--;
            } else {
                continue;
            }
        }

        
        if ((($i == ($len - 1) && ($ch == '-' || $ch == '/'))
          || ($i == ($len - 2) && (($ch == '-' && $buffer[$i + 1] == '-')
            || ($ch == '/' && $buffer[$i + 1] == '*')))) && 
!$GLOBALS['finished']) {
            break;
        }

       
        if ($ch == '#'
         || ($i < ($len - 1) && $ch == '-' && $buffer[$i + 1] == '-'
          && (($i < ($len - 2) && $buffer[$i + 2] <= ' ')
           || ($i == ($len - 1)  && $GLOBALS['finished'])))
         || ($i < ($len - 1) && $ch == '/' && $buffer[$i + 1] == '*')
                ) {
                       if ($start_pos != $i) {
                $sql .= substr($buffer, $start_pos, $i - $start_pos);
            }
           
            $j = $i;
            $i = strpos($buffer, $ch == '/' ? '*/' : "\n", $i);
         
            if ($i === FALSE) {
                if ($GLOBALS['finished']) {
                    $i = $len - 1;
                } else {
                    break;
                }
            }
          
            if ($ch == '/') {
               
                if ($buffer[$j + 2] == '!') {
                    $comment = substr($buffer, $j + 3, $i - $j - 3);
                    
                }
                $i++;
            }
           
            $i++;
          
            $start_pos = $i;
           
            if ($i == $len) {
                $i--;
            } else {
                continue;
            }
        }
       
        if (strtoupper(substr($buffer, $i, 9)) == "DELIMITER"
         && ($buffer[$i + 9] <= ' ')
         && ($i < $len - 11)
         && strpos($buffer, "\n", $i + 11) !== FALSE) {
           $new_line_pos = strpos($buffer, "\n", $i + 10);
           $sql_delimiter = substr($buffer, $i + 10, $new_line_pos - $i - 
10);
           $i = $new_line_pos + 1;
        
           $start_pos = $i;
           continue;
        }

       
        if ($found_delimiter || ($GLOBALS['finished'] && ($i == $len - 1))) 
{
            $tmp_sql = $sql;
            if ($start_pos < $len) {
                $length_to_grab = $i - $start_pos;

                if (! $found_delimiter) {
                    $length_to_grab++;
                }
                $tmp_sql .= substr($buffer, $start_pos, $length_to_grab);
                unset($length_to_grab);
            }
$error=0;
         
            if (! preg_match('/^([\s]*;)*$/', trim($tmp_sql))) {
                $sql = $tmp_sql;
if (!$result = mysql_query($sql))
 {
 $dbErr = true;
 }
                $buffer = substr($buffer, $i + strlen($sql_delimiter));
                
                $len = strlen($buffer);
                $sql = '';
                $i = 0;
                $start_pos = 0;
               
                if ((strpos($buffer, $sql_delimiter) === FALSE) && 
!$GLOBALS['finished']) {
                    break;
                }
            } else {
                $i++;
                $start_pos = $i;
            }
        }
    } 
 } 
 ?>
I hope this will help you to import mysqldump file using php script.
Note: importing a mysqldump file does not import triggers due to some permission problems.Make sure that the user importing the database has the SUPER priveledge.



Bookmark and Share