azazu testing azazu testing - 4 months ago 7
HTML Question

How to implement cookie in profile picture uploading?

I have a problem figuring this out. How to implement cookie in processing uploaded picture name ?

I have 2 files :

index.php (where you can set your profile picture).

<form action="setPicture.php" method="post" enctype="multipart/form-data" >
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">


if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";

If a user upload's a profile picture it will be saved in data/img/admin , i must use that source to save it inside the cookie and then get redirected to the main page index.php with the profile picture is set .

Can someone helps me to understand the implementation ?

Here is the complete code of my work.


Cookie is usually used to record mini temporary data that you want to access later when some interactions occur (ex: pages interaction). In your case, you want to save the cookie's value as the path of the successfully uploaded image.

In simple case you could just :

  • If the image has been uploaded succesfully, take the path of the file and then save it to a cookie :

     if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
       $full_path =$target_dir.( $_FILES["fileToUpload"]["name"]);
      // set the cookie
     setcookie("mypathvalueissaved",$full_path, time()+3600);  /* expire in 1 hour */ 

now a new cookie created with a name of "mypathvalueissaved" and its value is $full_path which is the the value of the target path + file's name (contains extension).

  • Later on when you want to access the cookie just refer to the cookie's name (even in the different pages, it will be recognized since $_COOKIE is a superglobal array with assumption that you don't set the cookie for a specific domain ) with $_COOKIE["mypathvalueissaved"]. Like when the uploading is successfully, set the cookie then do redirecting and finally set the value of the cookie as the value of a <img src= >, like <img src="<?php echo $_COOKIE['mypathvalueissaved'];?>">.

     // if the cookie with a "mypathvalueissaved" name was successfully created before
     if (isset($_COOKIE["mypathvalueissaved"])){ 

This is just a brief explanation, you can improve & expand its usage by yourself.