I have a site where with jQuery/ajax I want to upload my image.
The problem is when I have strange filename for my image. Like with dots or other.
I have tried with this mode but doesn't work fine, it replace the dot in file extension for example if I have
image.test.png
become
imagetestpng
but I want this:
imagetest.png
This is my code:
$name = $_FILES['upload']['name'];
$size = $_FILES['upload']['size'];
$name = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $name);
echo($name);
How to solve this?
Thanks
First, you need to decompose the file name:
$info = pathinfo($name);
Then apply your filter on both parts:
$name = preg_replace("/[^\w-]+/", "", $info['filename']);
// check if we have an extension
if (isset($info['extension'])) {
$name .= '.' . preg_replace('/[^\w]/', '', $info['extension']);
}
Demo
You can use this to replace the characters in the filename while preserving the file extension.
$name = preg_replace('/[^a-zA-Z0-9_-]+/',
"",
pathinfo($name, PATHINFO_FILENAME)
) . (pathinfo($name, PATHINFO_EXTENSION)?"." . pathinfo($name, PATHINFO_EXTENSION):"");
Related
I have this code, which will create result.png on my server:
imagepng($image, "'./result/result.png");
Now I have $text , $type , $id
How can I create file with result_$text _ $id _ $type?
Example: ./result/result_123_131_1.png ;
./result/result_Text_1364_3.png
It's very simple:
$name = "./result/result_$text_$id_$type";
//do whatever you do to save the image and use $name as name of the file.
In php the double quotes are used whenever you have variables you want to use in some string literal. What I do above is I insert the value of the variables into the string literal "./result/result___".
More info here.
$image = imagepng($image, "'./result/result");
$file = $image . "_" . $text . "_" . $id . "_" . $type ."png";
I'm trying to make a "send email" form which uploads files to a folder before the email is sent. The path to the files are then shown in the email, but if the files DO exist i don't want them to be overwritten, but i want to have a number added.
I have composed this tiny code, but it doesn't work!
The error says:
Parse error: syntax error, unexpected '$name_of_uploaded_file' (T_VARIABLE) in /customers/8/5/6/HOMEPAGE/httpd.www/php/mailtest2.php on line 49
The script below now upload a file if the file does not exist. If the file does exist nothing happens. The script ends at it should.
The script have been modified to what caused it not to ad "_1" to filename and save file in folder. Now it saves the file in folder and comes up with error: Error while copying the uploaded file
Can someone please explain to me what i do wrong?
Now all code is shown to debug this:
<?php
//Uploaded file 1
//Settings
$max_allowed_file_size = 2000; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "pdf");
error_reporting(E_ALL);
//Upload folder
//name also used later on mail
$name = $_POST['name'];
$d = date('d.m.y');
$varfoldername = "../receivedfiles/$name$d/";
if(!is_dir($varfoldername)) {
mkdir($varfoldername , 0777 , true);
}
$upload_folder = $varfoldername;
//Get the uploaded file information
$name_of_uploaded_file =
basename($_FILES['uploaded_file']['name']);
//Validations
//----- Check if files exists and adds _X to it -----
$original_name_of_file = pathinfo($name_of_uploaded_file, PATHINFO_FILENAME);
$extension = pathinfo($name_of_uploaded_file, PATHINFO_EXTENSION);
$FileCounter = 0;
while (file_exists($varfoldername.$name_of_uploaded_file)) {
$FileCounter++;
$name_of_uploaded_file = $original_name_of_file . '_' . $FileCounter . '.' . $extension;
}
//copy the temp. uploaded file to uploads folder
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
if(move_uploaded_file ( $tmp_path,$path_of_uploaded_file ))
{
die("Error while copying the uploaded file");
}
}
//Validate size requirements
$size_of_uploaded_file =
$_FILES["uploaded_file"]["size"]/1024;//size in KBs
if($size_of_uploaded_file > $max_allowed_file_size )
{
die("Fejl: Filen er for stor");
}
//------ Validate the file extension -----
//get the file extension of the file
$type_of_uploaded_file =
substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
die("The uploaded file is not supported file type. \n Send venligst filer af følgende type: .implode(',',$allowed_extensions)");
}
$email = $_POST['email'];
$phone = $_POST['phone'];
$call = $_POST['call'];
$company = $_POST['company'];
$type = $_POST['type'];
$adress = $_POST['adress'];
$hesteid = $_POST['hesteid'];
$hestenavn = $_POST['hestenavn'];
$message = $_POST['message'];
$areacode = $_POST['areacode'];
$land = $_POST['land'];
$formcontent=" Fra: $company \n Navn: $name \n Adresse: $adress , $areacode \n Land: $land \n Telefon: $phone \n Ringes op: $call \n Type: $type \n Hoppens navn og ID: $hestenavn , $hesteid \n Besked: \n $message \n Vedhæftede filer: \n $path_of_uploaded_file";
$recipient = "simon#secret.dk";
$subject = "Besked fra hjemmesiden";
$mailheader = "Fra: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header('Location: thank_you.shtml');
?>
You need to use the . character to concatenate (stick together) different PHP variables, so:
while (file_exists($varfoldername$name_of_uploaded_file ))
will return you a parse error, because you need to tell PHP you want to string the two variables together, so instead use the . and write:
while (file_exists($varfoldername.$name_of_uploaded_file))
You may also need to add a / directory seperator between the two variables, but that's an issue not directly related to your current problem. But it's useful to print $varfoldername.$name_of_uploaded_file and see if it is the correct filepath layout (has all the / etc. )
Further Work
Hi again I just modified the question. Found two stupid bugs. Now the script runs without error but doesn't add "_1" to the filename. – Simon Jensen
Rearrange your code as such:
$FileCounter = 0;
$original_name_of_file = $name_of_uploaded_file;
while (file_exists($varfoldername.$name_of_uploaded_file)) {
$FileCounter++;
$name_of_uploaded_file = $original_name_of_file . '_' . $FileCounter . '.' . $extension;
}
What happened here:
PHP in the while loop is overwriting the $name_of_uploaded_file so that if you have a file_1.txt then the next file name in the loop will be file_1.txt_2.txt and you can see this overwrite is far from perfect, instead you need to save the Original file, and then overwrite the original concatenated with the increment value and then the .txt .
Your original value of $name_of_uploaded_file is not defined.
$FileCounter for clarity is incremented before being written into the string.
Your code of $FileCounter++ will not work because you have defined $FileCounter as a string by setting it in quote marks. I have removed the quotes so it is now identified by PHP as an integer.
Your file_exists call should not be in quotes as this is causing PHP extra, and needless work, and also will often confuse you as well as your IDE. The quotes in effect do:
PHP Logic: I found a quote, I will start a string structure, oh, this
part looks like a variable, I will stop the string structure, then
concatenate this variable value into the string strucuture, then
continue the string, oh, another variable, I will stop the string
structure, and then concatenate the second variable into this string,
then continue. I found another quote so string finished.
Which is a far larger load of work than clearly and concisely defining two variables concatenated with a . .
Complete Code:
$name = $_POST['name'];
$d = date('d.m.y');
/***
Ideally folders should NEVER be relative, always base them from the PHP server
root such as (example only), using $_SERVER['DOCUMENT_ROOT']:
$varfoldername = $_SERVER['DOCUMENT_ROOT']."/data/uploads/receivedfiles/".$name.$d."/";
***/
$varfoldername = "../receivedfiles/".$name.$d."/";
$upload_folder = $varfoldername;
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
$original_name_of_file = pathinfo($name_of_uploaded_file, PATHINFO_FILENAME);
$extension = pathinfo($name_of_uploaded_file, PATHINFO_EXTENSION);
$FileCounter = 0;
while (file_exists($varfoldername.$name_of_uploaded_file)) {
$FileCounter++;
$name_of_uploaded_file = $original_name_of_file . '_' . $FileCounter . '.' . $extension;
}
/***
Now $name_of_uploaded_file will have the numerical appendage as needed.
***/
if(move_uploaded_file( $tmp_path , $varfoldername.$name_of_uploaded_file )){
print "file uploaded!";
}
IMPORTANT
Do not use copy, instead use PHP Move_upload_file :
if(!copy($tmp_path,$path_of_uploaded_file)){ ...
Becomes
if(move_uploaded_file ( $tmp_path , $path_of_uploaded_file )){ ...
There is not much need for using this long method when you could make a re-usable object out of it.
interface FileUploaderInterface
{
public function upload($path);
}
class FileUploader implements FileUploaderInterface
{
protected $File;
public function __construct($file)
{
$this->File = $file;
return $this;
}
public function upload($path)
{
if(file_exists($path.$this->File['name']))
{
$this->File["tmp_name"] = $this->File["name"] . '-' . time();
move_uploaded_file($this->File, $path . $this->File["name"]);
return false;
}
else
{
move_uploaded_file($this->File, $path . $this->File["name"]);
return true;
}
}
}
Can be used simply by using the require_once() and then this code:
$obj = new FileUploader($_FILES["fileToUpload"]);
if(!$obj->upload(dirname(__FILE__) . '/example/path/ect')) {
echo "File existed, we added the time onto the name";
}
PHP documentation says:
while (file_exists($varfoldername . $name_of_uploaded_file ))
Maybe you need a $varfoldername . '/' . $name_of_uploaded_file - best is if you could give us a var_dump of these two variables.
SOLUTION
$path = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$feedtitle = str_replace(" ", "", $feedtitle);
$feedtitle = strtolower($feedtitle);
$path = substr($path, 0, strrpos($path, "/"));
$feedlink = "http://" . "$path" . "/" . "$feedtitle" . '.xml';
PROBLEM
I am trying to generate a name for an rss feed from another field (feed title). In my query I have :
$path = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$feedtitle = str_replace(" ", "", $feedtitle);
$feedtitle = strtolower($feedtitle);
$feedlink = "$path" . "$feedtitle" . '.xml';
If feedtitle is my rss feed, $feedlink will have the value myrssfeed.xml so that part of the code works but I'm having problems with the path. Instead of writing the current path the above writes the current path & the name of the current file! e.g. if the script I'm using for this is named feedlink.php the path that is stored in the $feedlink variable is :
mywebsite.com/mydir/feedlink.phpmyrssfeed.xml
How do I remove the name of the script?
With the str_replace() function
$feedlink = str_replace("feedlink.php", "", $feedlink);
Assuming that you requested the site as mywebsite.com/mydir/feedlink.php you should consider removing everything past the last / and then add your filename to that:
$path = substr($path, 0, strrpos($path, "/") + 1);
I have a filename with a date in it, the date is always at the end of the filename.
And there is no extension (because of the basename function i use).
What i have:
$file = '../file_2012-01-02.txt';
$file = basename('$file', '.txt');
$date = preg_replace('PATTERN', '', $file);
Im really not good at regex, so could someone help me with getting the date out of the filename.
Thanks
I suggest to use preg_match instead of preg_replace:
$file = '../file_2012-01-02';
preg_match("/.*([0-9]{4}-[0-9]{2}-[0-9]{2}).*/", $file, $matches);
echo $matches[1]; // contains '2012-01-02'
If there is always an underscore before the date:
ltrim(strrchr($file, '_'), '_');
^^^^^^^ get the last underscore of the string and the rest of the string after it
^^^^^ remove the underscore
I suggest you to try:
$exploded = explode("_", $filename);
echo $exploded[1] . '<br />'; //prints out 2012-01-02.txt
$exploded_again = explode(".", $exploded[1]);
echo $exploded_again[0]; //prints out 2012-01-02
Shorten it:
$exploded = explode( "_" , str_replace( ".txt", "", $filename ) );
echo $exploded[1];
With this, use regexp when you really need to :
current(explode('.', end(explode('_', $filename))));
This should help i think:
<?php
$file = '../file_2012-01-02.txt';
$file = basename("$file", '.txt');
$date = preg_replace('/(\d{4})-(\d{2})-(\d{2})$/', '', $file);
echo $date; // will output: file_
?>
If I have filename.jpg, with PHP how would change it too filename123456789.jpg, where 123456789 is a timestamp, I currently do this,
$name = $filename;
$parts = explode(".", $name);
$filename = $parts[0].time().'.'.$parts[1];
however this just just leaves me with 123456789.
Your approach works fine too, but breaks if the filename has multiple dots. I'd rather use the pathinfo() function to accomplish this:
$info = pathinfo($filename);
$filename = $info['filename'].time().'.'.$info['extension'];
debug (output) your input and steps to find the error
function debug($var, $label = '') {
echo $label
. '<pre>'
. print_r($var, true)
. '</pre>';
}
$name = 'filename.bug.test.jpg';
debug($name, 'old filename');
$parts = explode('.', $name);
debug($parts, 'filenameparts');
$ext = array_pop($parts);
$prefix = implode('.', $parts);
$newName = $prefix . time() . '.' . $ext;
debug($newName, 'new filename');
as mention above use pathinfo instead of explode
i've used explode, couse i've used a dummy filename.
thats a no-brainer:
function getFileName($filename){
preg_match('#([^/]+)\.([\w]+)$#',$filename,$match);
return $match[1].time().'.'.$match[2];
}