As the internet continues to evolve, the demand for online music is growing rapidly. More and more users want the ability to play and share their favorite music on websites. If you want to create a simple music streaming platform, PHP and CGI are excellent technologies to consider. This article will guide you through the process of building a basic music streaming website with PHP and CGI.
Before we start developing, we need to set up the right environment:
A music streaming website requires a database to store song information. In this example, we’ll use MySQL as the database management system. First, we create a database named "music", and then create a table called "song_list" in that database. The SQL query for creating the table is as follows:
CREATE TABLE song_list ( id INT(11) NOT NULL AUTO_INCREMENT, title VARCHAR(255) NOT NULL, artist VARCHAR(255) NOT NULL, url VARCHAR(255) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Next, we need to write PHP code to connect to the database and retrieve the music list:
<?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'password'; $dbname = 'music'; $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); if (!$conn) { die("Database connection failed: " . mysqli_connect_error()); } $sql = "SELECT * FROM song_list"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_assoc($result)) { echo "<a href='" . $row['url'] . "'>" . $row['title'] . "</a> - " . $row['artist'] . "<br>"; } } else { echo "No music available"; } mysqli_close($conn); ?>
To enable the music upload feature, we also need to write a CGI script. Below is an example of a simple upload script written in Perl:
#!/usr/bin/perl use strict; use CGI; my $cgi = CGI->new(); print $cgi->header(); my $upload_dir = "/path/to/upload/directory/"; if ($cgi->param("file")) { my $file = $cgi->param("file"); my ($filename, $file_ext) = split(/\./, $file); my $upload_file = $upload_dir . $filename . "." . $file_ext; if ($cgi->upload("file", $upload_file)) { print "File upload successful!"; } else { print "File upload failed!"; } } else { print $cgi->start_form(-enctype => 'multipart/form-data', -method => 'POST'); print $cgi->filefield(-name => 'file'); print $cgi->submit(-name => 'submit', -value => 'Upload'); print $cgi->end_form(); } print "";
In addition to the basic music list and upload functions, we can also add more features to the website, such as user registration, login, comments, and likes. These features can be implemented using PHP and MySQL to enhance the user experience.
This article showed you how to develop a basic music streaming website using PHP and CGI. From database design to PHP and CGI code implementation, we covered the key techniques for building the site. I hope this guide helps with your development process. Best of luck with your project!