Jump to content

rewrite filename help


jimmyp3016

Recommended Posts

Hey Guys/Girls,

I have a file upload script that uploads images. It has a part of the script that i have highlighted below in pink where it says "case 2: // create new with incremental extention" that rewrites the filename that a user uploads to something different. What I want it to do is to rewite the filename to there username. I have the Mysql statement that pulls from my database at the top so it knows the correct username. How can i change the rewrite part so it makes the filename the username? Im pretty new to this stuff so its prob very easy to do. Any help would be great thanks! Sorry for the long script but the rewrite section is highlighted.

[code]

<?php

$user    =    $_GET['usr'];
include 'config.inc';
$db = @mysql_connect("$localhost", "$databaseuser", "$databasepasswd");
@mysql_select_db("$databasename",$db);
$sql    =    "SELECT * FROM table WHERE user='$user'";
$result = mysql_query($sql,$db);
if (mysql_num_rows($result) != 0) {

    $firstname    = mysql_result($result, 0, "firstname");
}
else {
  header("Location: notfound.html");
}

class uploader {

    var $file;
    var $path;
    var $language;
    var $acceptable_file_types;
    var $error;
    var $errors; // Depreciated (only for backward compatability)
    var $accepted;
    var $max_filesize;
    var $max_image_width;
    var $max_image_height;


    /**
    * uploader - Class constructor, sets error messaging language preference
    *
    * @param string language    defaults to en (English).
    * @return object
    *
    */
    function uploader ( $language = 'en' ) {
        $this->language = strtolower($language);
        $this->error  = '';
    }
   
   
    /**
    * max_filesize - Set the maximum file size in bytes ($size), allowable by the object.
    *
    * NOTE: PHP's configuration file also can control the maximum upload size, which is set to 2 or 4
    * megs by default. To upload larger files, you'll have to change the php.ini file first.
    *
    * @param int size file size in bytes
    * @return void
    *
    */
    function max_filesize($size){
        $this->max_filesize = (int) $size;
    }


    /**
    * max_image_size- Sets the maximum pixel dimensions.
    *
    * Will only be checked if the uploaded file is an image
    *
    * @param int width      maximum pixel width of image uploads
    * @param int height    maximum pixel height of image uploads
    * @return void
    *
    */
    function max_image_size($width, $height){
        $this->max_image_width  = (int) $width;
        $this->max_image_height = (int) $height;
    }
   
   
    /**
    * upload - Checks if the file is acceptable and uploads it to PHP's default upload diretory
    *
    * @param filename        (string) form field name of uploaded file
    * @param accept_type    (string) acceptable mime-types
    * @param extension        (string) default filename extenstion
    * @return bool
    *
    */
    function upload($filename='', $accept_type='', $extention='') {
       
        $this->acceptable_file_types = trim($accept_type); // used by error messages
       
        if (!isset($_FILES) || !is_array($_FILES[$filename]) || !$_FILES[$filename]['name']) {
            $this->error = $this->get_error(0);
            $this->accepted  = FALSE;
            return FALSE;
        }
               
        // Copy PHP's global $_FILES array to a local array
        $this->file = $_FILES[$filename];
        $this->file['file'] = $filename;
       
        // Initialize empty array elements
        if (!isset($this->file['extention'])) $this->file['extention'] = "";
        if (!isset($this->file['type']))      $this->file['type']      = "";
        if (!isset($this->file['size']))      $this->file['size']      = "";
        if (!isset($this->file['width']))    $this->file['width']    = "";
        if (!isset($this->file['height']))    $this->file['height']    = "";
        if (!isset($this->file['tmp_name']))  $this->file['tmp_name']  = "";
        if (!isset($this->file['raw_name']))  $this->file['raw_name']  = "";
               
        // test max size
        if($this->max_filesize && ($this->file["size"] > $this->max_filesize)) {
            $this->error = $this->get_error(1);
            $this->accepted  = FALSE;
            return FALSE;
        }
       
        if(stristr($this->file["type"], "image")) {
           
            /* IMAGES */
            $image = getimagesize($this->file["tmp_name"]);
            $this->file["width"]  = $image[0];
            $this->file["height"] = $image[1];
           
            // test max image size
            if(($this->max_image_width || $this->max_image_height) && (($this->file["width"] > $this->max_image_width) || ($this->file["height"] > $this->max_image_height))) {
                $this->error = $this->get_error(2);
                $this->accepted  = FALSE;
                return FALSE;
            }
            // Image Type is returned from getimagesize() function
            switch($image[2]) {
                case 1:
                    $this->file["extention"] = ".gif"; break;
                case 2:
                    $this->file["extention"] = ".jpg"; break;
                case 3:
                    $this->file["extention"] = ".png"; break;
                case 4:
                    $this->file["extention"] = ".swf"; break;
                case 5:
                    $this->file["extention"] = ".psd"; break;
                case 6:
                    $this->file["extention"] = ".bmp"; break;
                case 7:
                    $this->file["extention"] = ".tif"; break;
                case 8:
                    $this->file["extention"] = ".tif"; break;
                default:
                    $this->file["extention"] = $extention; break;
            }
        } elseif(!ereg("(.)([a-z0-9]{3,5})$", $this->file["name"]) && !$extention) {
            // Try and autmatically figure out the file type
            // For more on mime-types: <a href="http://httpd.apache.org/docs/mod/mod_mime_magic.html" target="_blank">http://httpd.apache.org/docs/mod/mod_mime_magic.html</a>
            switch($this->file["type"]) {
                case "text/plain":
                    $this->file["extention"] = ".txt"; break;
                case "text/richtext":
                    $this->file["extention"] = ".txt"; break;
                default:
                    break;
            }
        } else {
            $this->file["extention"] = $extention;
        }
       
        // check to see if the file is of type specified
        if($this->acceptable_file_types) {
            if(trim($this->file["type"]) && (stristr($this->acceptable_file_types, $this->file["type"]) || stristr($this->file["type"], $this->acceptable_file_types)) ) {
                $this->accepted = TRUE;
            } else {
                $this->accepted = FALSE;
                $this->error = $this->get_error(3);
            }
        } else {
            $this->accepted = TRUE;
        }
       
        return (bool) $this->accepted;
    }


    /**
    * save_file - Cleans up the filename, copies the file from PHP's temp location to $path,
    *
    * save_file() also checks the overwrite_mode and renames the file if needed
    *
    * overwrite_mode:
    *    + 1 = overwrite files with the same name
    *    + 2 = rename files with the same name.
    *    + 3 = do nothing if file name already exists
    *
    * overwrite_mode 2 works like this:
    *    file.txt  is uploaded
    *    another 'file.txt' is uploaded, and renamed file_copy0.txt
    *    another 'file.txt' is uploaded, and renamed file_copy1.txt
    *
    *
    * @param string path          File path to your upload directory
    * @param int overwrite_mode  Must be 1, 2, or 3
    * @return bool
    *
    */
    function save_file($path, $overwrite_mode="3"){
        if ($this->error) {
            return false;
        }
       
        if (strlen($path)>0) {
            if ($path[strlen($path)-1] != "/") {
                $path = $path . "/";
            }
        }
        $this->path = $path;   
        $copy      = "";   
        $n          = 1;   
        $success    = false;   
               
        if($this->accepted) {
            // Clean up file name (only lowercase letters, numbers and underscores)
            $this->file["name"] = ereg_replace("[^a-z0-9._]", "", str_replace(" ", "_", str_replace("%20", "_", strtolower($this->file["name"]))));
           
            // Clean up text file breaks
            if(stristr($this->file["type"], "text")) {
                $this->cleanup_text_file($this->file["tmp_name"]);
            }
           
            // get the raw name of the file (without its extenstion)
            if(ereg("(.)([a-z0-9]{2,5})$", $this->file["name"])) {
                $pos = strrpos($this->file["name"], ".");
                if(!$this->file["extention"]) {
                    $this->file["extention"] = substr($this->file["name"], $pos, strlen($this->file["name"]));
                }
                $this->file['raw_name'] = substr($this->file["name"], 0, $pos);
            } else {
                $this->file['raw_name'] = $this->file["name"];
                if ($this->file["extention"]) {
                    $this->file["name"] = $this->file["name"] . $this->file["extention"];
                }
            }
           
            switch((int) $overwrite_mode) {
                case 1: // overwrite mode
                    if (@copy($this->file["tmp_name"], $this->path . $this->file["name"])) {
                        $success = true;
                    } else {
                        $success    = false;
                        $this->error = $this->get_error(5);
                    }
                    break;
                case 2: // create new with incremental extention
                    while(file_exists($this->path . $this->file['raw_name'] . $copy . $this->file["extention"])) {
                        $copy = "_copy" . $n;
                        $n++;
                    }
                    $this->file["name"]  = $this->file['raw_name'] . $copy . $this->file["extention"];
                    if (@copy($this->file["tmp_name"], $this->path . $this->file["name"])) {
                        $success = true;
                    } else {
                        $success    = false;
                        $this->error = $this->get_error(5);
                    }
                    break;
                default: // do nothing if exists, highest protection
                    if(file_exists($this->path . $this->file["name"])){
                        $this->error = $this->get_error(4);
                        $success    = false;
                    } else {
                        if (@copy($this->file["tmp_name"], $this->path . $this->file["name"])) {
                            $success = true;
                        } else {
                            $success    = false;
                            $this->error = $this->get_error(5);
                        }
                    }
                    break;
            }
           
            if(!$success) { unset($this->file['tmp_name']); }
            return (bool) $success;
        } else {
            $this->error = $this->get_error(3);
            return FALSE;
        }
    }
   
   
    /**
    * get_error - Gets the correct error message for language set by constructor
    *
    * @param int error_code
    * @return string
    *
    */
    function get_error($error_code='') {
        $error_message = array();
        $error_code    = (int) $error_code;
       
        switch ( $this->language ) {
            // English
            default:
                $error_message[0] = "No file was uploaded";
                $error_message[1] = "Maximum file size exceeded. File may be no larger than " . $this->max_filesize/1000 . " KB (" . $this->max_filesize . " bytes).";
                $error_message[2] = "Maximum image size exceeded. Image may be no more than " . $this->max_image_width . " x " . $this->max_image_height . " pixels.";
                $error_message[3] = "Only " . str_replace("|", " or ", $this->acceptable_file_types) . " files may be uploaded.";
                $error_message[4] = "File '" . $this->path . $this->file["name"] . "' already exists.";
                $error_message[5] = "Permission denied. Unable to copy file to '" . $this->path . "'";
            break;
        }
       
        // for backward compatability:
        $this->errors[$error_code] = $error_message[$error_code];
       
        return $error_message[$error_code];
    }


    /**
    * void cleanup_text_file (string file);
    *
    * Convert Mac and/or PC line breaks to UNIX by opening
    * and rewriting the file on the server
    *
    * @param file            (string) Path and name of text file
    *
    */
    function cleanup_text_file($file){
        // chr(13)  = CR (carridge return) = Macintosh
        // chr(10)  = LF (line feed)      = Unix
        // Win line break = CRLF
        $new_file  = '';
        $old_file  = '';
        $fcontents = file($file);
        while (list ($line_num, $line) = each($fcontents)) {
            $old_file .= $line;
            $new_file .= str_replace(chr(13), chr(10), $line);
        }
        if ($old_file != $new_file) {
            // Open the uploaded file, and re-write it with the new changes
            $fp = fopen($file, "w");
            fwrite($fp, $new_file);
            fclose($fp);
        }
    }

}

?>
[/code]
Link to comment
Share on other sites

here is the script that calls this file. Any more suggestions?

[code]

<?php

$user = $_GET['usr'];

require("fileupload.class.php");



/*
**
** Variables
** --------------------------------------------------------------------
**
*/

// $path used by save_file() method
//
// Path to the directory where uploaded files will be saved. MUST end
// with a trailing slash unless you use $path = ""; to upload to
// current directory. chmod 777 this directory.

$path = "uploads/";


//$acceptable_file_types used by upload() method
//
// Limit acceptable uploads based on MIME type. Common MIME types
// include: text/plain, image/gif, image/jpeg image/png

// To accept ONLY gifs's use the following
//acceptable_file_types = "image/gifs";

// Accept GIF and JPEG files
$acceptable_file_types = "image/jpeg|image/pjpeg";

// Accept all image files
//$acceptable_file_types = "image";

// Accept ALL files
//$acceptable_file_types = "";


// $default_extension used by upload() method
//
// If no extension is supplied, and the browser or PHP can not figure
// out what type of file it is, you can add a default extension

$default_extension = ".jpg"; // example: ".jpg"


// $mode used by save_file() method
//
// Handles identically named uploaded files.
//
// OPTIONS:
//  1 = overwrite mode
//  2 = create new with incremental extention
//  3 = do nothing if exists, highest protection

$mode = 2;


/*
**
** UPLOAD LOGIC
** --------------------------------------------------------------------
**
*/
if (isset($_REQUEST['submitted'])) {

/*
A simpler way of handling the submitted upload form
might look like this:

$my_uploader = new uploader('en'); // errors in English

$my_uploader->max_filesize(30000);
$my_uploader->max_image_size(800, 800);
$my_uploader->upload('userfile', 'image/gif', '.gif');
$my_uploader->save_file('uploads/', 2);

if ($my_uploader->error) {
print($my_uploader->error . "<br><br>\n");
} else {
print("Thanks for uploading " . $my_uploader->file['name'] . "<br><br>\n");
}
*/

// Create a new instance of the class
$my_uploader = new uploader($_POST['language']); // for error messages in french, try: uploader('fr');

// OPTIONAL: set the max filesize of uploadable files in bytes
$my_uploader->max_filesize(300000);

// OPTIONAL: if you're uploading images, you can set the max pixel dimensions
$my_uploader->max_image_size(140, 250); // max_image_size($width, $height)

// UPLOAD the file
if ($my_uploader->upload("userfile", $acceptable_file_types, $default_extension)) {
$my_uploader->save_file($path, $mode);
}

if ($my_uploader->error) {
echo $my_uploader->error . "<br><br>\n";

} else {
// Successful upload!
print($my_uploader->file['name'] . " was successfully uploaded! <br>");

// Print all the array details...
//print_r($my_uploader->file);

// ...or print the file
if(stristr($my_uploader->file['type'], "image")) {
echo "<img src=\"" . $path . $my_uploader->file['name'] . "\" border=\"0\" alt=\"\">";
} else {
$fp = fopen($path . $my_uploader->file['name'], "r");
while(!feof($fp)) {
$line = fgets($fp, 255);
echo $line;
}
if ($fp) { fclose($fp); }
}
}
}




/*
**
** HTML FORM
** --------------------------------------------------------------------
**
*/
?>
<form enctype="multipart/form-data" action="<?= $_SERVER['PHP_SELF']; ?>" method="GET">
<input type="hidden" name="submitted" value="true">

Upload this file:<br>
<input name="userfile" type="file">
<br>

<br>
              <input name="usr" type="hidden" value="$user">
<input type="submit" value="Upload File">
</form>
<hr>

<?php
if (isset($acceptable_file_types) && trim($acceptable_file_types)) {
print("This form only accepts <b>" . str_replace("|", " or ", $acceptable_file_types) . "</b> files.\n");
print("If you are having trouble uploading your photo, please send your username and photo to <b>$siteinfo</b>\n");
}
?>


[/code]
Link to comment
Share on other sites

[code]<?php
$management = true;
$errorhandler = "";
$dateinfo = strtotime("now");
$dateformatted = date("n-d-y", $dateinfo);

$connect = mysql_connect("localhost", "####", "#####");
$select = mysql_select_db("funnyemailforwards");
if (!$connect && !$select) {
exit("There was an error connecting to, or selecting the database");
}

$name = $_POST['name'];
$name = strtolower($name);
$name = str_replace(" ", "", $name);
$nameselect = "SELECT nameoffunny FROM fileinfo WHERE nameoffunny = '$name';";
$namequery = mysql_query($nameselect) or die(mysql_error());
if (mysql_num_rows($namequery)) {
$errorhandler .= "The name you have chosen for your funny already appears<br />";
$errorhandler .= "The way to correct this problem would be to choose<br />";
$errorhandler .= "Another name, I apologize for the inconvenience.<br />";
exit();
}
$errorhandler = "";
if ($_POST['name'] == "") {
$errorhandler .= "The Name field has been left blank<br />";
}
if ($_POST['keywords'] == "") {
$errorhandler .= "The Keywords were left blank<br />";
}
if(!is_uploaded_file($_FILES['file']['tmp_name'])){
$errorhandler .= "No file has been uploaded<br />";
}
if ($errorhandler != "") {
echo "{$errorhandler}";
exit();
}


$_accepted_extensions = array('.tiff', '.png', '.mpeg', '.mpg', '.wav', '.avi', '.mid', '.jpg', '.txt', '.gif', '.mp3', '.jpeg', '.gif', '.swf', '.swc', '.flv', '.mov', '.ram', '.rm', '.ra', '.rpm', '.asf', '.wma', '.wmv', '.wm', '.asf', '.wma', '.wm', '.avi', '.mpeg', '.mpg', '.mp2', '.mp3', '.mid', '.midi', '.wav');
$tmp = pathinfo($_FILES['file']['name']);
if (in_array('.' . $tmp['extension'],$_accepted_extensions)) {
$filemanager = true;
}else {
exit("The file extension is not correct, please upload a different extension");
}



// Relative URL with desired folder name and the name of the file on the user's machine
$newfile = "uploads/".basename($_FILES['file']['name']);
$newfiletemp = "{$_FILES[file][tmp_name]}";
if (file_exists($newfile)) {
exit("The file already exists");
}
if (!move_uploaded_file($newfiletemp, $newfile)) {
exit("There was some sort of problem moving the file");
}




$query = "SELECT * from fileinfo WHERE type = '" . implode("", $_POST['type']) . "' AND nameoffunny = '" . mysql_real_escape_string($_POST['name']) . "' AND keywords = '" . mysql_real_escape_string($_POST['keywords']) . "' AND funnyurl = '" . mysql_real_escape_string($newfile) . "' AND entrydate = '" . mysql_real_escape_string($dateinfo) . "'";
$result = mysql_query($query);
$matches = mysql_num_rows($result);
if ($matches == 0) {
$inserter = "INSERT INTO fileinfo (type, nameoffunny, keywords, funnyurl, entrydate) VALUES ('" . implode("", $_POST['type']) . "', '" . mysql_real_escape_string($name) . "', '" . mysql_real_escape_string($_POST['keywords']) . "', '" . mysql_real_escape_string($newfile) . "', '" . mysql_real_escape_string($dateinfo) . "')";

if(!mysql_query($inserter)){
exit("The information was not databased properly");
}
}else {
exit("The data was already in the database");
}






$selectemail = "SELECT id, email FROM signoninfo;";
$emailquery = mysql_query($selectemail);
while ($row = mysql_fetch_array($emailquery)) {
  $to = "{$row[email]}";
  $subject = "Funny Email Forwards Database Results";
  $message = "You can see the results at this page: ";
  $message .= "http://www.funnyemailforwards.com/apex/limitedemailresults.php";
  if (mail($to, $subject, $message)) {
echo "The information has been distributed to everyone on the mailing list<br />";
  }
}
  $to = "information@theyellowpagesnetwork.com";
  $subject = "Funny Email Forwards Entry Approval";
  $message = "http://www.funnyemailforwards.com/administration/approval.php";
  mail($to, $subject, $message);






?>[/code]
A little outdated compared to my current style, but I had to create an entire file handling, and file management system, that ended up being able to play almost every file type concievable.  Flash files, and video files, music, movie sound and everything I used that above to accept the file submissions, maybe that will help, I will show you a few more scripts I use to handle file information, when people were trying to view it maybe it can lead you in the right direction
[code]<?php
# getLoc() grabs the current URL and parses the fake folders into variables.
function getLoc(){
$dirname = split("/", getenv("REQUEST_URI"));
foreach ($dirname as $var) {
if (($var!="BidRent")&&($var!="display")&&($var!="")){
$p[] = $var;
}
}
return $p;
}
# They are called and set here.
$pages = getLoc();
$folder = trim($pages[0]);
$pagename = trim($pages[1]);
$site = "http://www.funnyemailforwards.com/apex/";

$pageTitle = "Page For $page1";
mysql_connect("localhost", "#####", "#####")or die(mysql_error());
mysql_select_db("funnyemailforwards")or die(mysql_error());

$select = "SELECT * FROM fileinfo WHERE nameoffunny = '$pagename'";
$query = mysql_query($select);
$count = mysql_num_rows($query);
$fetch = mysql_fetch_assoc($query);
if ($count > 0){
if(extract($fetch)) {
$successful = true;
}else
$successful = false;
}else{
echo "The file Does not Exist in the database<br />";
}


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo "{$nameoffunny}" ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--<link href="style.css" rel="stylesheet" type="text/css" />-->
</head>
<body>
<?php
$funnyurl = $site . $funnyurl;
if (preg_match("/[.txt]$/i", $funnyurl)){
require_once("./includes/view_text.php");
}elseif (preg_match("/[.jpg|.gif|.jpeg|.bmp|.tiff]$/i",$funnyurl)) {
require_once("./includes/view_picture.php");
}elseif (preg_match("/[.mov]$/i",$funnyurl)) {
require_once("./includes/view_quicktime.php");
}elseif (preg_match("/[.ram|.rm|.ra|.rpm]$/i",$funnyurl)) {
require_once("./includes/view_realmedia.php");
}elseif (preg_match("/[.asf|.wma|.wmv|.wma|.wm|.asf|.avi|.mpeg|.mpg|.mp2|.mp3|.mid|.midi|.wav]$/i",$funnyurl)) {
require_once("./includes/view_windowsmedia.php");
}elseif (preg_match("/[.swf|.swc|.flv]$/i",$funnyurl)) {
require_once("./includes/view_flash.php");
}else {
echo "No file exists at this location";
}
?>
</body>
</html>[/code]
That is what views the files, on every url, I use get strings, to filter information to a display.php page, that chops up the information and redirects it to the appropriate includes, that has all the necessary information to view each file type.  This is all the help I can give you.
Link to comment
Share on other sites

Oh yes, also what you wanted to do is there too, in that script it takes the name that they chose for name, in teh other script and names as files by that, and also checks and makes sure the file doesn't already exist, you should be able to get what you need from bit's and pieces of that.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.