Jump to content

get the serial number from the file name


shumonira
Go to solution Solved by Barand,

Recommended Posts

yes you can.

 

After your php code has processed the uploaded file and saved it using the true filename and not the temporary filename that was generated by the upload, you can use a PHP string function to grab whatever portion of that filename that you want and then do whatever you want to do with that value.

Edited by ginerjm
Link to comment
Share on other sites

You need to combine the number extraction with validation. Users make mistakes. And some users even purposely break the applications of unsuspecting programmers.

<?php

/*
 * I don't know the exact pattern, so I'm guessing it's always 4 digits followed by an underscore, another 4 digits and
 * the extension. Change if necessary.
 */
const FILENAME_PATTERN = '/\\A(?<serial>\\d{4})_\\d{4}\\.txt\\z/i';



$filename = '0521_2145.txt';     // test
$filename_parts = null;
if (preg_match(FILENAME_PATTERN, $filename, $filename_parts))
{
    $serial_number = $filename_parts['serial'];
    echo 'The serial number is '.htmlspecialchars($serial_number, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
else
{
    echo 'Invalid filename!';
}
Link to comment
Share on other sites

Jacques has provided the better answer in this particular case. The rule is "Never Trust The User's Input" which he is attempting to solve for you. Barand has given you the purely mechanical solution to your question, but J has given you valuable code to build a better app.

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.