Jump to content

Storing variable in MYSQL results in the word 'array'


Bottyz

Recommended Posts

hi all,

 

i'm attempting to use the file upload script by blueimp: https://github.com/blueimp/jQuery-File-Upload in order to upload and store images for an image gallery. I've added a mysql script to store a title for each image to retrieve when showing them in the gallery.

 

now my problem is that when I try to store the title all it stores (when looking through phpmyadmin) is the word 'array'. I've tried a few variations of trying to extract the information such as var_dump or printr and all I seem to manage to get out of it is string(5). I'm not great with my knowledge on arrays so if someone can offer any ideas on how to extract the title, that would be great, thanks!

Link to comment
Share on other sites

I'll post some of the code below, but I'm not 100% sure how it all works as JSON is involved (Which i'm only just getting familiar with), so please bear with me.

 

upload.html - client side where file upload is requested and form where title is entered by users.

 

<form id="fileupload" action="server/php/" method="POST" enctype="multipart/form-data">

<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-upload fade">
        <td class="preview"><span class="fade"></span></td>
        <td class="name"><span>{%=file.name%}</span></td>
        <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>

// my additional code here:
	<td class="caption"><label>Photo Title: <input name="title[]" required></label></td>
        {% if (file.error) { %}
            <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>

// end of my code
        {% } else if (o.files.valid && !i) { %}
            <td>
                <div class="progress progress-success progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="bar" style="width:0%;"></div></div>
            </td>
            <td class="start">{% if (!o.options.autoUpload) { %}
                <button class="btn btn-primary">
                    <i class="icon-upload icon-white"></i>
                    <span>{%=locale.fileupload.start%}</span>
                </button>
            {% } %}</td>
        {% } else { %}
            <td colspan="2"></td>
        {% } %}
        <td class="cancel">{% if (!i) { %}
            <button class="btn btn-warning">
                <i class="icon-ban-circle icon-white"></i>
                <span>{%=locale.fileupload.cancel%}</span>
            </button>
        {% } %}</td>
    </tr>
{% } %}
</script>

 

server/php/index.php - called by the form submission above (not sure if you need to see this part but thought it may help)

 


session_start();
error_reporting(E_ALL | E_STRICT);
require('upload.class.php');

$upload_handler = new UploadHandler();

header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Content-Disposition: inline; filename="files.json"');
header('X-Content-Type-Options: nosniff');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: X-File-Name, X-File-Type, X-File-Size');

switch ($_SERVER['REQUEST_METHOD']) {
    case 'OPTIONS':
        break;
    case 'HEAD':
    case 'GET':
        $upload_handler->get();
        break;
    case 'POST':
        if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
            $upload_handler->delete();
        } else {
            $upload_handler->post();
        }
        break;
    case 'DELETE':
        $upload_handler->delete();
        break;
    default:
        header('HTTP/1.1 405 Method Not Allowed');
}

 

server/phpupload.class.php - Stores the classes which are probably causing the issue. I've tried to crop out most of the non relevant code. I've marked my edited code so you can see what I've changed as originally this script had no sort of mysql connection.

 

class UploadHandler
{
    protected $options;

    function __construct($options=null) {
        $this->options = array(
            'script_url' => $this->getFullUrl().'/',
            'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/img/',
            'upload_url' => $this->getFullUrl().'/img/',
            'param_name' => 'files',
            // Set the following option to 'POST', if your server does not support
            // DELETE requests. This is a parameter sent to the client:
            'delete_type' => 'DELETE',
            // The php.ini settings upload_max_filesize and post_max_size
            // take precedence over the following max_file_size setting:
            'max_file_size' => null,
            'min_file_size' => 1,
            'accept_file_types' => '/\.(gif|jpe?g|png)$/i',
            // The maximum number of files for the upload directory:
            'max_number_of_files' => null,
            // Image resolution restrictions:
            'max_width' => null,
            'max_height' => null,
            'min_width' => 1,
            'min_height' => 1,
            // Set the following option to false to enable resumable uploads:
            'discard_aborted_uploads' => true,
            // Set to true to rotate images based on EXIF meta data, if available:
            'orient_image' => true,
            'image_versions' => array(
                // Uncomment the following version to restrict the size of
                // uploaded images. You can also add additional versions with
                // their own upload directories:
                'large' => array(
                    'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/img/',
                    'upload_url' => $this->getFullUrl().'/img/',
                    'max_width' => 1920,
                    'max_height' => 1200,
                    'jpeg_quality' => 95
                ),
                'thumbnail' => array(
                    'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/thumbs/',
                    'upload_url' => $this->getFullUrl().'/thumbs/',
                    'max_width' => 75,
                    'max_height' => 75
                )
            )
        );
        if ($options) {
            $this->options = array_replace_recursive($this->options, $options);
        }
    }

    protected function getFullUrl() {
        $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
      	return
    		($https ? 'https://' : 'http://').
    		(!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
    		(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
    		($https && $_SERVER['SERVER_PORT'] === 443 ||
    		$_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
    		substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
    }

    protected function get_file_object($file_name) {
        $file_path = $this->options['upload_dir'].$file_name;
        if (is_file($file_path) && $file_name[0] !== '.') {
            $file = new stdClass();
            $file->name = $file_name;
            $file->size = filesize($file_path);
            $file->url = $this->options['upload_url'].rawurlencode($file->name);
            foreach($this->options['image_versions'] as $version => $options) {
                if (is_file($options['upload_dir'].$file_name)) {
                    $file->{$version.'_url'} = $options['upload_url']
                        .rawurlencode($file->name);
                }
            }
            $this->set_file_delete_url($file);
            return $file;
        }
        return null;
    }

    protected function get_file_objects() {
        return array_values(array_filter(array_map(
            array($this, 'get_file_object'),
            scandir($this->options['upload_dir'])
        )));
    }

    protected function handle_file_upload($uploaded_file, $name, $size, $type, $error, $title) {

//My code:
	// connect to db to retrieve next file number
	include('../../../../../db/gallerypass.php');

	$idstmt = $mysqli->stmt_init();
	if ($idstmt = $mysqli->prepare("SELECT max(id) FROM gallery")){
		$idstmt->execute();
		$idstmt->bind_result($idnum);
		$idstmt->fetch();
		$idstmt->close();
	}
	// if query errors sends an email
	if ($mysqli->error) {
		try {   
			throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $mysqli->errno);   
		} catch(Exception $e ) {
			$mess = "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br>";
			$mess .= nl2br($e->getTraceAsString());
			$contact_email = "user@user.com";
			$message_sub = "Mysqli Query Error [uPFAIL]";
			$hdrs = "From: " . $contact_email . "\r\n";
			$hdrs .= "Reply-To: ". $contact_email . "\r\n";
			$hdrs .= "MIME-Version: 1.0\r\n";
			$hdrs .= "Content-Type: text/html; charset=UTF-8\r\n";
			mail($contact_email, $message_sub, $mess, $hdrs);
		}
		header("location: http://website.co.uk/");
		exit();
	}
	$mysqli->close();

	$ext = strtolower(substr(strrchr($name, '.'), 1));
	if ($ext == 'jpg') {
		$ext = 'jpeg';
	}
	$idnum++;
	$name = $idnum . '.' . $ext;
// End My Code

        $file = new stdClass();
        $file->name = $this->trim_file_name($idnum, $type, $index);
        $file->size = intval($size);
        $file->type = $type;
        if ($this->validate($uploaded_file, $file, $error, $index)) {
            $this->handle_form_data($file, $index);
            $file_path = $this->options['upload_dir'].$file->name;
            $append_file = !$this->options['discard_aborted_uploads'] &&
                is_file($file_path) && $file->size > filesize($file_path);
            clearstatcache();
            if ($uploaded_file && is_uploaded_file($uploaded_file)) {
                // multipart/formdata uploads (POST method uploads)
                if ($append_file) {
                    file_put_contents(
                        $file_path,
                        fopen($uploaded_file, 'r'),
                        FILE_APPEND
                    );
                } else {
                    move_uploaded_file($uploaded_file, $file_path);
                }
            } else {
                // Non-multipart uploads (PUT method support)
                file_put_contents(
                    $file_path,
                    fopen('php://input', 'r'),
                    $append_file ? FILE_APPEND : 0
                );
            }
            $file_size = filesize($file_path);
            if ($file_size === $file->size) {
            	if ($this->options['orient_image']) {
            		$this->orient_image($file_path);
            	}
                $file->url = $this->options['upload_url'].rawurlencode($file->name);
                foreach($this->options['image_versions'] as $version => $options) {
                    if ($this->create_scaled_image($file->name, $options)) {
                        if ($this->options['upload_dir'] !== $options['upload_dir']) {
                            $file->{$version.'_url'} = $options['upload_url']
                                .rawurlencode($file->name);
                        } else {
                            clearstatcache();
                            $file_size = filesize($file_path);
                        }
                    }
                }
            } else if ($this->options['discard_aborted_uploads']) {
                unlink($file_path);
                $file->error = 'abort';
            }
            $file->size = $file_size;
            $this->set_file_delete_url($file);
        }
// My Code:
	// connect to db to record file name & caption
	include('../../../../../db/gallerypass.php');

	$null = NULL;
	$address = $_SERVER['REMOTE_ADDR'];
	$recordimgstmt = $mysqli->stmt_init();
	if ($recordimgstmt->prepare("INSERT INTO gallery VALUES (?, ?, ?, ?)")) {
		$recordimgstmt->bind_param('isss', $null, $name, $title, $address);
		$recordimgstmt->execute();
		$recordimgstmt->close();
	}
	// if query errors sends an email
	if ($mysqli->error) {
		try {   
			throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $mysqli->errno);   
		} catch(Exception $e ) {
			$mess = "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br>";
			$mess .= nl2br($e->getTraceAsString());
			$contact_email = "user@user.com";
			$message_sub = "Mysqli Query Error [uAIMGDB]";
			$hdrs = "From: " . $contact_email . "\r\n";
			$hdrs .= "Reply-To: ". $contact_email . "\r\n";
			$hdrs .= "MIME-Version: 1.0\r\n";
			$hdrs .= "Content-Type: text/html; charset=UTF-8\r\n";
			mail($contact_email, $message_sub, $mess, $hdrs);
		}
		exit();
	}
	$mysqli->close();
// End My Code

        return $file;
    }

    public function get() {
        $file_name = isset($_REQUEST['file']) ?
            basename(stripslashes($_REQUEST['file'])) : null;
        if ($file_name) {
            $info = $this->get_file_object($file_name);
        } else {
            $info = $this->get_file_objects();
        }
        header('Content-type: application/json');
        echo json_encode($info);
    }

    public function post() {
        if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
            return $this->delete();
        }
        $upload = isset($_FILES[$this->options['param_name']]) ?
            $_FILES[$this->options['param_name']] : null;
        $info = array();
        if ($upload && is_array($upload['tmp_name'])) {
            // param_name is an array identifier like "files[]",
            // $_FILES is a multi-dimensional array:
            foreach ($upload['tmp_name'] as $index => $value) {
                $info[] = $this->handle_file_upload(
                    $upload['tmp_name'][$index],
                    isset($_SERVER['HTTP_X_FILE_NAME']) ?
                        $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
                    isset($_SERVER['HTTP_X_FILE_SIZE']) ?
                        $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
                    isset($_SERVER['HTTP_X_FILE_TYPE']) ?
                        $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
                    $upload['error'][$index],
// My code to pass the input title
	$_REQUEST['title']
// end of my code
                );
            }
        } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
            // param_name is a single object identifier like "file",
            // $_FILES is a one-dimensional array:
            $info[] = $this->handle_file_upload(
                isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
                isset($_SERVER['HTTP_X_FILE_NAME']) ?
                    $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ?
                        $upload['name'] : null),
                isset($_SERVER['HTTP_X_FILE_SIZE']) ?
                    $_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ?
                        $upload['size'] : null),
                isset($_SERVER['HTTP_X_FILE_TYPE']) ?
                    $_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ?
                        $upload['type'] : null),
                isset($upload['error']) ? $upload['error'] : null
            );
        }
        header('Vary: Accept');
        $json = json_encode($info);
        $redirect = isset($_REQUEST['redirect']) ?
            stripslashes($_REQUEST['redirect']) : null;
        if ($redirect) {
            header('Location: '.sprintf($redirect, rawurlencode($json)));
            return;
        }
        if (isset($_SERVER['HTTP_ACCEPT']) &&
            (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
            header('Content-type: application/json');
        } else {
            header('Content-type: text/plain');
        }
        echo $json;
    }



}

 

I also edited the main javascript file:

 

$('#fileupload').bind('fileuploadsubmit', function (e, data) {
	var inputs = data.context.find(':input');
	if (inputs.filter('[required][value=""]').first().focus().length) {
		return false;
	}
	data.formData = inputs.serializeArray();
});

 

 

As you can see from above I thought that js may be serializing the data so I did try to use unserialize() around the title variable but this didn't change anything either.

 

Anyone with a better understanding able to help? I'd very much appreciate it.

 

 

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.