Hongmu Notes
Home Language Notes PHP remotely obtains the .sql.zip file and then imports it into the database
Language Notes PHP PHP and mysql

PHP remotely obtains the .sql.zip file and then imports it into the database

PHP remotely obtains the .sql.zip file and then imports it into the database

I have published a similar article beforePHP obtains the remote .sql.zip file, then clears the data, and then imports the .sql.zip into the mysql database》, but here is another function, which is also available for personal testing!

 隐藏内容:会员可查看
/**
 * 从远程URL下载包含SQL文件的ZIP压缩文件,解压缩SQL文件到指定目录,然后将数据导入到MySQL数据库中。
 *
 * @param string $remoteUrl 远程ZIP文件的URL地址
 * @param string $dbName 目标MySQL数据库的名称
 * @param string $dbUser 目标MySQL数据库的用户名
 * @param string $dbPass 目标MySQL数据库的密码
 * @param string $dbHost 目标MySQL数据库的主机地址,默认为localhost
 * @param string $sqlDir 解压缩SQL文件的目录路径,默认为当前文件所在目录下的path/目录
 * @throws Exception 如果下载、解压缩、数据库操作失败,则会抛出异常
 */
function importSqlZip($remoteUrl, $dbName, $dbUser, $dbPass, $dbHost = 'localhost', $sqlDir = __DIR__.'/path/') {
    // 创建一个临时文件用于保存下载的 Zip 文件
    $tempZip = tempnam(sys_get_temp_dir(), 'sql_zip_');

    // 下载远程 Zip 文件并保存到本地
    $fp = fopen($tempZip, 'w');
    $ch = curl_init($remoteUrl);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    $success = curl_exec($ch);
    curl_close($ch);
    fclose($fp);

    if (!$success) {
        throw new Exception('Failed to download the remote SQL ZIP file.');
    }
    // 创建指定目录
    if (!mkdir($sqlDir, 0777, true)) {
        throw new Exception('Failed to create directory.');
    }

    // 解压缩文件到指定目录
    $zip = new ZipArchive();
    if ($zip->open($tempZip) === TRUE) {
        $zip->extractTo($sqlDir);
        $zip->close();
    } else {
        throw new Exception('Failed to extract the SQL ZIP file.');
    }

    // 清空数据库
    $dsn = "mysql:host=$dbHost;dbname=$dbName";
    $pdo = new PDO($dsn, $dbUser, $dbPass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    foreach ($tables as $table) {
        $pdo->query("DROP TABLE IF EXISTS $table");
    }

    // 导入 SQL 文件
    $files = glob($sqlDir . '*.sql');
    foreach ($files as $file) {
        $pdo->exec(file_get_contents($file));
    }

    // 删除临时文件和 SQL 文件
    unlink($tempZip);
    $files = glob($sqlDir . '*.sql');
    foreach ($files as $file) {
        unlink($file);
    }
    rmdir($sqlDir);
}

When you want to call this function, you need to call it in the following format:

importSqlZip($remoteUrl, $dbName, $dbUser, $dbPass, $dbHost, $sqlDir)

Among them, $remoteUrl is the URL of the remote SQL ZIP file, $dbName is the name of the MySQL database to be imported, $dbUser is the user name of the MySQL database, $dbPass is the password of the MySQL database, $dbHost is the host address of the MySQL database, the default is localhost, $sqlDir is the storage path of the decompressed SQL file, the default is the "path/" folder in the directory of the current PHP file.

For example, if you want to import data from "https://example.com/backup.zip" into the "my_database" database, using the username "my_user" and password "my_password", the default database host address and the SQL file storage path, you should call the function like this:

importSqlZip('https://example.com/backup.zip', 'my_database', 'my_user', 'my_password');

If you want to customize the database host address and SQL file storage path, you can call the function like this:

importSqlZip('https://example.com/backup.zip', 'my_database', 'my_user', 'my_password', 'my_db_host', '/custom/sql/dir/');

 

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232
PHP special character escaping and restoration

PHP special character escaping and restoration Language Notes PHP PHP collection PHP and mysql

Escape character is a special character constant. Escape characters are backslashed " & quot; At the beginning, followed by one or more characters. The escaped character has a specific meaning, which is different from the original meaning of the character, so it is called "escaped" character. The use of escape characters 1: turn ordinary characters into special purposes, such as back key and enter key. 2. Used to convert a character with special meaning back to its original meaning. 3. Before data is written into the database, escape characters (function …
👁 180
mysqli in PHP

mysqli in PHP Language Notes PHP PHP collection PHP and mysql

The `mysqli_num_rows()` function is exclusively used with `SELECT` query methods, whereas the `mysqli_affected_rows()` function returns the number of rows affected by the previous SQL statement across the entire database; this function is primarily used with `INSERT`, `UPDATE`, and `DELETE` operations.
👁 146

Recommended reading

Home Security and Surveillance System Corporate Website Template 1031

Home Security and Surveillance System Corporate Website Template 1031 Practical Collection Yiyou template

This EyouCMS template is ideal for companies specializing in home surveillance and security systems. Its modern, technology-driven design effectively showcases surveillance equipment, security systems, solutions, and project cases. It enables security technology firms to present their products online and attract both residential and commercial clients. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 57
Summary of common problems in Yiyou CMS installation

Summary of common problems in Yiyou CMS installation Program Notes Yiyoucms

As an enterprise website building system developed based on PHP+MySQL, EyouCMS often encounters various problems during the actual installation and deployment process due to differences in server environments and improper operating procedures. This article summarizes the 7 most common installation errors and their solutions for your reference. Question 1: The installation error "Please carefully check the database account and password" error phenomenon: During the installation process, it prompts "Database connection failed, please try again..."
👁 73
(Adaptive Mobile Version) Yellow responsive car rental website PBootCMS template; Download used car sales and rental company website template – 0181

(Adaptive Mobile Version) Yellow responsive car rental website PBootCMS template; Download used car sales and rental company website template – 0181 Practical Collection pbootcms Template

This adaptive mobile-friendly PbootCMS website template is designed for the automotive and car rental industry, featuring a striking and professional design ideal for showcasing the sale of used or new vehicles as well as car rental services. It enables automotive dealerships or rental companies to display their vehicle inventory online and attract potential buyers or renters. Template Overview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.c...
👁 48
Responsive Precision Electronics Technology Website Template 1032

Responsive Precision Electronics Technology Website Template 1032 Practical Collection Yiyou template

An eyouCMS responsive website template designed for the precision electronics industry. Its modern, tech-driven design effectively showcases electronic products, R&D capabilities, manufacturing expertise, and industry applications. This template helps precision electronics companies showcase their brands online and attract industry clients. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for YououCMS | YououCMS...
👁 37
(Adaptive mobile app) – Official APP website (PBootCMS template) – Download source code for app landing pages – 0182

(Adaptive mobile app) – Official APP website (PBootCMS template) – Download source code for app landing pages – 0182 Practical Collection pbootcms Template

An adaptive mobile app template based on the PbootCMS website template, ideal for displaying app landing pages. Featuring a modern, tech-driven design style, it effectively highlights the app's core functionalities, interface screenshots, and download guidance. This template is an ideal choice for app development and operations teams looking to build high-conversion branded official websites and app download pages. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin
👁 64