Change name of uploaded file - php

I have been trying to change the name of a file after an upload with my script.
I want every file to be named as "testing". Later I am going to change "testing" to a
variable that gets a unique name. Now I just want to change the name to "testing".
Also the script always says error although the file are uploaded.
Can I get some help here please?
Here is my code:
<?php
$uploadDir = 'images/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO $db_table ( Image ) VALUES ('$filePath')";
mysql_query($query) or die('Error, query failed');
}
?>

I think you need
$fileName = "testing"; //maybe add extension
instead of getting original filename from $_FILES. Although after the file is moved you may end up with a situation of overwriting existing files as they all has the same name. To prevent that (for testing purposes) you may add something to $fileName, maybe a short random string.

Related

Cannot upload file with custom php function

I try using function to upload different kind of file by giving it variables. As shown below:
<?
function fn_fileUpload($data,$dir,$uid){
include_once($_SERVER['DOCUMENT_ROOT']."/cgi-bin/connect.php");
if(isset($data) && $data['error'] === UPLOAD_ERR_OK){
$fileTmpPath = $data['tmp_name'];
$fileName = $data['name'];
$fileSize = $data['size'];
$fileType = $data['type'];
$fileNameCmps = explode(".", $fileName);
$fileExt = strtolower(end($fileNameCmps));
$newFileName = $uid . '.' . $fileExt;
//check file ext
$okEXT = array('jpg', 'jpeg', 'png','doc','docx','pdf');
if (in_array($fileExt, $okEXT)) {
$fileDir = '/'.$dir.'/';
$dest_path = $fileDir.$newFileName;
if(move_uploaded_file($fileTmpPath, $dest_path)){
try{
$stmt2=$mysqli->prepare("insert into job_file (jfile_id, job_id, jfile_name, jfile_size, jfile_type, jfile_ext) valies(?,?,?,?,?,?)");
$stmt2->bind_param('iisiss',$zero,$uid,$newFileName,$fileSize,$fileType,$fileExt);
$stmt2->execute();
$result = 'ok';
}catch(mysqli_sql_exception $err){
$result=$err;
}
}else{
$result = 'Cannot upload file!';
}
}//in_array
}//if(isset
return $result;
}
?>
And this is how to use:
//upload file
$job_file=fn_fileUpload($_FILES['job_file'],'uploads',$_POST['passport_id']);
//upload photo
$job_img=fn_fileUpload($_FILES['job_img'],'photos',$_POST['passport_id']);
From here, the function always return : Cannot upload file!. At first I think. It might have something to do with move_uploaded_file but the file was there in /uploads directory but not with /photos. Both directories CHMOD 755 (tried 777 but no luck).
The db went through correctly. Is there any idea how to fix this?
You can only use move_uploaded_file() ONCE on a temporary file that has been uploaded through a form. This function destroys the temporary file after it has been moved, so the for the first upload in the uploads directory you can do it well but in for the second one no.

Save full URL link in database when image upload

My upload form for images is working good. Save name and path to database. I want to save full url to image along whit name instead just a name. What I mean is now in DB is saved file_name.jpg I want to save http://example.com/images/file_name.jpg. Here is the upload.php
define('MAX_FILE_SIZE', 20000000430);
$uploadDir = "../../img/";
$permitted = array('image/jpeg', 'image/jpeg', 'image/png', 'image/gif');
$fileName = $_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileType = $_FILES['image']['type'];
// make a new image name
$ext = substr(strrchr($fileName, "."), 1);
// generate the random file name
$randName = md5(rand() * time());
// image name with extension
$myFile = $randName . '.' . $ext;
// save image path
$path = $uploadDir . $myFile;
if (in_array($fileType, $permitted))
{
$result = move_uploaded_file($tmpName, $path);
if (!$result)
{
echo "Error uploading image file";
exit;
}
else
{
// keep track post values
$name = $_POST['name'];
$description = $_POST['description'];
// update data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE food set name = ?, image = ?, path = ?, description = ?
WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$myFile,$path,$description,$id));
Database::disconnect();
echo "<code>Information updated!!</code>";
}
}
What I try is to put the URL in $uploadDir.
$uploadDir = "http://example.com/img/";
But I get this error.
Warning: move_uploaded_file(http://example.com/img/75a13564a8f3305fb0a30ab95487b8de.jpg): failed to open stream: HTTP wrapper does not support writeable connections
Also tried something like this and got same error
define('domainURL', 'http://'.$_SERVER['HTTP_HOST']);
$path = domainURL . $uploadDir . $myFile;
The move_uploaded_file function does not accept file url.
It accepts image actual path.
Because, your file is getting moved physically.
e.g. $path = $_SERVER['DOCUMENT_ROOT'] . 'img/'
You may use relative or absolute path.
Relative path is "../../img/";
Absolute path should be like "/www/htdocs/img/"; (you can see absolute path in FTP client)
And you cannot use URL.
For store in DB use another one variable with URL
assign the upload path in a php variable and use $path to store it in database..
$path = "www.sitename.com/uploads/".$filename ;

Upload file with PHP using a random temporary filename

I have a piece of code that uploads a file using it's current file name which is OK unless there is a file already on the server with that name and extension. How can I modify my code so that it uploads it with a random temporary file name before it renames it?
Here's my code:
if(!empty($_FILES['file']['name'])) {
copy($_FILES['file']['tmp_name'], WEB_UPLOAD."/pdf/".$_FILES['file']['name']) or die("Error uploading file.");
$ext = strtolower(substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], ".")));
$filename = $url.$ext;
rename(WEB_UPLOAD."/pdf/".$_FILES['file']['name'], WEB_UPLOAD."/pdf/".$filename);
mysql_query ("UPDATE downloads SET file ='".$filename."' WHERE id = '".$insertid."'") or die (mysql_error());
}
Thank you for your continued help!
Pete
if(!empty($_FILES['file']['name'])) {
$targetFile = time().$_FILES['file']['name'];
copy($_FILES['file']['tmp_name'], WEB_UPLOAD."/pdf/".$targetFile) or die("Error uploading file.");
$ext = strtolower(substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], ".")));
$filename = $url.$ext;
rename(WEB_UPLOAD."/pdf/".$targetFile , WEB_UPLOAD."/pdf/".$filename);
mysql_query ("UPDATE downloads SET file ='".$filename."' WHERE id = '".$insertid."'") or die (mysql_error());
}
With file name added current time stamp so file name will be unique.
//get the extension
$ext = strtolower(substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], ".")));
//generate random name
$random_name = uniqid();
copy($_FILES['file']['tmp_name'], WEB_UPLOAD."/pdf/".$random_name . '.' . $ext) or die("Error uploading file.");
Now do whatever you want with it. The saved filename will be $random_name.'.'.$ext

how do i send a timestamped image name to mysql with PHP

Below I have included my code that uploads multiple images to a folder and the path to mysql. I am brand new so please excuse me for such a silly question but I can not figure where to start with sending this timestamp or $fileName value to mysql.
<?php
require_once('storescripts/connect.php');
mysql_select_db($database_phpimage,$phpimage);
$uploadDir = 'upload/';
if(isset($_POST['upload']))
{
foreach ($_FILES as $file)
{
$fileName = $file['name'];
$tmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileType = $file['type'];
if ($fileName != ""){
$filePath = $uploadDir;
$fileName = str_replace(" ", "_", $fileName);
//Split the name into the base name and extension
$pathInfo = pathinfo($fileName);
$fileName_base = $pathInfo['fileName'];
$fileName_ext = $pathInfo['extension'];
//now we re-assemble the file name, sticking the output of uniqid into it
//and keep doing this in a loop until we generate a name that
//does not already exist (most likely we will get that first try)
do {
$fileName = $fileName_base . uniqid() . '.' . $fileName_ext;
} while (file_exists($filePath.$fileName));
$result = move_uploaded_file($tmpName, $filePath.$fileName);
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$fileinsert[]=$filePath;
}
$cat=$_POST['cat'];//this is the category the product is stored in
$about=$_POST['about'];//this is some general information about the item
$price=$_POST['price'];//the price of the item
$item=$_POST['item'];//the name of the item
$name1=basename($_FILES['image01'][$fileName]);//the file name of the first actual jpg
$name2=basename($_FILES['image02'][$fileName]);//the file name of the sencond actual jpg
$name3=basename($_FILES['image03'][$fileName]);//the file name of the third actual jpg
$name4=basename($_FILES['image04'][$fileName]);//the file name of the fourth actual jpg
$query = "INSERT INTO image (mid, cid, about, price, item, name1, name2, name3, name4) ".
"VALUES ('','$cat','$about','$price','$item','$name1','$name2','$name3','$name4')";
mysql_query($query) or die('Error, query failed : ' . mysql_error()); }
?>
If I understand your question correctly, you need to change:
$fileinsert[]=$filePath;
to:
$fileinsert = array(); // initialize the variable before the loop
...
$fileinsert[]=$filePath.$fileName; // or just $fileName if you don't need the path in the DB
and then you need to change:
$name1=basename($_FILES['image01'][$fileName]);//the file name of the first actual jpg
$name2=basename($_FILES['image02'][$fileName]);//the file name of the sencond actual jpg
$name3=basename($_FILES['image03'][$fileName]);//the file name of the third actual jpg
$name4=basename($_FILES['image04'][$fileName]);//the file name of the fourth actual jpg
to:
$name1=$fileinsert[0];
$name2=$fileinsert[1];
$name3=$fileinsert[2];
$name4=$fileinsert[3];
Something like that should do it.

Why this php file upload validation script not working?

Dear friends, this is a script which simply upload file and insert filename into database, why is this not working ? It's just upload the file and send filename to db even after validation . Please help
<?php
//file validation starts
//split filename into array and substract full stop from the last part
$tmp = explode('.', $_FILES['photo']['name']);
$fileext= $tmp[count($tmp)-1];
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(in_array($fileext, $allowedexts)){
return true;
}else{
$form_error= "Upload file was not supported<br />";
header('Location: apply.php?form_error=' .urlencode($form_error));
}
//file validation ends
//upload dir for pics
$uploaddir = './uploads/';
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile);
// $photo value is goin to db
$photo = $upload_filename;
function send_error($error = 'Unknown error accured')
{
header('Location: apply.php?form_error=' .urlencode($error));
exit; //!!!!!!
}
//file validation starts
//split filename into array and substract full stop from the last part
$fileext = end(explode('.', $_FILES['photo']['name'])); //Ricky Dang | end()
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(!in_array($fileext, $allowedexts))
{
}
//upload dir for pics
$uploaddir = './uploads/';
if(!is_dir($uploaddir))
{
send_error("Upload Directory Error");
}
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
if(!file_exists($uploadfile ))
{
send_error("File already exists!");
}
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
if(move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile))
{
send_error('Upload Failed, cannot move file!');
}
// $photo value is goin to db
$photo = $upload_filename;
This is a cleared up version to yours, give that a go and see if you get any errors
You can find the extension of file by using this code also.
$tmp = end(explode('.', $_FILES['photo']['name']));
now $tmp got the extension of file.
Why not use PHP's built-in functions to extract the extension from the filename?
$fileext = pathinfo($_FILES['photo']['name'],PATHINFO_EXTENSION);
And if the file extension is valid, you're returning from the function without doing anything further, if it's invalid you're setting the header, but the code logic will continue to your file processing
You blindly assume the file upload succeeded, but there's many reasons for it to fail, which is why PHP provides ['error'] in the $_FILES array:
if ($_FILES['photo']['error'] === UPLOAD_ERR_OK) {
// uploaded properly, handle it here...
} else {
die("File upload error, code #" . $_FILES['photo']['error']);
}
The error codes are defined here.

Categories