How to convert a string according to said criteria and how to apply this newly converted string as a file name to the file uploaded by user?

StackOverflow https://stackoverflow.com/questions/21138417

سؤال

I'm using PHP, Smarty and MySQL for my website. I'm relatively new to the concept of Files in PHP and String. I'm accepting a "document title" and a "file" from the user. User will enter whatever title he/she wants to give and uploads a file by using HTML file control.

I want to convert all the characters of a document title into small case, replace the spaces between two words by underscore and create a new string from it. Now I want to rename the file uploaded by user with this name and then save it to the server. While doing this the extension of uploaded file shouldn't change, it should be kept intact. But I'm not understanding how could I achieve this. Can anyone help me in this regard please?

<form name="import_tests"  action="" method="post" enctype="multipart/form-data">
  <div class="terthead">Document Title <input type="text" name="pt_doc_title" id="pt_doc_title" value="" maxlength="50"/></div>
  <p class="uploadBtn"><input type="file" name="document_file_name" id="document_file_name"></p>
  <input type="submit" name="submit" value="Upload Document" class="c-btn" />
</form>
هل كانت مفيدة؟

المحلول

  1. Receive the title in your PHP script using $_POST['pt_doc_title']
  2. Use strtolower() to convert the title to lowercase
  3. Use str_replace() to replace all spaces with underscores
  4. Use rename() function to rename the file uploaded by the user

This should get you started:

if (isset($_POST['submit'])) {
    $title = $_POST['pt_doc_title'];
    $title = strtolower($title);
    $title = str_replace(' ', '_', $title);

    // do additional checks and rename the file
}

نصائح أخرى

I want to convert all the characters of a document title into small case, replace the spaces between two words by underscore

$string = strtolower(preg_replace("\s+", "_", $string));

Now I want to rename the file uploaded by user with this name and then save it to the server.

move_uploaded_file($_FILES['upload']['tmp_name'], $dir . "/" . $string);

Should work if i didnt do smthg wrong ... and im quite sure i forgot something.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top