Jump to content

help with uploading a picture to MySQL DB


webguync

Recommended Posts

  • Replies 53
  • Created
  • Last Reply

Top Posters In This Topic

yea, I have a submit button now.

I made that change, but still no love.

 

The php page produces these warnings still

 

Connected successfully
Notice: Undefined index: myfile in flash_upload.php on line 24

Notice: Undefined offset: 0 in flash_upload.php on line 31

Notice: Undefined offset: 0 in flash_upload.php on line 40


Array
(
    [undefined] => Login.png
    [submit] => Send
)

Link to comment
Share on other sites

Hm, I'm at a loss.  I've copied your form code into an html page on my server, then posted it to a php file with just this:

 

<?
print_r($_FILES);
exit;
?>

 

and got this result:

 

Array

(

    [myfile] => Array

        (

            [name] => test.txt

            [type] => text/plain

            [tmp_name] => /tmp/phpk2krLk

            [error] => 0

            => 301

        )

 

)

 

 

Try putting that block of code at the top of flash_upload.php just to make sure that something in the rest of the file isn't redefining $_FILES.

Link to comment
Share on other sites

tried that and still the same result. Here is all of my PHP code again, in case I am missing something.

 

<?php
ini_set("display_errors","1");
ERROR_REPORTING(E_ALL);
session_start();
$db_user = "";
$db_pass = "";
$db = "";


$link = mysql_connect('localhost',$db_user,$db_pass);
$db_selected = mysql_select_db($db);
/*debugging*/

if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';

if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}

$uploadDir = dirname(__FILE__) . '/files/';
$uploadFile = $uploadDir . basename($_FILES['myfile']['name']);
Print_r ($_FILES);

if ($_POST['submit'] != '') {
    // 1. submitting the html form
    if (!isset($_GET['jqUploader'])) {
        // 1.a javascript off, we need to upload the file
        if (move_uploaded_file ($_FILES[0]['tmp_name'], $uploadFile)) {
            // delete the file
            // @unlink ($uploadFile);
            $html_body = '<h1>File successfully uploaded!</h1><pre>';
            $html_body .= print_r($_FILES, true);
            $html_body .= '</pre>';
        } else {
            $html_body = '<h1>File upload error!</h1>';

            switch ($_FILES[0]['error']) {
                case 1:
                    $html_body .= 'The file is bigger than this PHP installation allows';
                    break;
                case 2:
                    $html_body .= 'The file is bigger than this form allows';
                    break;
                case 3:
                    $html_body .= 'Only part of the file was uploaded';
                    break;
                case 4:
                    $html_body .= 'No file was uploaded';
                    break;
                default:
                    $html_body .= 'unknown errror';
            }
            $html_body .= 'File data received: <pre>';
            $html_body .= print_r($_FILES, true);
            $html_body .= '</pre>';
        }
        $html_body = '<h1>Full form</h1><pre>';
        $html_body .= print_r($_POST, true);
        $html_body .= '</pre>';
    } else {
        // 1.b javascript on, so the file has been uploaded and its filename is in the POST array
        $html_body = '<h1>Form posted!</h1><p>Error:<pre>';
        $html_body .= print_r($_POST, false);
        $html_body .= '</pre>';
    }
    myHtml($html_body);
} else {
    if ($_GET['jqUploader'] == 1) {
        // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        // 2. performing jqUploader flash upload
        if ($_FILES['myfile']['name']) {
           if (move_uploaded_file ($_FILES['myfile']['tmp_name'], $uploadFile)) {
                $statement = "insert into Profile_Photos (filename) values ('{$uploadFile}')";
                echo "<P>".$statement;
                mysql_query($statement);
                echo "<P>".mysql_error();
                // delete the file
                //  @unlink ($uploadFile);
                return $uploadFile;
            }
        } else {
            if ($_FILES['myfile']['error']) {
                return $_FILES['myfile']['error'];
            }
        }
    }
}
// /////////////////// HELPER FUNCTIONS
function myHtml($bodyHtml)
{

    ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jqUploader demo - Result</title>
<link rel="stylesheet" type="text/css" media="screen" href="style.css"/>
</head>
<body>
<?php echo $bodyHtml;

    ?>
</body>
</html>
<?php
}

?>

Link to comment
Share on other sites

So when you posted to the file that only printed out the $_FILES array what did you get?  Just a blank page?

 

At the very top, before your opening "<?", put this block:

 

<?
echo "Post Data:<br>";
print_r($_POST);
echo "File Data:</br>";
print_r($_FILES);
exit;
?>

 

You've got so many print_r's in that code, and what's being printed appears to be the $_POST variable and not the $_FILES variable, so use that - which will stop and not execute any of the code afterward - to see what exactly is ending up at the server.

Link to comment
Share on other sites

there is some JS involved (JQuery), which is involved with displaying the file name when you upload and also a progress bar for the upload. Posting JS below to see if there is something I need to change there.

 

/**
* jqUploader (http://www.pixeline.be/experiments/jqUploader/)
* A jQuery plugin to replace html-based file upload input fields with richer flash-based upload progress bar UI.
*
* Version 1.0.2.2
* September 2007
*
* Copyright (c) 2007 Alexandre Plennevaux (http://www.pixeline.be)
* Dual licensed under the MIT and GPL licenses.
* http://www.opensource.org/licenses/mit-license.php
* http://www.opensource.org/licenses/gpl-license.php
*
* using plugin "Flash" by Luke Lutman (http://jquery.lukelutman.com/plugins/flash)
*
* IMPORTANT:
* The packed version of jQuery breaks ActiveX control
* activation in Internet Explorer. Use JSMin to minifiy
* jQuery (see: http://jquery.lukelutman.com/plugins/flash#activex).
*
**/
jQuery.fn.jqUploader = function(options) {
    return this.each(function(index) {
        var $this = jQuery(this);
	// fetch label value if any, otherwise set a default one
	var $thisForm =  $this.parents("form");
	var $thisInput = $("input[@type='file']",$this);
	var $thisLabel = $("label",$this);
	var containerId = $this.attr("id") || 'jqUploader-'+index;
	var startMessage = ($thisLabel.text() =='') ? 'Please select a file' : $thisLabel.text();
	// get form action attribute value as upload script, appending to it a variable telling the script that this is an upload only functionality
	var actionURL = $thisForm.attr("action");
	// adds a var setting jqUploader to 1, so you can use it for serverside processing
	var prepender = (actionURL.lastIndexOf("?") != -1) ? "&": "?";
	actionURL = actionURL+prepender+'jqUploader=1';
	// check if max file size is set in html form
	var maxFileSize = $("input[@name='MAX_FILE_SIZE']", $(this.form)).val();
	var opts = jQuery.extend({
			width:320,
			height:85,
			version: 8, // version 8+ of flash player required to run jqUploader
			background: 'FFFFFF', // background color of flash file
			src:    'jqUploader.swf',
			uploadScript:     actionURL,
			afterScript:      null, // if this is empty, jqUploader will replace the upload swf by a hidden input element
			varName:	        $thisInput.attr("name"),  //this holds the variable name of the file input field in your html form
			allowedExt:	      '*.jpg; *.jpeg; *.png', // allowed extensions
			allowedExtDescr:  'Images (*.jpg; *.jpeg; *.png)',
			params:           {menu:false},
			flashvars:        {},
			hideSubmit:       true,
			barColor:		      '336',
			maxFileSize:      maxFileSize,
			startMessage:     startMessage,
			errorSizeMessage: 'File is too big!',
			validFileMessage: 'now click Upload to proceed',
			progressMessage: 'Please wait, uploading ',
			endMessage:    'You\'re all done'
	}, options || {}
	);
	// disable form submit button
	if (opts.hideSubmit==true) {
		$("*[@type='submit']",this.form).hide();
	}
	// THIS WILL BE EXECUTED IN THE USECASE THAT THERE IS NO REDIRECTION TO BE DONE AFTER UPLOAD
	TerminateJQUploader = function(containerId,filename,varname){
		$this= $('#'+containerId).empty();
		$this.text('').append('<span style="color:#036">Upload of <strong>'+filename+'</strong> finished! )</span><input name="'+varname+'" type="hidden" id="'+varname+'" value="'+filename+'"/>');
		var myForm = $this.parents("form");
		myForm.submit(function(){return true});
		$("*[@type='submit']",myForm).show();
	}
	var myParams = '';
	for (var p in opts.params){
			myParams += p+'='+opts.params[p]+',';
	}
	myParams = myParams.substring(0, myParams.length-1);
	// this function interfaces with the jquery flash plugin
	jQuery(this).flash(
	{
		src: opts.src,
		width: opts.width,
		height: opts.height,
		id:'movie_player-'+index,
		bgcolor:'#'+opts.background,
		flashvars: {
			containerId: containerId,
			uploadScript: opts.uploadScript,
			afterScript: opts.afterScript,
			allowedExt: opts.allowedExt,
			allowedExtDescr: opts.allowedExtDescr,
			varName :  opts.varName,
			barColor : opts.barColor,
			maxFileSize :opts.maxFileSize,
			startMessage : opts.startMessage,
			errorSizeMessage : opts.errorSizeMessage,
			validFileMessage : opts.validFileMessage,
			progressMessage : opts.progressMessage,
			endMessage: opts.endMessage
		},
		params: myParams
	},
	{
		version: opts.version,
		update: false
	},
		function(htmlOptions){
			var $el = $('<div id="'+containerId+'" class="flash-replaced"><div class="alt">'+this.innerHTML+'</div></div>');
				 $el.prepend($.fn.flash.transform(htmlOptions));
				 $('div.alt',$el).remove();
				 $(this).after($el).remove();
		}
	);
});
};

/**
* Flash (http://jquery.lukelutman.com/plugins/flash)
* A jQuery plugin for embedding Flash movies.
* 
* Version 1.0
* November 9th, 2006
*
* Copyright (c) 2006 Luke Lutman (http://www.lukelutman.com)
* Dual licensed under the MIT and GPL licenses.
* http://www.opensource.org/licenses/mit-license.php
* http://www.opensource.org/licenses/gpl-license.php
* 
* Inspired by:
* SWFObject (http://blog.deconcept.com/swfobject/)
* UFO (http://www.bobbyvandersluis.com/ufo/)
* sIFR (http://www.mikeindustries.com/sifr/)
* 
* IMPORTANT: 
* The packed version of jQuery breaks ActiveX control
* activation in Internet Explorer. Use JSMin to minifiy
* jQuery (see: http://jquery.lukelutman.com/plugins/flash#activex).
*
**/ 
;(function(){

var $$;

/**
* 
* @desc Replace matching elements with a flash movie.
* @author Luke Lutman
* @version 1.0.1
*
* @name flash
* @param Hash htmlOptions Options for the embed/object tag.
* @param Hash pluginOptions Options for detecting/updating the Flash plugin (optional).
* @param Function replace Custom block called for each matched element if flash is installed (optional).
* @param Function update Custom block called for each matched if flash isn't installed (optional).
* @type jQuery
*
* @cat plugins/flash
* 
* @example $('#hello').flash({ src: 'hello.swf' });
* @desc Embed a Flash movie.
*
* @example $('#hello').flash({ src: 'hello.swf' }, { version: 8 });
* @desc Embed a Flash 8 movie.
*
* @example $('#hello').flash({ src: 'hello.swf' }, { expressInstall: true });
* @desc Embed a Flash movie using Express Install if flash isn't installed.
*
* @example $('#hello').flash({ src: 'hello.swf' }, { update: false });
* @desc Embed a Flash movie, don't show an update message if Flash isn't installed.
*
**/
$$ = jQuery.fn.flash = function(htmlOptions, pluginOptions, replace, update) {

// Set the default block.
var block = replace || $$.replace;

// Merge the default and passed plugin options.
pluginOptions = $$.copy($$.pluginOptions, pluginOptions);

// Detect Flash.
if(!$$.hasFlash(pluginOptions.version)) {
	// Use Express Install (if specified and Flash plugin 6,0,65 or higher is installed).
	if(pluginOptions.expressInstall && $$.hasFlash(6,0,65)) {
		// Add the necessary flashvars (merged later).
		var expressInstallOptions = {
			flashvars: {  	
				MMredirectURL: location,
				MMplayerType: 'PlugIn',
				MMdoctitle: jQuery('title').text() 
			}					
		};
	// Ask the user to update (if specified).
	} else if (pluginOptions.update) {
		// Change the block to insert the update message instead of the flash movie.
		block = update || $$.update;
	// Fail
	} else {
		// The required version of flash isn't installed.
		// Express Install is turned off, or flash 6,0,65 isn't installed.
		// Update is turned off.
		// Return without doing anything.
		return this;
	}
}

// Merge the default, express install and passed html options.
htmlOptions = $$.copy($$.htmlOptions, expressInstallOptions, htmlOptions);

// Invoke $block (with a copy of the merged html options) for each element.
return this.each(function(){
	block.call(this, $$.copy(htmlOptions));
});

};
/**
*
* @name flash.copy
* @desc Copy an arbitrary number of objects into a new object.
* @type Object
* 
* @example $$.copy({ foo: 1 }, { bar: 2 });
* @result { foo: 1, bar: 2 };
*
**/
$$.copy = function() {
var options = {}, flashvars = {};
for(var i = 0; i < arguments.length; i++) {
	var arg = arguments[i];
	if(arg == undefined) continue;
	jQuery.extend(options, arg);
	// don't clobber one flash vars object with another
	// merge them instead
	if(arg.flashvars == undefined) continue;
	jQuery.extend(flashvars, arg.flashvars);
}
options.flashvars = flashvars;
return options;
};
/*
* @name flash.hasFlash
* @desc Check if a specific version of the Flash plugin is installed
* @type Boolean
*
**/
$$.hasFlash = function() {
// look for a flag in the query string to bypass flash detection
if(/hasFlash\=true/.test(location)) return true;
if(/hasFlash\=false/.test(location)) return false;
var pv = $$.hasFlash.playerVersion().match(/\d+/g);
var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
for(var i = 0; i < 3; i++) {
	pv[i] = parseInt(pv[i] || 0);
	rv[i] = parseInt(rv[i] || 0);
	// player is less than required
	if(pv[i] < rv[i]) return false;
	// player is greater than required
	if(pv[i] > rv[i]) return true;
}
// major version, minor version and revision match exactly
return true;
};
/**
*
* @name flash.hasFlash.playerVersion
* @desc Get the version of the installed Flash plugin.
* @type String
*
**/
$$.hasFlash.playerVersion = function() {
// ie
try {
	try {
		// avoid fp6 minor version lookup issues
		// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
		var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
		try { axo.AllowScriptAccess = 'always';	} 
		catch(e) { return '6,0,0'; }				
	} catch(e) {}
	return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
// other browsers
} catch(e) {
	try {
		if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
			return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
		}
	} catch(e) {}		
}
return '0,0,0';
};
/**
*
* @name flash.htmlOptions
* @desc The default set of options for the object or embed tag.
*
**/
$$.htmlOptions = {
height: 240,
flashvars: {},
pluginspage: 'http://www.adobe.com/go/getflashplayer',
src: '#',
type: 'application/x-shockwave-flash',
width: 320		
};
/**
*
* @name flash.pluginOptions
* @desc The default set of options for checking/updating the flash Plugin.
*
**/
$$.pluginOptions = {
expressInstall: false,
update: true,
version: '6.0.65'
};
/**
*
* @name flash.replace
* @desc The default method for replacing an element with a Flash movie.
*
**/
$$.replace = function(htmlOptions) {
this.innerHTML = '<div class="alt">'+this.innerHTML+'</div>';
jQuery(this)
	.addClass('flash-replaced')
	.prepend($$.transform(htmlOptions));
};
/**
*
* @name flash.update
* @desc The default method for replacing an element with an update message.
*
**/
$$.update = function(htmlOptions) {
var url = String(location).split('?');
url.splice(1,0,'?hasFlash=true&');
url = url.join('');
var msg = '<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';
this.innerHTML = '<span class="alt">'+this.innerHTML+'</span>';
jQuery(this)
	.addClass('flash-update')
	.prepend(msg);
};
/**
*
* @desc Convert a hash of html options to a string of attributes, using Function.apply(). 
* @example toAttributeString.apply(htmlOptions)
* @result foo="bar" foo="bar"
*
**/
function toAttributeString() {
var s = '';
for(var key in this)
	if(typeof this[key] != 'function')
		s += key+'="'+this[key]+'" ';
return s;		
};
/**
*
* @desc Convert a hash of flashvars to a url-encoded string, using Function.apply(). 
* @example toFlashvarsString.apply(flashvarsObject)
* @result foo=bar&foo=bar
*
**/
function toFlashvarsString() {
var s = '';
for(var key in this)
	if(typeof this[key] != 'function')
		s += key+'='+encodeURIComponent(this[key])+'&';
return s.replace(/&$/, '');		
};
/**
*
* @name flash.transform
* @desc Transform a set of html options into an embed tag.
* @type String 
*
* @example $$.transform(htmlOptions)
* @result <embed src="foo.swf" ... />
*
* Note: The embed tag is NOT standards-compliant, but it 
* works in all current browsers. flash.transform can be
* overwritten with a custom function to generate more 
* standards-compliant markup.
*
**/
$$.transform = function(htmlOptions) {
htmlOptions.toString = toAttributeString;
if(htmlOptions.flashvars) htmlOptions.flashvars.toString = toFlashvarsString;
return '<embed ' + String(htmlOptions) + '/>';		
};

/**
*
* Flash Player 9 Fix (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
*
**/
if (window.attachEvent) {
window.attachEvent("onbeforeunload", function(){
	__flash_unloadHandler = function() {};
	__flash_savedUnloadHandler = function() {};
});
}

})();

Link to comment
Share on other sites

Try killing the javascript and see if the form submits ok without it.  I'll bet it will.  You'll probably need to trace through that code to see what it's doing and why it's not working, but it's somehow converting the file into an input named "undefined" with the file's filename when the form is submitted - and the file is never actually getting submitted.  Is this a form submission script that you got from somewhere or did you write it yourself?  The reason I ask is that doing the progress bar upload with AJAX is pretty hairy - best to get your form working without the javascript, then try to adapt it to try to get the progress bar.

Link to comment
Share on other sites

Just a recommendation, but if you are having fundamental problems getting your php upload processing script to work, test it with a simple traditional HTML form first. Only add extras like javascript/flash AFTER you have completely tested and gotten the server side script working the way you want.

Link to comment
Share on other sites

ok, I am trying with just the HTML/PHP and no JS.

 

The output from print_r is this.

Post Data:
Array ( [submit] => Send ) File Data:
Array ( [myfile] => Array ( [name] => CIMG0505.JPG [type] => image/jpeg [tmp_name] => /var/tmp/phpgRUJyR [error] => 0 [size] => 1319406 ) ) 

 

the file doesn't get uploaded in the files directory though and the file path isn't submitted into the DB either.

Link to comment
Share on other sites

Ok, go back and try to understand the error messages.  They're designed to be human-readable. 

 

Notice: Undefined offset: 0 in flash_upload.php on line 32

 

Notice:  This is the error LEVEL.  A notice is less severe than a warning or an actual error.

 

Undefined offset:  You are using an array, and you are trying to access an offset that doesn't exist.

 

0:  The offset you're using.  Look for the zero in your code.

 

in flash_upload.php on line 32:  The location of the error.

 

 

 

 

You pasted code that contains an array access using the number zero on those lines.  That's the problem.  The array that you expect to have an element zero doesn't have one. Print_r, find out what it does have.  Find out which of your assumptions are wrong, and why.

 

jdavidbakr already gave you the answer, this is just general advice for debugging.  You could have solved all your problems yourself if you had turned on error_reporting and understood the messages.

 

-Dan

Link to comment
Share on other sites

sorry, I missed the last post by - jdavidbakr.

 

I changed to $_FILES['myfile'] and the upload works but the path to the file name to the filename isn't getting submitted into the DB. I tested the connection and no problems there. I think the Query should be echoing out on the flash_upload page but it's not. Any reasons why?

 

if (move_uploaded_file ($_FILES['myfile']['tmp_name'], $uploadFile)) {
                $statement = "insert into Profile_Photos (filename) values ('{$uploadFile}')";
                echo "<P>".$statement;
                mysql_query($statement);
                echo "<P>".mysql_error();

 

Link to comment
Share on other sites

print what these lines echoing

if (move_uploaded_file ($_FILES['myfile']['tmp_name'], $uploadFile)) {
                $statement = "insert into Profile_Photos (filename) values ('{$uploadFile}')";
                echo "<P>".$statement;
                mysql_query($statement);
                echo "<P>".mysql_error();

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.