www.webdeveloper.com
Page 2 of 2 FirstFirst 12
Results 16 to 29 of 29

Thread: Uploading and downloading music files to and from Mysql

  1. #16
    Join Date
    May 2014
    Posts
    75
    Try replacing the PHP file with this:

    PHP Code:
    <?php
     
    // Show the page as text instead of HTML. Can be helpful in debugging
     
    header('Content-Type:text/plain');

     
    // Enable debug error reporting
     
    if (true) {
      
    error_reporting(E_ALL);
      
    ini_set("display_errors"1);
     }
     
    print_r($_POST);
    echo 
    "\n-------\n"// \n = new line
     
    print_r($_FILES);

     
    // Connects to your Database 
     
    mysql_connect("localhost""root""") or die(mysql_error()) ; 
     
    mysql_select_db("mydb") or die(mysql_error()) ; 




     if (((
    $_FILES["file"]["type"] == "audio/mp3")
     || (
    $_FILES["file"]["type"] == "audio/mp4")
     || (
    $_FILES["file"]["type"] == "audio/wav"))
     && (
    $_FILES["file"]["size"] < 1000000))
     {
     if (
    $_FILES["file"]["error"] > 0)
     {
     echo 
    "Return Code: " $_FILES["file"]["error"] . "<br />";
     }
     else
     {
     echo 
    "Upload: " $_FILES["file"]["name"] . "<br />";
     echo 
    "Type: " $_FILES["file"]["type"] . "<br />";
     echo 
    "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
     echo 
    "Temp file: " $_FILES["file"]["tmp_name"] . "<br />";

     if (
    file_exists("upload/" $_FILES["file"]["name"]))
     {
     echo 
    $_FILES["file"]["name"] . " already exists. ";
     }
     else

     
    $mp3_name $_FILES["file"]["name"];
     
    $mp3_path "pload/$mp3_name";

     
    move_uploaded_file($_FILES["file"]["tmp_name"], $mp3_path);

     
    $sql "INSERT INTO 'music' SET name='$mp3_name', location'$mp3_path'";
     
    $result mysql_query($sql);
     if(
    $result)
     {
     echo 
    'MP3 Upload successfully';
     }
     else
     {
     echo 
    'ERROR: Upload Failed';
     }

     }
     }
     else
     {
     echo 
    "Invalid file";
     }
     
    ?>
    Paste the results here.

    Congrats on finally getting the PHP tags, it's appreciated and much easier to read.

  2. #17
    Join Date
    May 2014
    Posts
    30
    Quote Originally Posted by Gravy View Post
    Try replacing the PHP file with this:

    PHP Code:
    <?php
     
    // Show the page as text instead of HTML. Can be helpful in debugging
     
    header('Content-Type:text/plain');

     
    // Enable debug error reporting
     
    if (true) {
      
    error_reporting(E_ALL);
      
    ini_set("display_errors"1);
     }
     
    print_r($_POST);
    echo 
    "\n-------\n"// \n = new line
     
    print_r($_FILES);

     
    // Connects to your Database 
     
    mysql_connect("localhost""root""") or die(mysql_error()) ; 
     
    mysql_select_db("mydb") or die(mysql_error()) ; 




     if (((
    $_FILES["file"]["type"] == "audio/mp3")
     || (
    $_FILES["file"]["type"] == "audio/mp4")
     || (
    $_FILES["file"]["type"] == "audio/wav"))
     && (
    $_FILES["file"]["size"] < 1000000))
     {
     if (
    $_FILES["file"]["error"] > 0)
     {
     echo 
    "Return Code: " $_FILES["file"]["error"] . "<br />";
     }
     else
     {
     echo 
    "Upload: " $_FILES["file"]["name"] . "<br />";
     echo 
    "Type: " $_FILES["file"]["type"] . "<br />";
     echo 
    "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
     echo 
    "Temp file: " $_FILES["file"]["tmp_name"] . "<br />";

     if (
    file_exists("upload/" $_FILES["file"]["name"]))
     {
     echo 
    $_FILES["file"]["name"] . " already exists. ";
     }
     else

     
    $mp3_name $_FILES["file"]["name"];
     
    $mp3_path "pload/$mp3_name";

     
    move_uploaded_file($_FILES["file"]["tmp_name"], $mp3_path);

     
    $sql "INSERT INTO 'music' SET name='$mp3_name', location'$mp3_path'";
     
    $result mysql_query($sql);
     if(
    $result)
     {
     echo 
    'MP3 Upload successfully';
     }
     else
     {
     echo 
    'ERROR: Upload Failed';
     }

     }
     }
     else
     {
     echo 
    "Invalid file";
     }
     
    ?>
    Paste the results here.

    Array
    (
    )

    -------
    Array
    (
    )
    <br />
    <b>Notice</b>: Undefined index: file in <b>C:\xampp\htdocs\FXMAS\upload.php</b> on line <b>104</b><br />
    <br />
    <b>Notice</b>: Undefined index: file in <b>C:\xampp\htdocs\FXMAS\upload.php</b> on line <b>105</b><br />
    <br />
    <b>Notice</b>: Undefined index: file in <b>C:\xampp\htdocs\FXMAS\upload.php</b> on line <b>106</b><br />
    Invalid file

    Congrats on finally getting the PHP tags, it's appreciated and much easier to read.
    Just pasted in the results.

    Getting round the undefined index issue is just a matter of putting in the isset function right? Would that really prevent me from uploading files to the db?

  3. #18
    Join Date
    May 2014
    Posts
    75
    Well, there seems to be the problem:

    Array
    (
    )

    -------
    Array
    (
    )

    Those 2 arrays should have content, they should contain your post and uploaded file info, since they're empty we now know why there's nothing being added to the database. I'm not sure why it's not receiving any data, but that's the first issue I'd look into.

    And yes, you should do an isset check to make sure $_FILES['file'] exists, but that wont fix the current problem.

    Final note: you did submit a file to that form when you got those results, right?

  4. #19
    Join Date
    May 2014
    Posts
    30
    Quote Originally Posted by Gravy View Post
    Well, there seems to be the problem:

    Array
    (
    )

    -------
    Array
    (
    )

    Those 2 arrays should have content, they should contain your post and uploaded file info, since they're empty we now know why there's nothing being added to the database. I'm not sure why it's not receiving any data, but that's the first issue I'd look into.

    And yes, you should do an isset check to make sure $_FILES['file'] exists, but that wont fix the current problem.

    Final note: you did submit a file to that form when you got those results, right?
    I just added the code you ask me to then ran it in my browser. When I did that it just returned back that result

  5. #20
    Join Date
    May 2014
    Posts
    75
    Quote Originally Posted by Jcse7en View Post
    I just added the code you ask me to then ran it in my browser. When I did that it just returned back that result
    Don't just run it, try to upload a file with the form. You can't see the errors and debugging info if you don't try to upload the file.

  6. #21
    Join Date
    May 2014
    Posts
    30
    Quote Originally Posted by Gravy View Post
    Don't just run it, try to upload a file with the form. You can't see the errors and debugging info if you don't try to upload the file.
    Ok was being an idiot :-)

    Here's the result after submitting file to form

    Array ( ) ------- Array ( [file] => Array ( [name] => NTLInstr.mp3 [type] => [tmp_name] => [error] => 1 [size] => 0 ) ) Invalid file


    Thanks

  7. #22
    Join Date
    May 2014
    Posts
    75
    Quote Originally Posted by Jcse7en View Post
    Ok was being an idiot :-)

    Here's the result after submitting file to form

    Array ( ) ------- Array ( [file] => Array ( [name] => NTLInstr.mp3 [type] => [tmp_name] => [error] => 1 [size] => 0 ) ) Invalid file


    Thanks
    There we go... [error] => 1, that looks like the cause of problems!

    We do a quick google for php file upload error 1 : https://www.google.com/search?q=php+file+upload+error+1

    http://us1.php.net//manual/en/featur...oad.errors.php

    UPLOAD_ERR_INI_SIZE
    Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

    And there's the source of our problem! upload_max_filesize in your php.ini file is smaller than the size of the file you're uploading.

    You'll need to change this in php.ini or in .htaccess, ini_set() will not work for this setting.

    You can view the current limit via:

    PHP Code:
    echo ini_get('upload_max_filesize'); 
    I also noticed some other problems and unusual parts in your code:

    PHP Code:
    <?php
     
    // Show the page as text instead of HTML. Can be helpful in debugging
    header('Content-Type:text/plain');

    // Enable debug error reporting
    if (true) {
        
    error_reporting(E_ALL);
        
    ini_set("display_errors"1);
    }
    print_r($_POST);
    echo 
    "\n-------\n"// \n = new line
    print_r($_FILES);

     
    // Connects to your Database 
    mysql_connect("localhost""root""") or die(mysql_error()) ; 
    mysql_select_db("mydb") or die(mysql_error()) ; 

    if (((
    $_FILES["file"]["type"] == "audio/mp3")
    || (
    $_FILES["file"]["type"] == "audio/mp4")
    || (
    $_FILES["file"]["type"] == "audio/wav"))
    && (
    $_FILES["file"]["size"] < 1000000)) {
         if (
    $_FILES["file"]["error"] > 0) {
            echo 
    "Return Code: " $_FILES["file"]["error"] . "<br />";
        } else {
            echo 
    "Upload: " $_FILES["file"]["name"] . "<br />";
            echo 
    "Type: " $_FILES["file"]["type"] . "<br />";
            echo 
    "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
            echo 
    "Temp file: " $_FILES["file"]["tmp_name"] . "<br />";

            if (
    file_exists("upload/" $_FILES["file"]["name"])) {
                echo 
    $_FILES["file"]["name"] . " already exists. ";
            } else 
    // this seems unusual
            
    $mp3_name $_FILES["file"]["name"]; // this seems unusual
        
    $mp3_path "pload/$mp3_name"// should this be pload or upload?

        
    move_uploaded_file($_FILES["file"]["tmp_name"], $mp3_path);

        
    $sql "INSERT INTO 'music' SET name='$mp3_name', location'$mp3_path'"// this no variable cleaning is very dangerous, google SQL injection
        
    $result mysql_query($sql);
        if(
    $result) {
            echo 
    'MP3 Upload successfully';
        } else {
            echo 
    'ERROR: Upload Failed';
        }

        }
    } else {
        echo 
    "Invalid file";
    }
    ?>
    (1)
    and } else with no {} after it will run only the next line as part of the else, even if this is your intention it is best to use the {} for readability.
    (2)
    $mp3_path = "pload/$mp3_name";
    Should the folder anme be pload or upload?
    (3)
    PHP Code:
    $sql "INSERT INTO 'music' SET name='$mp3_name', location'$mp3_path'"// this no variable cleaning is very dangerous, google SQL injection
    $result mysql_query($sql); 
    Firstly, you really shouldn't be using mysql_query it is outdated and soon to be removed completely from PHP. You should instead use mysqli or PDO.

    Secondly, setting the location in the SQL is missing an = sign.

    Thirdly, you should never insert a variable directly into your sql as you did without cleaning, otherwise people can hack your database and your site and do really nasty stuff.

    Someone could send a file and tell the server that the file name was:

    hello', location='whatever'; DELETE FROM music; INSERT INTO 'music' SET name='

    Then the total code would become

    INSERT INTO 'music' SET name='hello', location='whatever'; DELETE FROM music; INSERT INTO 'music' SET name='aaa', location = '$mp3_path

    Which in many cases would also be valid, but would also delete everything in your music table. Google SQL injection for more info.

    If you were using mysqli, you could use:
    http://us1.php.net//manual/en/mysqli...ape-string.php

    If you were using PDO you could use:
    http://www.php.net/manual/en/pdostatement.bindparam.php

    Or something like that, I have a few classes in the middle which help me do all this dirty work these days so I'm a little out of experience with the particular details, but that's roughly it.

  8. #23
    Join Date
    May 2014
    Posts
    30
    Gravy this is good stuff!!!

    Thanks!!

  9. #24
    Join Date
    May 2014
    Posts
    30
    I have changed my code to make it more simpler and easier to read

    However I am now getting the following error

    Array ( ) ------- Array ( [name] => Array ( [name] => NTLInstr.mp3 [type] => audio/mp3 [tmp_name] => C:\xampp\tmp\php672A.tmp [error] => 0 [size] => 5112602 ) )

    Now I checked on Google and that error seems to mean the file was uploaded but this is not the case as the file doesn't appear in MySQL or the upload folder. Now I upped my maximum file upload size to 100mb (although I won't be uploading anything near that size) as well as the post_max_size and I'm still getting the above.

    Just really at a loss now, all the tutorials I've looked at suggest I'm doing everything right and the code seems correct as well.

    Below I've posted the html as well as the php to maybe see if there's a problem there.

    Thanks

    PHP Code:
    <?php 

    // Enable debug error reporting 
     
    if (true) { 
      
    error_reporting(E_ALL); 
      
    ini_set("display_errors"1); 
     } 
     
    print_r($_POST); 
    echo 
    "\n-------\n"// \n = new line 
     
    print_r($_FILES); 

     
    // Connects to your Database  
     
    mysql_connect("localhost""root""") or die(mysql_error()) ;  
     
    mysql_select_db("fxmas") or die(mysql_error()) ;  

    if(isset(
    $_POST['submit']))
    {
        
    $name $_FILES['file']['name'];
        
    $temp $_FILES['file']['tmp_name'];
        
        
    move_uploaded_file($temp,"uploaded/".$name);
        
    $location "http://localhost/xampp/htdocs/FXMAS/Upload/$name";
        
    mysql_query("INSERT INTO 'music' VALUE ('', '$name', '$location')");
    }

    ?>

    <!doctype html>

    <html lang="en">
    <head>
        <!--how browser interprets stuff-->
        <meta charset="utf-8" />
        <title>FXMAS</title>
        
        <link rel="stylesheet" href="main.css" />
        
    </head>
    <body id="up">
        <div id="big_wrapper">
        



        <header id="main_header">
        
            <h1></h1>
            <h4></h4>
        </header>
        <nav id="menu">
        <form method="get" action="/search" id="search">
      <input name="q" type="text" size="40" placeholder="Search..." />
    </form>
                <ul id=navlist>
                <li><a href="music.php" id="homenav">Music</a></li>
                <li><a href="fx.php" id="fxnav">FX</a></li>
                <li><a href="upload.php" id="upnav">Upload</a></li>
                <li><a href="forum.php" id="forumnav">Forum</a></li>
                <li><a href="reports.php" id="reportsnav">Reports</a></li>
                <li><a href="about.php" id="aboutnav">About</a></li>
            </ul>
        </nav>
        <form  id="upload" enctype="multipart/form-data" action="upload.php" method="POST"> 
            File: <input type="file" name = "name"><br> 
           <input type="submit" value="Upload"> 
        </form>
        
    <?php

    if(isset($_POST['submit']))
    {
        echo 
    "<br />".$name." has been uploaded ";
    }
    ?>

        <section>
            <article>
                <header>
                <hgroup> <!--when you have more than one header-->
                    <h1></h1>
                    <h2></h2>
                </hgroup>
                </header>
                <p></p>
                <footer>
                    <p></p>
                </footer>
            </article>
            
            <article>
                <header>
                <hgroup> <!--when you have more than one header-->
                    <h1></h1>
                    <h2></h2>
                </hgroup>
                </header>
                <p></p>
                <footer>
                    <p></p>
                </footer>
            </article>
        </section>
        
        <aside>
            <h4></h4>
            
        </aside>
        <footer>
            
        </footer>
        </div>
    </body>
    </html>

    <?php 

    // Enable debug error reporting 
     
    if (true) { 
      
    error_reporting(E_ALL); 
      
    ini_set("display_errors"1); 
     } 
     
    print_r($_POST); 
    echo 
    "\n-------\n"// \n = new line 
     
    print_r($_FILES); 

     
    // Connects to your Database  
     
    mysql_connect("localhost""root""") or die(mysql_error()) ;  
     
    mysql_select_db("fxmas") or die(mysql_error()) ;  

    if(isset(
    $_POST['submit']))
    {
        
    $name $_FILES['file']['name'];
        
    $temp $_FILES['file']['tmp_name'];
        
        
    move_uploaded_file($temp,"upload/".$name);
        
    $location "http://localhost/xampp/htdocs/FXMAS/upload/$name";
        
    mysql_query("INSERT INTO 'music' VALUE ('', '$name', '$location')");
    }

  10. #25
    Join Date
    May 2014
    Posts
    30
    Please ignore the php code at the very top it seems I got a little excited with my cutting and pasting ;-) it's just a duplication of the code at the end.

    Thanks

  11. #26
    Join Date
    May 2014
    Posts
    75
    There is no error:
    http://www.php.net//manual/en/featur...oad.errors.php

    [error] => 0
    UPLOAD_ERR_OK
    Value: 0; There is no error, the file uploaded with success.


    ======================

    Your problem here would be your sql. it should be VALUES not VALUE and the auto increment should be set to NULL.

    INSERT INTO 'music' VALUE ('', '$name', '$location')

    INSERT INTO 'music' VALUES (NULL, '$name', '$location')

    ======================

    Also, your code is still not safe. Do not use mysql_* functions. It can still be hacked now.

    Have a look at this example of how to do it better and more safely:

    http://www.phpeveryday.com/articles/...ment-P552.html

  12. #27
    Join Date
    May 2014
    Posts
    30
    Hey Gravy

    Hope you're well.

    Finally managed to get the file into the database and into my upload folder, yay!

    I have two issues that are currently stumping me.

    1. When I reload the page in web browser it adds a new entry to the database as well as a copy of the file in the upload folder
    - Why is this happening and how can I stop it
    - Shouldn't MYSQL recognise a duplicated entry or is it that something I need to add into the code

    2. In php you'll notice I have used a <select> tag with an <option> tag how do I get the entry into the relevant field in my database table

    One more thing actually
    3. I know I need an isset function but slightly confused as to where to add it

    The current code:

    Code:
    <!doctype html>
    
    <html lang="en">
    <head>
    	<!--how browser interprets stuff-->
    	<meta charset="utf-8" />
    	<title>FXMAS</title>
    	
    	<link rel="stylesheet" href="main.css" />
    	<style type="text/css"> 
    			#upload {position: absolute;
    					top: 260px;
    					left: 500px;
    					color: 	#FFAD33;
    					font-family: arial;
    					font-weight: bold;
    					font-size: 140%;
    					background: rgba(0, 0, 0, 0.5);}
    	</style>
    </head>
    <body id="up">
    	<div id="big_wrapper">
    	
    
    
    
    	<header id="main_header">
    	
    		<h1></h1>
    		<h4></h4>
    	</header>
    	<nav id="menu">
    	<form method="get" action="/search" id="search">
      <input name="q" type="text" size="40" placeholder="Search..." />
    </form>
    			<ul id=navlist>
    			<li><a href="music.php" id="homenav">Music</a></li>
    			<li><a href="fx.php" id="fxnav">FX</a></li>
    			<li><a href="upload.php" id="upnav">Upload</a></li>
    			<li><a href="forum.php" id="forumnav">Forum</a></li>
    			<li><a href="reports.php" id="reportsnav">Reports</a></li>
    			<li><a href="about.php" id="aboutnav">About</a></li>
    		</ul>
    	</nav>
    	<form  id="upload" enctype="multipart/form-data" action="upload.php" method="POST"> 
    		File: <input type="file" name = "Filename"><br />
    		Type: <select name="Type">
    					   <option value="music">Music</option>
    					   <option value="FX">FX</option>
    			  </select><br />
    								<input type="submit" value="Upload"> 
    	</form>
    
    
    	<section>
    		<article>
    			<header>
    			<hgroup> <!--when you have more than one header-->
    				<h1></h1>
    				<h2></h2>
    			</hgroup>
    			</header>
    			<p></p>
    			<footer>
    				<p></p>
    			</footer>
    		</article>
    		
    		<article>
    			<header>
    			<hgroup> <!--when you have more than one header-->
    				<h1></h1>
    				<h2></h2>
    			</hgroup>
    			</header>
    			<p></p>
    			<footer>
    				<p></p>
    			</footer>
    		</article>
    	</section>
    	
    	<aside>
    		<h4></h4>
    		
    	</aside>
    	<footer>
    		
    	</footer>
    	</div>
    </body>
    </html>
    PHP Code:
    <?php 

     
    //This is the directory where images will be saved
    $target "uploads/";
    $target $target basename$_FILES['Filename']['name']);

    //This gets all the other information from the form
    $Filename=basename$_FILES['Filename']['name']);
    $Location ="http://localhost/xampp/htdocs/FXMAS/uploads/$Filename";




    //Writes the Filename to the server
    if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
        
    //Tells you if its all ok
     
    "The file "basename$_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
        
    // Connects to your Database
        
    mysql_connect("localhost""root""") or die(mysql_error()) ;
        
    mysql_select_db("fxmas") or die(mysql_error()) ;

        
    //Writes the information to the database
        
    mysql_query("INSERT INTO music (name, location)
        VALUES ('
    $Filename', '$Location')") ;
    } else {
        
    //Gives and error if its not
       // echo "Sorry, there was a problem uploading your file.";
    }



    ?>

  13. #28
    Join Date
    May 2014
    Posts
    30
    Oh thanks as always

  14. #29
    Join Date
    May 2014
    Posts
    30
    Bump... ;-)

Thread Information

Users Browsing this Thread

There are currently 3 users browsing this thread. (0 members and 3 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles