Viewed   92 times

If I want to change my filename before it goes to the server for its permanent location, not its temporary Location how could I do this.

The code is as followed:

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>


<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

 Answers

3

I'm not sure if I understand what you mean. If you just want to rename the file when storing it in the "upload" directory, do so when using move_uploaded_file():

$destination = "upload/" . $new_filename;
if (file_exists($destination)) {
    echo 'File ', $destination, ' already exists!';
} else {
    move_uploaded_file($temp_filename, $destination);
}

You could also let the user define $new_filename by providing an additional "rename" text field in your HTML form.


EDIT: Code could be something like that:

Form:

<form action="upload_file.php" method="post"
    enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />

<!-- NEW TEXTBOX -->
<label for="newname">Rename to (optional):</label>
<input type="text" name="newname" id="newname" /> 
<br />

<input type="submit" name="submit" value="Submit" />
</form>

PHP:

$upload_dir = realpath('upload') . DIRECTORY_SEPARATOR;
$file_info = $_FILES['file'];

// Check if the user requested to rename the uploaded file
if (!empty($_POST['newname'])) {
    $new_filename = $_POST['newname'];
} else {
    $new_filename = $file_info['name'];
}

// Make sure that the file name is valid.
if (strpos($new_filename, '/') !== false || strpos($new_filename, '\') !== false) {
    // We *have* to make sure that the user cannot save the file outside
    // of $upload_dir, so we don't allow slashes.
    // ATTENTION: You should do more serious checks here!
    die("Invalid filename");
}

$destination = $upload_dir . $new_filename;
// ... if (file_exists(... move_uploaded_file(...
Tuesday, August 30, 2022
1

How to do file uploads is explained in the PHP Manual:

  • POST method uploads
  • Error Messages Explained
  • Common Pitfalls
  • Uploading multiple files
  • PUT method support

Please go through these chapters to learn how to do uploads.

If you want to know how File Uploads are implemented in the PHP core, check out

  • http://svn.php.net/viewvc/php/php-src/trunk/main/rfc1867.c?view=markup

Afaik, this is the module that handles this.

If none of the above do give you the information you are looking for, please refine your question to indicate what is missing.

Thursday, December 15, 2022
 
abaghel
 
5

I was able to so solve this problem using GroupSequence, it's explained here :

http://symfony.com/doc/current/validation/sequence_provider.html

Added some code to my Event class and it's all good

use SymfonyComponentValidatorGroupSequenceProviderInterface;

/**
 * @ORMTable(name="event")
 * @ORMEntity(repositoryClass="AppBundleRepositoryEventRepository")
 * @AssertGroupSequenceProvider
 */
class Event implements GroupSequenceProviderInterface
{
......
   /**
    * @var datetime $date
    *
    * @ORMColumn(name="date_debut_inscri", type="datetime")
    * @AssertGreaterThanOrEqual("today UTC", groups = {grp1})
    */
    protected $dateDebutInscri;
......

    public function getGroupSequence(){
            $groups = ['Default', 'Event'];

            if(!$this->getMyCheckBox())
            {
                $groups[] = 'grp1';
            }
            return $groups;
    }
}
Saturday, October 29, 2022
 
abbr
 
4

Try using a separate variable for errors, and not output error messages to the input field.

You could use global variables for this, but I'm not fond of them.

login.php

<?php 
$firstname = '';
$password  = '';
$username  = '';
$emailadd  = '';
$response  = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
    <fieldset>
        <p>Please enter your username and password</p>
    <legend>Login</legend>
        <div>
        <label for="fullname">Full Name</label>
            <input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
        </div>
        <div>
         <label for="emailad">Email address</label>
         <input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
        </div>
        <div>
        <label for="username">Username (between 5-10 characters)</label>
        <input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
        </div>
        <div>            
        <label for="password">Password (between 8-10 characters)</label>
        <input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
        </div>
        <div>            
            <input type="submit" name="" value="Submit" />
        </div>
    </fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
    print $response;         
}     
?>
//Footer stuff

loginprocess.php

//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
    //Here we concatenate the return values of your validation functions.
    $response .= validate_fname();
    $response .= validate_email();
    $response .= validate_username();
    $response .= validate_pw();
}    
//...or footer stuff.

functions.php

function validate_fname() {
    //Note the use of global...
    global $firstname;
    if (!empty($_POST['fname']))    {
        $form_is_submitted = true;
        $trimmed = trim($_POST['fname']);
        if(strlen($trimmed)<=150  && preg_match('/\s/', $trimmed)){
            $fname = htmlentities($_POST['fname']);
            //..and the setting of the global.
            $firstname = $fname;
            //Change all your 'echo' to 'return' in other functions.
            return"<p>You entered full name: $fname</p>";
        } else {
            return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
        }
    }
}

I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.

Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.

Tuesday, October 4, 2022
 
5

Some providers does not allow you change certain values in running time. Instead of this, try to either change it in the real php.ini file or use an .htaccess (For Apache web servers) where you can add your configuration. You can find more information in the PHP.net article about this subject: How to change configuration settings.

Based on your story, example .htaccess

<IfModule mod_php5.c>
php_value upload_max_filesize 100000000
php_value post_max_size 110000000
php_value memory_limit 120000000
php_value max_input_time 20
</IfModule>
Wednesday, December 14, 2022
 
msc
 
msc
1

I have tried the same code and it works for me. I have made some changes for you.

<form method="POST" enctype="multipart/form-data">
    <label for="">Upload Your Cv</label><input type="file" name="file">
    <input type="submit" name="upload" value="upload">
</form>

After that you don't need to redirect the page; instead you can use this, below the </form>

if(isset($_REQUEST["upload"]))
{
if (isset($_FILES['file'])) {
        $file   = $_FILES['file'];
        // print_r($file);  just checking File properties

        // File Properties
        $file_name  = $file['name'];
        $file_tmp   = $file['tmp_name'];
        $file_size  = $file['size'];
        $file_error = $file['error'];

        // Working With File Extension
        $file_ext   = explode('.', $file_name);
        $file_fname = explode('.', $file_name);

        $file_fname = strtolower(current($file_fname));
        $file_ext   = strtolower(end($file_ext));
        $allowed    = array('txt','pdf','doc','ods');


        if (in_array($file_ext,$allowed)) {
            //print_r($_FILES);


            if ($file_error === 0) {
                if ($file_size <= 5000000) {
                        $file_name_new     =  $file_fname . uniqid('',true) . '.' . $file_ext;
                        $file_name_new    =  uniqid('',true) . '.' . $file_ext;
                        $file_destination =  'upload/' . $file_name_new;
                        // echo $file_destination;
                        if (move_uploaded_file($file_tmp, $file_destination)) {
                                echo "Cv uploaded";
                        }
                        else
                        {
                            echo "some error in uploading file".mysql_error();
                        }
//                        
                }
                else
                {
                    echo "size must bne less then 5MB";
                }
            }

        }
        else
        {
            echo "invalid file";
        }
}
}

Note that the upload folder must be in the same directory as where you store the file.

Sunday, October 9, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :