Shihan Khan
Shihan Khan

Reputation: 2188

Upload image according to name in PHP

Suppose there are 2 same images in different names. I want to upload these images & put them in different folder. Suppose, img1.jpg & a-img1.jpg are the images. Now img1.jpg will go on "files/images/" location & a-img1.jpg will go on "files/a-images/" location. I've successfully manage to upload images but it'll only go to one destination folder. This is my code,

    $upload_errors = 0;
    $images= $_FILES['img'];
    $img_id = get_new_image_id();
    $image_ok = true;
    $queries = array();
    $allowed_exts    = array('jpg', 'png', 'jpeg', 'gif');
    foreach ($images['tmp_name'] as $key => $val ) {
        $fileName = $images['name'][$key];
        $fileSize = $images['size'][$key];
        $fileSize = round($fileSize/1024);
        $fileTemp = $images['tmp_name'][$key];
        $path_parts = pathinfo($fileName);
        $fileExt = $path_parts['extension'];
        $fileExt = strtolower($fileExt);
        if($fileSize > 2*1024){
            $image_ok = false;
        }
        if(!in_array($fileExt, $allowed_exts)){
            $image_ok = false;
        }
        if($image_ok){
            $upload_link = "files/images/".$img_id.".".$fileExt;
    $tupload_link = "files/a-images/".$img_id.".".$fileExt;

        move_uploaded_file($fileTemp, $upload_link);
        move_uploaded_file($fileTemp, $tupload_link);
        $img_id++;
        }else{
            $upload_errors++;
        }

Is there any way to identify an image file like "a-img1.jpg"? I need this help badly. Tnx in advance!

Upvotes: 0

Views: 84

Answers (2)

Scott Helme
Scott Helme

Reputation: 4799

You can use this function to see if the string starts with "a-":

function startsWith($haystack, $needle){
    return strpos($haystack, $needle) === 0;
}

So you would do something like:

if(startsWith($img_id, "a-")){
    $upload_link = "files/a-images/".$img_id.".".$fileExt;
}else{
    $upload_link = "files/images/".$img_id.".".$fileExt;
}

move_uploaded_file($fileTemp, $upload_link);

Upvotes: 0

Dubaischeich
Dubaischeich

Reputation: 11

Since you already moved the file a second move from the same source won't work. Maybe you should copy the file the second time.

Upvotes: 1

Related Questions