Reputation: 303
I am saving news' pictures in my file system and also saving the path in my mysql database. But I want to save the file by setting the name in my discretion and not the file name that has been set by the uploader. I want this to prevent the possible duplication of file name in my directory. I was thinking of saving them with a unique number on it.
Send file:
$target_dir_image = "../upload/image/";
$target_file1 = $target_dir_image. basename($_FILES["nimg"]["name"]);
$move_images1=move_uploaded_file($_FILES["nimg"]`["tmp_name"],$target_file1);
// after connect the db
$nimg2=$target_file1;
Upvotes: 0
Views: 1178
Reputation: 5991
Just replace the basename()
in your $target_file1
variable, assuming that you already have a way to generate a new file name.
$newfilename = "YourNewGeneratedFilename.png";
$target_dir_image = "../upload/image/";
$target_file1 = $target_dir_image.$newfilename;
move_uploaded_file($_FILES["nimg"]["tmp_name"],$target_file1);
$nim2 = $target_file1;
Then on your query
if($stmt = $con->prepare("INSERT INTO tablename (image,path) VALUES (?,?)")){
$stmt->bind_param("ss",$newfilename,$nim2);
...
But if you don't have any, you can use the time to generate a new and unique filename (increasing the chance of not uploading the same file name, but I would still prefer a unique id to be added at the end of your file name).
Generate a new file name, along with the time it was uploaded:
$file = explode(".",$_FILES["nimg"]["name"]); /* STORE THE UPLOADED FILE NAME */
$extension = pathinfo(stripslashes($_FILES["nimg"]["name"]), PATHINFO_EXTENSION); /* STORE THE FILE EXTENSION */
$extension = strtolower($extension);
$timenow = date('his'); /* GET THE TIME NOW */
$count = count($file); /* COUNT HOW MANY STRINGS HAVE BEEN PRODUCED */
$count = $count - 1; /* TO REMOVE THE EXTENSION ON THE COUNT */
$newfilename = ""; /* ESTABLISH A CLEAN VARIABLE */
for($x = 0;$x<$count; $x++){
$newfilename .= $file[$x]; /* STORE THE EXPLODED STRING TO THE CLEAN VARIABLE */
} /* END OF FOR LOOP */
$newfilename = $newfilename."_".$timenow.".".$extension; /* PUT THE TIME AT THE END OF THE FILE NAME */
/* ...PUT HERE YOUR UPLOAD AND INSERT QUERY CODE... */
Upvotes: 2