Dear all,
I have created a website where I would like my users to register and upload profile images to my server and then store it under folder in my server known as "images" and then save the dataurl of the images into MySQL database. Then, I would display their profile picture on a page known as "profile.html" into row and resize the images into 60x60 pixels images.

I have no idea how to do this. I have found and read through a lot of thread ut I did not find any related information.
Anyone can help me with this?

Thanks for any help.

Dani AI

Generated

Good progress so far — shows how to produce two sizes and save files, and correctly explains the . concatenation. For a robust, maintainable solution: store the image files on disk and save a path (or thumbnail path) in MySQL. Only store a full data: URL (base64) in the database if you truly cannot use the filesystem — base64 inflates storage by about 33% and makes backups and queries heavier.

Recommended workflow you can apply immediately:

  1. Validate the upload server-side (use finfo and getimagesize) and enforce a size limit. 2) Generate a sanitized, unique filename (avoid user-supplied names). 3) Move the uploaded file with move_uploaded_file() into a non-executable upload directory (or a directory outside webroot). 4) Create a square 60x60 thumbnail by center-cropping then resizing (GD or Imagick) so avatars are not distorted. 5) Store the relative path (VARCHAR(255)) in MySQL using prepared statements (PDO or mysqli). If you must store binary, use a BLOB column and understand the backup/performance trade-offs.

Security and performance notes:

  • Never trust the client MIME or extension; check server-side MIME.
  • Strip/normalize EXIF orientation so images display correctly.
  • Prevent code execution in the upload folder (disable PHP execution or place uploads outside webroot).
  • Randomize filenames to avoid collisions and disclosure of original names.
  • Add cache headers when serving avatars and consider storing static assets on object storage/CDN for scale.

Minimal example (validation -> move -> DB insert):

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($_FILES['avatar']['tmp_name']);
if (! in_array($mime, ['image/jpeg','image/png','image/gif'])) exit('bad file');

$ext = ($mime==='image/png')? 'png' : (($mime==='image/gif')? 'gif' : 'jpg');
$basename = bin2hex(random_bytes(8));
$target = 'images/avatars/' . $basename . '.' . $ext;
move_uploaded_file($_FILES['avatar']['tmp_name'], $target);

$stmt = $pdo->prepare('INSERT INTO users (user_id, avatar_path) VALUES (:uid, :p)');
$stmt->execute([':uid'=>$userId, ':p'=>$target]);

These points address the gaps in earlier posts: safer validation, modern DB API, and the trade-offs of storing data URLs vs file paths.

Recommended Answers

All 4 Replies

There many way to do that, you can do that, in php, and get the values from the form and save it to Database and save the image to the folder.

Check bellow the code.

<?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("localhost","root","");
  if (!$connection) {
    die("Database connection failed: " . mysql_error());
  }

  $db_select = mysql_select_db("test",$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++;

  mysql_query("Insert into tbl_user set user_id='2',
  ap_id='2',big='$filename',small='$filename1' ", $connection);

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



//sql code for user table 

create table 'tbl_user'
(
'id' INT NOT NULL primary key AUTO_INCREMENT,
'user_id' int,
'ap_id' int,
'small'varchar,
'big' varchar,
);

Hi hoppe it can help.

Hi,
Thanks a lot. I think this has solved major part of my problem. I have some question:
$filename = "images/". $image_name;
$filename1 = "images/small_". $image_name;

The above codes "images/". $image_name has a . $image_name. Is it meaning that if my photo name is ABC.jpeg, the URL to the image will become "images/.ABC.jpeg" ?

Thanks a lot :)

Look, when you save the image, you have 2 different image size.
one is big then another, and you can choose which one you want or you can specify the about width and heigth.
$filename is original size and and $filename1 saving with another size.

the "dot" in a php text variable is concatenation, it means the variable is appended directly to the preceding text
The above codes "images/". $image_name
if your photo name is ABC.jpeg, the URL to the image will be "images/ABC.jpeg"
normally used with 'single quotes' :: "double quoted" text is parsed for variables ,, so may equally look like this "images/$image_name"

you see the .dot in declarations

$a = 'ralph';
$a .= ' wiggum'; // eq to $a = 'ralph'.' wiggum';
echo $a; // ralph wiggum

and many other (non-trivial) instances where it is important to see the development of variables $c=$a.$b;
hth

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.