Saturday, January 17, 2015

Code for Image Upload restricting dublicate image with PHP

There are different ways of uploading image in database in php. The below code is uploading the image and instead of keeping the image in database, it sets the location of image in database e.g: image/gallery/picture1.jpg . The advantage of this approach is that, it reduces the load in database by reducing the size from image size to text size(instead of uploading images, it upload path to that image). Below is a working code for uploading image.



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
if(loggedin() && $who == 2){

    $user = $_POST['username'];
    $location = $_POST['location'];
    $qualification = $_POST['qualification'];
    $quality = $_POST['special'];

    $id = $_SESSION['user_id']; // get id of the loggedin user and store in $id.

    $name = $_FILES['file']['name']; //get file name of the uploaded image

    $ext_array = explode('.',strtolower($name)); // collect all the '.' between the name and store in array

    $ext = end($ext_array); //among the array of '.', select the last part after '.'

    $new_name = $name.".".$ext; //gives new name to uploading image

    $target = 'uploads/'.$new_name; // location of the image to be upload

    $tmp_name = $_FILES['file']['tmp_name'];

    if(isset($name)){
        if(!empty($name) && $ext == 'docx' || $ext == 'txt' || $ext == 'doc' || $ext == 'xls'){

            if(move_uploaded_file($tmp_name, $target)){ //move the uploading file to temp folder $temp_name is file name and $target is destination
                $query = "UPDATE `courses`.`store_resume` SET resume = '$target' where ";
                $query_run = mysql_query($query);

                $insert = "INSERT INTO `courses`.`store_resume`(`username`, `location`, `qualification`, `quality`) VALUES ('$user', '$location', '$qualification', '$quality')";
                $qry_run = mysql_query($insert);
               echo 'successfully uploaded';
               echo '<br><br>';
               echo '<a href="index.php">RETURN HOME</a>"';

            }else{
                echo 'opps!!! error uploading file';
                echo '<a href="post_resume_form.php">Try again</a>';
            }
        }else{
            echo 'file must be .docx or .txt or .xls or .doc <br /><br />';
            echo '<a href="post_resume_form.php">Try again</a>';
        }
    }
}

1 comment: