PHP Upload Example

darren's Avatar

darren

27 Oct, 2011 03:54 AM

I got this working tonight, didn't find another example, so hope this helps someone.

To use the code, the /upload folder must be in the same folder as the php file, and must exist. The code will create a client folder by passing a querystring parameter, don't use spaces in the client name. If the file being uploaded already exists, the name will be created with a incremented number that is unique (myimage.jpg exists, file will be named myimage(1).jpg)

Querystring example:
http://www.server.com/upload.php?client=myclient

Creates a new folder called 'myclient' (/upload/myclient)

`<?php // upload.php created by Darren Wright, Buzz KC

$rootimagefolder = "upload/"; 

//get the client folder from querystring parm, will create if doesn't exist. makePath() creates path string.
$targetdir = makePath($rootimagefolder, $_REQUEST['client']);
@mkdir($targetdir, 0755, true);

if (!file_exists($targetdir)) {
    throw new Exception("Could not create upload directory: $targetdir");
}

//get other querystring parameters
$username = $_REQUEST['username'];
$password = $_REQUEST['username'];
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$messagetxt = $_REQUEST['message'];


$target = "";
$basename = basename( $_FILES['media']['name']) ;
$filetype = $_FILES["media"]["type"]; 
$target = makePath($targetdir , $basename);
$ok=1; 
$errormsg = "";

//This is our size condition 
if ($uploaded_size > 1350000) 
{ 
    $ok=0; 
    $errormsg="Your file is too large.";
} 

//check file types for only the ones we want. sparkbooth users octet-stream.
if (($filetype == "image/gif")
|| ($filetype == "image/jpeg")
|| ($filetype == "image/jpg")
|| ($filetype == "application/octet-stream")){

    //ok to upload

}else{
    $ok=0;
    $errormsg = "Invalid file type, file type = ".$filetype;
}


//Here we check that $ok was not set to 0 by an error 
if ($ok==0) 
{ 
    echo '<?xml version="1.0" encoding="UTF-8"?><rsp status="fail" ><err msg="'.$errormsg.'" /></rsp>';
} 

//If everything is ok we try to upload it 
else 
{ 
            //if the file name exists, increment the name with a number.
    $x=0;

    if(file_exists($target )){
        $exists = true;
        while($exists == true){

            $x = $x + 1;

            $pos = strrpos($basename, ".");
            if ($pos === false) { // note: three equal signs
                $target = makePath($targetdir, $basename . "(". $x . ")");            
            } else {
                $fileparts = explode(".",$basename);
                if(count($fileparts)==2){
                    $target = makePath($targetdir, $fileparts[0] . "(". $x . ").". $fileparts[1]);        
                } else {
                    $newbase = "";
                    for ($i = 0; $i < count($fileparts)-1; $i++) {
                        if ($newbase ==""){
                            $newbase = $fileparts[$i];
                        } else {
                            $newbase = $newbase . "." . $fileparts[$i];    
                        }  
                    }
                    $target = makePath($targetdir, $newbase . "(". $x . ").". $fileparts[count($fileparts)-1]);
                }   
            }



            $exists = file_exists($target);


        }

    }


    //sparkbooth sends image as an octet/stream, must read data stream and create file 
    if($filetype == "application/octet-stream"){
        $fp = fopen( $target, 'wb' );
        $data = file_get_contents($_FILES['media']['tmp_name']);
        fwrite( $fp, $data );
        fclose( $fp ); 

        //send mail with link if email is provided.
        if($email <> ""){
            if($name =="" || name==null) $name = "Customer";
            $from="[email blocked]";
            $subject= $messagetxt;
            $to=$email;
            $url = "http://server_domain/".str_replace("\\", "/", $target);

            $message = "<html><head><title>Photos By You</title></head><body>$name,<br><br>Thank you for stopping by our photo booth, here's a link to download your photo:<br><br>
                <a href='".$url."'>".$url."</a>
                <br><br>Photos By You</body></html>";

            // Always set content-type when sending HTML email
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
            $headers .= "From:" . $from. "\r\n";
            mail($to,$subject,$message,$headers);

        }

        echo '<?xml version="1.0" encoding="UTF-8"?><rsp status="ok" />';
    }else if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) 
    { 
        echo '<?xml version="1.0" encoding="UTF-8"?><rsp status="ok" />';
    } 
    else 
    { 
        echo '<?xml version="1.0" encoding="UTF-8"?><rsp status="fail" ><err msg="Sorry, there was a problem uploading your file." /></rsp>'; 
    } 

} 

function makePath() {
    $args = func_get_args();

    // Special case: $args is 1 argument, an array
    if (count($args) == 1 && is_array($args[0])) {
        $args = $args[0];
    }

    $finStr = "";

    for ($i =0; $i < count($args); $i++) {
        if ($i != (count($args) - 1) && substr($args[$i], strlen($args[$i]) - 1, 1) != "/") {
            $finStr .= $args[$i] . "/";
        } else {
            $finStr .= $args[$i];
        }
    }

    $finStr = str_replace("//", "/", $finStr);

    // Special case... don't mess with protocol strings
    $finStr = str_replace(":/", "://", $finStr);

    return $finStr;
}

?>`

  1. John Wu closed this discussion on 27 Feb, 2012 02:14 AM.

Comments are currently closed for this discussion. You can start a new one.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac