PHP Upload Example

darren's Avatar

darren

01 Nov, 2011 06:43 PM

I didn't find another example of this, hope this helps someone.

            <?php 
                /*
                * Create file on server from sparkbooth custom file upload. 
                * Upload folder must exist, can create folder for client by passing name with the 
                * client querystring parameter saved in the upload settings. 
                *
                * Will rename file if one by that name already exists.
                *
                * If email address is passed, an email with a link to the image is sent to the email address.
                *
                * params: client = name of folder to create for client images, no spaces in name
                * http://www.yourdomain.com/upload.php?client=myclient
                *
                * Creates new folder /upload/myclient/
                */
                $root = "upload/"; 

                $targetdir = makePath($root, $_REQUEST['client']);
                @mkdir($targetdir, 0755, true);

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

                $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.";
                } 


                //sparkbooth sends attachment as octet-stream
                if (($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 output file 
                    if($filetype == "application/octet-stream"){
                        $fp = fopen( $target, 'wb' );

                        //get the data stream and write it to the new file
                        $data = file_get_contents($_FILES['media']['tmp_name']);
                        fwrite( $fp, $data );

                        //close the new file
                        fclose( $fp ); 

                        //if email is passed, send link to photo to user
                        if($email <> ""){
                            $from="[email blocked]";
                            $subject= $messagetxt;
                            $vistor_email=$from;
                            $to=$email;
                            $url = "http://www.yourdomain.com/".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>'; 
                    } 

                } 

                /**
                creates a path string from arguments
                */
                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. Support Staff 1 Posted by John Wu on 02 Nov, 2011 02:01 AM

    John Wu's Avatar

    Thanks for sharing!

  2. John Wu closed this discussion on 27 Feb, 2012 01:56 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