


How to use PHP to implement a simple online music download and playback system
How to use PHP to implement a simple online music download and playback system
As network technology continues to develop today, music has become an indispensable part of people's lives. The demand for online music downloading and playing systems is also growing. This article will introduce how to use PHP to write a simple online music download and playback system, and provide specific code examples.
1. Build environment and database
First, we need a server environment to run PHP and create a database to store information about music files. Use XAMPP or other similar tools to set up a PHP running environment, and use MySQL to create a database named "music". Create a table named "songs" in the "music" database. The structure of the table is as follows:
CREATE TABLE `songs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `artist` varchar(255) NOT NULL, `file` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2. Upload music files
In the system, users can pass a simple form to upload music files and save the files to the specified directory on the server. Create a file named "upload.php" and add the following code:
<?php if(isset($_POST['submit'])){ $name = $_POST['name']; $artist = $_POST['artist']; $file = $_FILES['file']['name']; $targetDir = "./uploads/"; $targetFile = $targetDir . basename($file); // 保存文件 if(move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)){ // 将文件信息保存到数据库 $conn = new mysqli('localhost', 'root', '', 'music'); $sql = "INSERT INTO songs (name, artist, file) VALUES ('$name', '$artist', '$file')"; $conn->query($sql); $conn->close(); echo "上传成功!"; }else{ echo "上传失败!"; } } ?> <form method="POST" action="" enctype="multipart/form-data"> 歌曲名:<input type="text" name="name" required><br> 歌手:<input type="text" name="artist" required><br> 音乐文件:<input type="file" name="file" required><br> <input type="submit" name="submit" value="上传"> </form>
This code will receive the music files submitted by the user and save them to the "uploads" folder in the specified directory on the server. At the same time, the name, artist and file name of the music file are saved to the database.
3. Display the music list
In the system, users can view the uploaded music list. Create a file named "index.php" and add the following code:
<?php $conn = new mysqli('localhost', 'root', '', 'music'); $sql = "SELECT * FROM songs"; $result = $conn->query($sql); ?> <table> <tr> <th>歌曲名</th> <th>歌手</th> <th>操作</th> </tr> <?php while($row = $result->fetch_assoc()): ?> <tr> <td><?php echo $row['name']; ?></td> <td><?php echo $row['artist']; ?></td> <td> <a href="play.php?id=<?php echo $row['id']; ?>">播放</a> <a href="download.php?file=<?php echo $row['file']; ?>">下载</a> </td> </tr> <?php endwhile; ?> </table>
In the above code, the "song" table in the database is queried and the name of the music file, the singer and the name of the music file are added using a loop statement. Action links are displayed in a table.
4. Play music
When the user clicks the "play" link in the music list, we need to use a file named "play.php" to play the music. Create this file and add the following code:
<?php $id = $_GET['id']; $conn = new mysqli('localhost', 'root', '', 'music'); $sql = "SELECT * FROM songs WHERE id=$id"; $result = $conn->query($sql); $row = $result->fetch_assoc(); $music = "./uploads/" . $row['file']; ?> <audio controls autoplay> <source src="<?php echo $music; ?>" type="audio/mpeg"> 你的浏览器不支持音频播放。 </audio>
In the above code, by obtaining the URL parameter "id" of the "play.php" file, query the corresponding music file information in the database and change the path of the music file Displayed in an HTML5 audio player.
5. Download Music
When the user clicks the "Download" link in the music list, we need to use a file named "download.php" to implement the download function of the music file. Create the file and add the following code:
<?php $file = $_GET['file']; $filepath = './uploads/' . $file; header('Content-Type: application/octet-stream'); header('Content-disposition: attachment; filename="'.$file.'"'); header('Content-Length: ' . filesize($filepath)); readfile($filepath); ?>
In the above code, by obtaining the URL parameter "file" of the "download.php" file, the music file is downloaded to the user's computer as an attachment according to the file path. middle.
6. Summary
Through the above code examples, we can implement a simple online music download and playback system. Users can upload music files, and the system will save the files to the specified directory on the server and save relevant information to the database. Users can choose to play or download music files by viewing the music list. Although this system is simple, it can provide users with basic online music services. Of course, we can also expand and optimize according to needs.
The above is the detailed content of How to use PHP to implement a simple online music download and playback system. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.
