Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

Why isn't this file uploading?

Here's my code:

...and here's what I get in return.

The permissions to the mp3 directory have been set to 777 so everything looks good from my perspective, but something is still missing.

Thoughts?
<?php
session_start();
if (!isset ($_SESSION['sv_email'])) {               
header("Location:contestants_login.php");exit();
}
$sv_email=$_SESSION['sv_email'];
include("carter.inc"); 
$cxn = mysqli_connect($host,$user,$password,$database)
or die ("couldn't connect to server");
$bruce="select * from registration where email = '$sv_email'";
$bruce_query = mysqli_query($cxn, $bruce)
or die("Couldn't execute query.");
$bruce_row = mysqli_fetch_assoc($bruce_query);
extract($bruce_row);
$the_contestant_id = $id;
if(isset($_FILES['mp3_file']['tmp_name'])&& !empty($_FILES['mp3_file']['tmp_name']))
{

//checking here to see if contestant is currently participating in Songwriting Competition

$poppy = "select * from registration where id = '$the_contestant_id'";
$poppy_query = mysqli_query($cxn, $poppy)
or die ("Couldn't execute query.");
$poppy_row = mysqli_fetch_assoc($poppy_query);
extract($poppy_row);
$mp3_today = date("Y-m-d"); 
$artist_songwriting_date = $songwriting_contest;

if($artist_songwriting_date <> "0000-00-00"){

//this contestant has declared that they want to be in the Songwriting Competition, now we have to find out if they're participating in contest currently underway
	$contest = "select * from songwriting_contest where start_date <= '$mp3_today' ORDER by start_date ASC LIMIT 1";
	$contest_query = mysqli_query($cxn, $contest)
	or die ("Couldnt' execute query.");
	$contest_count = mysqli_num_rows($contest_query);
	if($contest_count >0){
		//we've just determined that there is a contest currently underway with the above script, now we look to see if the start date for this particular contest is greater than the date the contestant entered. If it is, they're trying to adjust their song in the middle of the competition and they can't do that
		$contest_row = mysqli_fetch_assoc($contest_query)
		or die("Couldn't execute query.");
		extract($contest_row);
		$this_start_date = $start_date;
		//now we post the question
		if($artist_songwriting_date<=$this_start_date){
		header("Location:songwriting_mp3_prohibited.php");
		exit();
		}
		
	}
}

//end of Songwriting Competition code

 
$filecheck = basename($_FILES['mp3_file']['name']);
// this will return whatever is past the final . in the file name 
$ext = strtolower(substr($filecheck, strrpos($filecheck, '.') + 1));
 // check that the file extention is "mp3" 
if (strtolower($ext) == 'mp3') { 
 //here is where you're uploading the mp3 file based on the fact that the file type is, indeed, an mp3
 $userfile_name = (isset ($_FILES['mp3_file']['name']) ? $_FILES['mp3_file']['name'] : '');
 
 //If they've already agreed to the original music clause, then we don't need to see if there's a "Y" in the mp3_agreement box. Otherwise, we need to make sure it's checked.
 
	 if($contestant_song_permission=="0000-00-00")
	{   
		if(!$_POST['originals']=="Y"){  
		header("Location: mp3_agreement.php");
		exit();
		}
	}
	
	/*if($_POST['song_title']==""){
	header("Location: mp3_songtitle.php");
	exit();
	}*/

$filename = explode ('\\.', $userfile_name);
$good_ext = false;
$file_ext = '';
    if (strcmp (substr ($userfile_name, 0 - 4, 1), '.') === 0)
    {
      $good_ext = true;
      $file_ext = substr ($userfile_name, 0 - 3);
    }

    if (!$good_ext)
    {
      if (strcasecmp (substr ($userfile_name, 0 - 5, 1), '.') === 0)
      {
        $good_ext = true;
        $file_ext = substr ($userfile_name, 0 - 4);
      }
    }

    if (!$good_ext)
    {
      if (strcasecmp (substr ($userfile_name, 0 - 3, 1), '.') === 0)
      {
        $good_ext = true;
        $file_ext = substr ($userfile_name, 0 - 2);
      }
    }
}
$start_target = "../mp3/";
$target = $start_target . $the_contestant_id.'.'.$file_ext;
echo $target;
	if(!move_uploaded_file($_FILES['mp3_file']['name'], $target)) {
	echo "Nope";
	}

}
?>

Open in new window

Avatar of Bruce Gust
Bruce Gust
Flag of United States of America image

ASKER

And here's what I get when I do the "echo"...

../mp3/19913.mp3Nope

So the target, the filename and everything is exactly as it should be, yet it's not going anywhere. Why?
This is kindof a guess because I am without a editor ATM but should
$userfile_name = (isset ($_FILES['mp3_file']['name'])) ? $_FILES['mp3_file']['name'] : '');

Open in new window


BE

$userfile_name = (isset ($_FILES['mp3_file']['name'])) ? $_FILES['mp3_file']['name'] : ''; 

Open in new window

Hey, galexaner! No change. I tried the edit you suggested and got the same response.

What else?
SOLUTION
Avatar of Greg Alexander
Greg Alexander
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Did that do it?
Avatar of kumaranmca
kumaranmca

Hi,

Try copy() function its similar to move_upload_file(). Refer the below url...

http://php.net/manual/en/function.copy.php

I think it might be resolve your needs.



There is a security difference between using copy() and using move_uploaded_file().  Executive summary: Read the manual and choose the right function!

Here is a teaching example that shows how to upload files.  Please read it over - code, comments and man pages that are referenced.  Then post back with any specific questions about how file uploads work.  Note the file extensions near line 25 - you would want to make your own customization of this script at that point, and in the lines just above that point.
<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php


// PHP 5.1+  SEE http://us3.php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'RAY_junk';

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8192000';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME SCRIPT
    -->

    <form name="UploadForm" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    //    echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code    = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file = getcwd() . '/' . $uploads . '/' . $f_name . '.' . $f_type;
        $my_file     =                  $uploads . '/' . $f_name . '.' . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a href=\"$my_file\">See the file $my_file</a>\n";
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

OK, Ray, here's what I've got:

The code that I've been working with does work...on files smaller than 10MB. Anything larger than that, not only does it not upload, but the rest of the code that's updating data in the database is lost and you wind up erasing bio info, tour schedule...oh, yeah, it's a drag.

But the light at the end of the tunnel right now is that as long as you keep it under 10 MB, everything works great. I changed my ini file to this:

register_globals = off
allow_url_fopen = off

expose_php = Off
max_input_time = 0
variables_order = "EGPCS"
extension_dir = ./
upload_tmp_dir = /tmp
precision = 12
SMTP = relay-hosting.secureserver.net
url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=,fieldset="

memory_limit = 50M
post_max_size = 20M
file_uploads = On
upload_max_filesize = 20M


[Zend]
zend_extension=/usr/local/zo/ZendExtensionManager.so
zend_extension=/usr/local/zo/4_3/ZendOptimizer.so


When I run your example (thank you, by the way), I get no error messages, but the file has not uploaded. The only thing I can think of is maybe there's a time out dynamic that I'm not seeing, that I don't know how to correct.

Thoughts?


<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php


// PHP 5.1+  SEE http://us3.php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = '../mp3/';

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 15 MB
$max_file_size = '15192000';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
('mp3');
/*( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
)
;*/

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME SCRIPT
    -->

    <form name="upload_test.php" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    //    echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code    = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file = getcwd() . '/' . $uploads . '/' . $f_name . '.' . $f_type;
        $my_file     =                  $uploads . '/' . $f_name . '.' . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a href=\"$my_file\">See the file $my_file</a>\n";
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

Have you got this script installed on a server where I can try to use it to upload an MP3 file?  If not, please put it somewhere that we can test and post the URL.  If it ran at all, it created some browser output.  I would like to see that.  Also, if you have a phpinfo() script online, please post the URL of that, too.  Thanks.
Here's the URL: http://countryshowdown.com/Texaco/mp3_ray_script.php

The php ini file looks like this:


register_globals = off
allow_url_fopen = off

expose_php = Off
max_input_time = 0
variables_order = "EGPCS"
extension_dir = ./
upload_tmp_dir = /tmp
precision = 12
SMTP = relay-hosting.secureserver.net
url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=,fieldset="

memory_limit = 50M
post_max_size = 20M
file_uploads = On
upload_max_filesize = 20M


[Zend]
zend_extension=/usr/local/zo/ZendExtensionManager.so
zend_extension=/usr/local/zo/4_3/ZendOptimizer.so
Running it, I got this:

Results: File Upload

../mp3//ray_bogus.mp3 has been saved. 25 bytes uploaded.
See the file ../mp3//ray_bogus.mp3

A couple of things got my attention.  The file I uploaded was not an MP3 - it was just a little text string named RAY_bogus.mp3.  But the name was changed to lower case.  That might or might not matter.  IIRC linux file systems are case-sensitive.  And note the double slashes in the link to the file.  Not sure that makes any sense so you might want to drop one of those directory separators.
Hey, Ray!

Thanks for your time and I'm not surprised it worked, given your expertise. But, would you mind trying to upload something a little over 10MB. That's my dilemma at this point. The code that I have works, but if it's over 10MB, at that point, the script fails and I lose all of the data associated with that file (bio of contestant, name, everything...).

So, it's the size of the file that I think is a problem. Could you give it another whirl on your end and tell me what you think?
I'll see if I can find anything over 10MB...
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ray, after talking with godaddy I learned that my ini file needed to be renamed to php5.ini in order to be recognized in light of the version of php being recently upgraded. Once I made that change, the new parameters kicked in and I'm now good to go.

Thanks!
Interesting.  If we had seen the phpinfo() script we would have immediately known what the INI settings were and we would have seen that they were not taking effect from the INI file.  That would be a strong clue that might have saved some time that was spent testing around the perimeter of the problem.

Thanks for the points and good luck with the project, ~Ray