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 ;
Related
I want to change the uploaded image filename to a certain name for example:
Original name:city.jpg -> D0000_04042018094730121.jpg (D0000 is kodeDosen and the other is a microtime timestamp.)Here is my php code:uploadDosen.php
<?php
include 'connectdb.php';
if (isset($_POST['upload_Btn'])) {
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
$kodeDosen = $_POST['kodeDosen'];
$namaJurnal = $_POST['namaJurnal'];
$tipePublikasi = $_POST['tipePublikasi'];
$status= $_POST['status'];
$gambar = $_FILES['gambar']['name'];
$sql = "INSERT INTO tbl_publikasi (kodeDosen,gambar,namaJurnal,tipePublikasi,status) VALUES ('$kodeDosen','$gambar','$namaJurnal',
'$tipePublikasi','$status')";
// execute query
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['gambar']['tmp_name'],$target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
header("location:uploadTest.php");
}
?>
Instead of using
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
Put your desired name in
$ext = end((explode(".", $_FILES['gambar']['name'])));
$target = "uploaddosen/MYNEWNAME." . $ext
$ext is taking the uploaded file name and getting the file extension. Then adding it together with your new name.
Just change the value of $target to your preferred filename.
You can try:
$extention = explode(".", $_FILES['gambar']['name']);
$extention = end($extention);
$target = $kodeDosen."_".str_replace(array(".", " "), "", microtime() ).".".$extention;
I have been trying to save uploaded images to a folder using PHP. I have been stuck on this because the name of the image saves differently to the database than the folder.
Database:assets/images/profile_pics/john_doe5a153efc8731359393775e3355df0b77n.jpg
Folder: john_doe_original.5a153efc8731359393775e3355df0b77njpeg
include("includes/header2.php");
$profile_id = $user['username'];
$imgSrc = "";
$result_path = "";
$msg = "";
/***********************************************************
0 - Remove The Temp image if it exists
***********************************************************/
if (!isset($_POST['x']) && !isset($_FILES['image']['name']) ){
//Delete users temp image
$temppath = 'assets/images/profile_pics/'.$profile_id.'_temp.jpeg';
if (file_exists ($temppath)){ #unlink($temppath); }
}
if(isset($_FILES['image']['name'])){
/***********************************************************
1 - Upload Original Image To Server
***********************************************************/
//Get Name | Size | Temp Location
$ImageName = $_FILES['image']['name'];
$ImageSize = $_FILES['image']['size'];
$ImageTempName = $_FILES['image']['tmp_name'];
//Get File Ext
$ImageType = #explode('/', $_FILES['image']['type']);
$type = $ImageType[1]; //file type
//Set Upload directory
$uploaddir = $_SERVER['DOCUMENT_ROOT'].'/name/assets/images/profile_pics';
//Set File name
$file_temp_name = $profile_id.'_original.'.md5(time()).'n'.$type; //the temp file name
$fullpath = $uploaddir."/".$file_temp_name; // the temp file path
$file_name = $profile_id.'_temp.jpeg'; //$profile_id.'_temp.'.$type; // for the final resized image
$finalname = $profile_id.md5(time());
$fullpath_2 = "assets/images/profile_pics/".$finalname."n.jpg"; //for the final resized image
//Move the file to correct location
$move = move_uploaded_file($ImageTempName,$fullpath) ;
chmod($fullpath, 0777);
//Check for valid uplaod
if (!$move) {
die ('File didnt upload');
} else {
$imgSrc= "assets/images/profile_pics/".$file_name; // the image to display in crop area
$msg= "Upload Complete!"; //message to page
$src = $file_name; //the file name to post from cropping form to the resize
}
}
if (isset($_POST['Submit'])){
//Insert image into database
$insert_pic_query = mysqli_query($con, "UPDATE users SET profile_pic='$fullpath_2' WHERE username='$userLoggedIn'");
//header("Location: account.php");
}
Thank you for your help. Let me know how I can improve my question as well.
Use $fullpath_2 in your move_uploaded_file(). change upload directiry to $uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/Halpper/';
if (isset($_FILES['image']['name'])) {
/***********************************************************
* 1 - Upload Original Image To Server
***********************************************************/
//Get Name | Size | Temp Location
$ImageName = $_FILES['image']['name'];
$ImageSize = $_FILES['image']['size'];
$ImageTempName = $_FILES['image']['tmp_name'];
//Get File Ext
$ImageType = #explode('/', $_FILES['image']['type']);
$type = $ImageType[1]; //file type
//Set Upload directory
$uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/Halpper/';
//Set File name
$file_temp_name = $profile_id . '_original.' . md5(time()) . 'n' . $type; //the temp file name
$fullpath = $uploaddir . "/" . $file_temp_name; // the temp file path
$file_name = $profile_id . '_temp.jpeg'; //$profile_id.'_temp.'.$type; // for the final resized image
$finalname = $profile_id . md5(time());
$fullpath_2 = "assets/images/profile_pics/" . $finalname . "n.jpg"; //for the final resized image
//Move the file to correct location
if (move_uploaded_file($ImageTempName, $uploaddir . $fullpath_2)) {
chmod($uploaddir . $fullpath_2, 0777);
}
//Check for valid uplaod
if (!$move) {
die ('File didnt upload');
} else {
$imgSrc = "assets/images/profile_pics/" . $file_name; // the image to display in crop area
$msg = "Upload Complete!"; //message to page
$src = $file_name; //the file name to post from cropping form to the resize
}
}
Personally I have used imagecreatefromjpeg
http://php.net/manual/en/function.imagecreatefromjpeg.php
Passed the temp uploaded file directly to this function.
Then this allows me to use imagescale for profile pic sizing.
http://php.net/manual/en/function.imagescale.php
Finally I find file-put-contents is a rather clean way to save the content.
http://php.net/manual/en/function.file-put-contents.php
I know that move_uploaded_file() sets the name of the uploaded file and sets the destination also. I have this:
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/img/profiles/'.$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file`
I have tried explode $_FILES['file']['tmp_name'] but I don't get to change the name of my uploaded file to my POST variable $newfile=$_POST["something"];
Thank you in advance
I am using
//File name
$file_name = $_FILES["file"]["name"];
$file_name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file_name);
// get extension
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
// change name
$imagename = $file_name . time() . "." . $ext;
Set the entire upload path with the file name in $targetpath variable.
In you code
$sourcePath = $_FILES['file']['tmp_name'];
$newfile=$_POST["something"]; //any name sample.jpg
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/img/profiles/'.$newfile;
move_uploaded_file($sourcePath,$targetPath) ;
Now the uploaded file name is sample.jpg
I think this will helpful for you.
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.
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.