Dear all,
I am developing a website which can upload photos and also uploading Name, Descrptions etc using one form and one "submit" button.
I found this below:
http://plugins.krajee.com/file-advanced-usage-demo#comments

The Example has some codes but I am not sure how to put it into a HTML Form and submit to my server folder and also submit to MYSQL.
I copied the codes and save as HTML but it is not showing like the Example give.

Anyone can help me on this? really appreciate any help.

Thanks.

Recommended Answers

All 18 Replies

Member Avatar for diafol

Dear Liang. if you don't post the code you're using, how do you expect us to know what's wrong? Posting a link to somebody else's code is not the same thing. What errors do you get?

Perhaps this would be useful? although it deals with PHP, it is relevant to general programming questions too.
pritaeas' "Read This" for posting PHP related questions

Hi Diafol,
My codes:

<html>
<head>
<title>TestPage</title>
  <link rel="stylesheet" href="/Testing/bootstrap/3.3.5/css/bootstrap.min.css"> 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
  <script src="/Testing/bootstrap/3.3.5/js/bootstrap.min.js"></script> 
</head>
<body>
<label class="control-label">Planets and Satellites</label>
<form method="POST" action="image-upload.php">
<input id="input-24" type="file" multiple=true class="file-loading">
</form>
<?php include("img-upload.php"); 
?>
<script>
$(document).on('ready', function() {
    $("#input-24").fileinput({
        initialPreview: [
            '<img src="/images/moon.jpg" class="file-preview-image" alt="The Moon" title="The Moon">',
            '<img src="/images/earth.jpg" class="file-preview-image" alt="The Earth" title="The Earth">'
        ],
        overwriteInitial: false,
        maxFileSize: 100,
        initialCaption: "The Moon and the Earth"
    });
});
</script>

</body>
<html>

I am not too sure how the codes work. Sorry, I am very new to this Java script and bootstrap and php thing.
I want to using Javascript to upload images because it is faster and it can show the preview.

The website I am refering to is: http://plugins.krajee.com/file-advanced-usage-demo#advanced-example-1

Which I do not understand how to apply it to a wbepage.

Thanks

Member Avatar for diafol

Where is the fileinput.js file referenced? You can't use the plugin unless you download the file from that site and reference it in the head section below the bootstrap.js.

Dear Diafol,
I have managed to make it work. Is the "form" correct? I am using my own PHP script for the upload.

<html>
<head>
<title>TestPage</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
<link href="http://plugins.krajee.com/assets/prod/all-krajee.css" rel="stylesheet">
<link href="http://plugins.krajee.com/assets/478e4822/css/fileinput.min.css" rel="stylesheet">
<script src="http://plugins.krajee.com/assets/478e4822/js/fileinput.min.js"></script>
</head>
<body>
<label class="control-label">Upload Image</label>
<form method="POST" action="image-upload.php"  enctype="multipart/form-data">
<input id="input-24" type="file" multiple=true class="file-loading">
</form>
<?php include("img-upload.php"); 
?>
<script>
$(document).on('ready', function() {
    $("#input-24").fileinput({
        initialPreview: [

        ],
        overwriteInitial: false,
        maxFileSize: 100,
        initialCaption: "No images selected"
    });
});
</script>
</body>
<html>

My image-upload.php:

<?php
error_reporting(0);
$change="";
$abc="";
 define ("MAX_SIZE","400");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }
 $errors=0;
  $connection = mysql_connect("","","");
  if (!$connection) {
    die("Database connection failed: " . mysql_error());
  }
  $db_select = mysql_select_db("yourdbname",$connection);
  if (!$db_select) {
    die("Database selection failed: " . mysql_error());
  }

  $slike = array(file, file1, file2, file3, file4);
  if($_SERVER["REQUEST_METHOD"] == "POST")
 {
  $filearray = array();
  $filearray1 = array();
  $k=0;
  foreach($slike as $slika){
  $image =$_FILES[$slika]["name"];
  $uploadedfile = $_FILES[$slika]['tmp_name'];
  if ($image)
  {
    $filename = stripslashes($_FILES[$slika]['name']);
      $extension = getExtension($filename);
    $extension = strtolower($extension);
 if (($extension != "jpg") && ($extension != "jpeg") &&
        ($extension != "png") && ($extension != "gif"))
    {
      $change='<div class="msgdiv">Unknown Image extension </div> ';
      $errors=1;
    }
    else
    {
 $size=filesize($_FILES[$slika]['tmp_name']);
if ($size > MAX_SIZE*1024)
{
  $change='<div class="msgdiv">You have exceeded the size limit!</div> ';
  $errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES[$slika]['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES[$slika]['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
echo $scr;
list($width,$height)=getimagesize($uploadedfile);
$newwidth=600;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=130;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
$image_name=(time()+$k).'.'.$extension;
$filename = "images/". $image_name;
$filename1 = "images/small_". $image_name;
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
$filearray[$k]= $filename;
$filearray1[$k]= $filename1;
$k++;

//The if below is to confirm that the third item is available, then only fill in the database.
if ($filearray[2]) {
  mysql_query("Insert into tbl_user set user_id='2',
 ap_id='2',big='$filearray[0]',small='$filearray1[0]',big1='$filearray[1]',small1='$filearray1[1]',big2='$filearray[2]',small2='$filearray1[2]' ", $connection);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}


}}
}
}
if(isset($_FILES['Submit']) && !$errors)
 {
    $change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
 }
?>
Member Avatar for diafol

You are using deprecated code (mysql functions) - see my tutorial for alternatives: DW Tutorial: Common Issues with MySQL and PHP .

Also, get the file extension using pathinfo() not the DIY method.

Dear Diafol,
You are right. This codes will be outdated soon. I am having headache to convert it into PDO or Myqsli code.
"Also, get the file extension using pathinfo() not the DIY method."
Is it possible to give me example how to use pathifo() in my php code?

Thanks

Member Avatar for diafol
$ext = pathinfo($filename, PATHINFO_EXTENSION);

PDO is really easy - the hardest part is remembering the conenction string!

$pdo = new PDO("mysql:host=localhost,dbname=mydb","root","password");

$stmt = $pdo->prepare(Insert into tbl_user (user_id, ap_id, big, small, big1, small1, big2, small2) VALUES (?,?,?,?,?,?,?,?));
$stmt->execute([2,2,$filearray[0],$filearray1[0],$filearray[1],$filearray1[1],$filearray[2],$filearray1[2]]);

Done. No need for any escaping / sanitizing.

Dear Diafol,
The VALUES (?,?,?,?,?,?,?,?), this is the actual code? No need make changes?

Can this be used for mysql? Or, my server needs to upgrade the mysql to newer version?

Thanks

Dear Diafol,
From your codes, I have combined into my own codes as shown below:

<?php
error_reporting(0);
$change="";
$abc="";
 define ("MAX_SIZE","400");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }
 $errors=0;
  $connection = mysql_connect("","","");
  if (!$connection) {
    die("Database connection failed: " . mysql_error());
  }
  $db_select = mysql_select_db("yourdbname",$connection);
  if (!$db_select) {
    die("Database selection failed: " . mysql_error());
  }
  $slike = array(file, file1, file2, file3, file4);
  if($_SERVER["REQUEST_METHOD"] == "POST")
 {
  $filearray = array();
  $filearray1 = array();
  $k=0;
  foreach($slike as $slika){
  $image =$_FILES[$slika]["name"];
  $uploadedfile = $_FILES[$slika]['tmp_name'];
  if ($image)
  {
    $filename = stripslashes($_FILES[$slika]['name']);
      $extension = getExtension($filename);
    $extension = strtolower($extension);
 if (($extension != "jpg") && ($extension != "jpeg") &&
        ($extension != "png") && ($extension != "gif"))
    {
      $change='<div class="msgdiv">Unknown Image extension </div> ';
      $errors=1;
    }
    else
    {
 $size=filesize($_FILES[$slika]['tmp_name']);
if ($size > MAX_SIZE*1024)
{
  $change='<div class="msgdiv">You have exceeded the size limit!</div> ';
  $errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES[$slika]['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES[$slika]['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
echo $scr;
list($width,$height)=getimagesize($uploadedfile);
$newwidth=600;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=130;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
$image_name=(time()+$k).'.'.$extension;
$filename = "images/". $image_name;
$filename1 = "images/small_". $image_name;
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
$filearray[$k]= $filename;
$filearray1[$k]= $filename1;
$k++;
//The if below is to confirm that the third item is available, then only fill in the database.
if ($filearray[2]) {

//Diafol's code
$stmt = $pdo->prepare(Insert into tbl_user (user_id, ap_id, big, small, big1, small1, big2, small2) VALUES (?,?,?,?,?,?,?,?));
$stmt->execute([2,2,$filearray[0],$filearray1[0],$filearray[1],$filearray1[1],$filearray[2],$filearray1[2]]);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}}
}
}
if(isset($_FILES['Submit']) && !$errors)
 {
    $change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
 }
?>

I am not sure whether I did it correctly or not. The "$pdo = new PDO("mysql:host=localhost,dbname=mydb","root","password");" I am not sure which part of my codes need to be replaced.

Thanks

Member Avatar for diafol

I'd probably do something like this, in order to keep it flexible. I'd most likely create a class though.

<?php

//SET DEFAULTS
//error_reporting(0);
$change="";
$abc="";
$errors=0;
$allowedExtensions = ['png','jpg','jpeg','gif'];
$key = 'myimage';
$setWidths = [600, 130];
$uploadDirectory = ['upload/','upload/'];
$prefix = ['','small_'];
$quality = [100,100];
$fieldListArray = ['big','small','big1','small1','big2','small2'];
$newFilenames = [];

define ("MAX_SIZE","400"); //assuming kb


//FUCNTIONS
//Check and return file type
function validate_extension($file, $allowedExtensions) {
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    if(in_array($ext, $allowedExtensions)) {
        if ($ext == 'jpg') $ext = 'jpeg';
        return $ext;
    }
    return false;
}

//Change array structure
function transpose($files)
{
    $result = [];
    foreach ($files as $key1 => $value1)
        foreach ($value1 as $key2 => $value2)
            $result[$key2][$key1] = $value2;
    return $result;
}

//Check size allowed
function check_size($file)
{
    return $file['size'] / 1024 <= MAX_SIZE;
}


//MAIN ROUTINE

if(isset($_FILES[$key]))
{
    //Apply error handling to this
    $pdo = new PDO("mysql:host=localhost;dbname=dwtest","root","mypassword");

    if(is_array($_FILES[$key]['name']))
    {
        $files = transpose($_FILES[$key]); //change ridiculous multiple files array structure
    }else{
        $files = (array) $_FILES[$key];
    }

    $i = 0;
    foreach($files as $file)
    {
        $ext = validate_extension($file['name'], $allowedExtensions);
        if($ext && check_size($file)) {
            $stored = $file['tmp_name'];
            $function = 'imagecreatefrom' . $ext;
            $src = $function($stored);
            list($w, $h) = getimagesize($stored);

            for ($j = 0; $j < count($setWidths); $j++)
            {
                echo 'Inner' . $j . '<br/>';
                $w2 = $setWidths[$j];
                $h2 = $h / $w * $w2;
                $tmp = imagecreatetruecolor($w2, $h2);
                imagecopyresampled($tmp, $src, 0, 0, 0, 0, $w2, $h2, $w, $h);
                $image_name = (time() . $i) . '.' .$ext;
                $filename = $uploadDirectory[$j] . $prefix[$j] . $image_name;
                $function = 'image' . $ext;
                if($ext == 'gif' || !isset($quality[$j]) || is_null($quality[$j]))
                {
                    $function($tmp, $filename);
                }else {
                    $function($tmp, $filename, $quality[$j]);
                }
                $newFilenames[] = $filename;
                echo $filename . '<br />';
            }
            imagedestroy($src);
        }
        $i++;
    }
    $fieldString = '`' . implode('`,`', $fieldListArray)  . '`';
    $valueString = trim(str_repeat('?,',count($newFilenames)),',');
    $stmt = $pdo->prepare("INSERT INTO tbl_user (`user_id`, `ap_id`, $fieldString) VALUES (?,?,$valueString)");
    $stmt->execute(array_merge( [2,2], $newFilenames ));
}
?>

<html>
<body>
<form enctype="multipart/form-data" method="post">
    <input type="file" name="myimage[]" multiple><label>Enter </label>
    <input type="submit" value="Go" />
</form>
</body>
</html>

Dear Diafol,
Thanks for the codes. I test and save it as .php file in my server but it shows "Internal Server Error".

I am not too sure what happen. I did ask the service provider, they said the server support PDO.

Member Avatar for diafol

Make sure this:

$pdo = new PDO("mysql:host=localhost;dbname=dwtest","root","mypassword");

Has your correct connection details. Don't think that should bive an ISE though. If you're using a framework though, stupid things can trigger ISEs for no good reason that I can think of. It all worked fine for me other than the write to DB bit since I didn't implement that.

Member Avatar for diafol

Oh BTW - this is JS upload? Missed that in the title. Are you ajaxing the form?

Dear Diafol,
$pdo = new PDO("mysql:host=localhost;dbname=dwtest","root","mypassword");
I have made changes to the codes by putting in my host, username and password. But still not working.

I am not ajaxing the form yet. I am saving it as .php file. Should I save it as other format (php5, html etc)?

Thanks

Member Avatar for diafol

No. Php is fine. Try sectioning off bits of the code or create a new page adding bits of code at a time until u come across the issue.

Dear Diafol, ok thanks. I will try it out and let you know. Maybe I separate the codes into two. Php in one PHP file and then the form in html.

Can you teach me how use this codes for 3 images uploading?

Thanks.

Member Avatar for diafol

I don.t understand. Teach you how to use it?

Dear Diafol,
I have separated the codes into two file, php and html. The codes as below:

The PHP code: upload-pdo.php

<?php
//SET DEFAULTS
//error_reporting(0);
$change="";
$abc="";
$errors=0;
$allowedExtensions = ['png','jpg','jpeg','gif'];
$key = 'myimage';
$setWidths = [600, 130];
$uploadDirectory = ['Testing/images/','Testing/images/'];
$prefix = ['','small_'];
$quality = [100,100];
$fieldListArray = ['big','small','big1','small1','big2','small2'];
$newFilenames = [];
define ("MAX_SIZE","400"); //assuming kb
//FUCNTIONS
//Check and return file type
function validate_extension($file, $allowedExtensions) {
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    if(in_array($ext, $allowedExtensions)) {
        if ($ext == 'jpg') $ext = 'jpeg';
        return $ext;
    }
    return false;
}
//Change array structure
function transpose($files)
{
    $result = [];
    foreach ($files as $key1 => $value1)
        foreach ($value1 as $key2 => $value2)
            $result[$key2][$key1] = $value2;
    return $result;
}
//Check size allowed
function check_size($file)
{
    return $file['size'] / 1024 <= MAX_SIZE;
}
//MAIN ROUTINE
  if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_FILES[$key]))
{
    //Apply error handling to this
try {
$dbh = new PDO('mysql:host=HOST;dbname=DB',"USER","PASSWORD");
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
    die();
}

    if(is_array($_FILES[$key]['name']))
    {
        $files = transpose($_FILES[$key]); //change ridiculous multiple files array structure
    }else{
        $files = (array) $_FILES[$key];
    }
    $i = 0;
    foreach($files as $file)
    {
        $ext = validate_extension($file['name'], $allowedExtensions);
        if($ext && check_size($file)) {
            $stored = $file['tmp_name'];
            $function = 'imagecreatefrom' . $ext;
            $src = $function($stored);
            list($w, $h) = getimagesize($stored);
            for ($j = 0; $j < count($setWidths); $j++)
            {
                echo 'Inner' . $j . '<br/>';
                $w2 = $setWidths[$j];
                $h2 = $h / $w * $w2;
                $tmp = imagecreatetruecolor($w2, $h2);
                imagecopyresampled($tmp, $src, 0, 0, 0, 0, $w2, $h2, $w, $h);
                $image_name = (time() . $i) . '.' .$ext;
                $filename = $uploadDirectory[$j] . $prefix[$j] . $image_name;
                $function = 'image' . $ext;
                if($ext == 'gif' || !isset($quality[$j]) || is_null($quality[$j]))
                {
                    $function($tmp, $filename);
                }else {
                    $function($tmp, $filename, $quality[$j]);
                }
                $newFilenames[] = $filename;
                echo $filename . '<br />';
            }
            imagedestroy($src);
        }
        $i++;
    }
    $fieldString = '`' . implode('`,`', $fieldListArray)  . '`';
    $valueString = trim(str_repeat('?,',count($newFilenames)),',');
    $stmt = $pdo->prepare("INSERT INTO tbl_user (`user_id`, `ap_id`, $fieldString) VALUES (?,?,$valueString)");
    $stmt->execute(array_merge( [2,2], $newFilenames ));
}
}
else {
}
?>

The HTML Code:

<html>
<body>

<?php include("upload-pdo.php"); 
?>
<form enctype="multipart/form-data" method="post">
    <input type="file" name="myimage[]" multiple><label>Enter </label>
    <input type="submit" value="Go" />
</form>

</body>
</html>

I have tested it but it does not upload my image to server.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.