I am trying to add a URL to a image file name before uploading it to database. It seems that nothing worked out. Have searched Google and Stackoverflow. I guess I am missing something. Here's my code, please find the comment 'here is the issue'
I have a variable $value which pulls latest ID from database.
All I have to achieve is add path to the variable: "http://example.com/location/something/"
Desired Output : the image should be renamed as http://example.com/location/something/1.jpg
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$title = $_POST['title'];
$file = $_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$info = pathinfo($_FILES['file']['name']);
$ext = $info['extension']; // get the extension of the file
$folder="uploads/";
function execute_scalar($sql,$def="") {
$rs = mysql_query($sql) or die("bad query");
if (mysql_num_rows($rs)) {
$r = mysql_fetch_row($rs);
mysql_free_result($rs);
return $r[0];
mysql_free_result($rs);
}
return $def;
}
$value = execute_scalar("select max(ID)+1 from tablename");
$newname = "$value.".$ext; // Here is the issue.
$newname = "http://example.com/location/something/"."$value.".$ext; //did not work
$newname = "http://example.com/location/something/ $value.".$ext; //did not work
// even tried assingning url to variable still did not worked
if(move_uploaded_file($file_loc,$folder.$newname))
{
$sql="INSERT INTO tablename(id,title,image)VALUES('$value','$title','$newname')";
mysql_query($sql);
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
is it something with URL?
Try moving your quotes like below:
$newname = "http://example.com/location/something/". $value ."." . $ext;
The problem is that you are not allowed to use / (slash) in your file name, because it acts as directory path.
I found a solution :
$newname = "http:\\//www.example.com\/location\/something\/\/$value.".$ext;
It is working :D
Related
this is my code
<?php
include 'koneksi.php';
$judul_artikel = $_POST['judul_artikel'];
$isi_artikel = $_POST['isi_artikel'];
$tanggal_artikel = date('Y-m-d');
$tag_artikel = $_POST['tag_artikel'];
$filetmp = $_FILES["gambar_artikel"]["tmp_name"];
$filename = $_FILES["gambar_artikel"]["name"];
$filetype = $_FILES["gambar_artikel"]["type"];
$filepath = "img/".$filename;
move_uploaded_file($filetmp, $filepath);
$query = mysql_query('INSERT INTO artikel(judul_artikel,isi_artikel,tanggal_artikel,tag_artikel,gambar_artikel) VALUES ("'.$judul_artikel.'","'.$isi_artikel.'","'.$tanggal_artikel.'","'.$tag_artikel.'","'.$filepath.'")')or die(mysql_error());
if ($query) {
header('location:artikel.php?notif=berhasil');
} else {
header('location:artikel.php?notif=gagal');
}
?>
the problem I face is, I want to copy the image file to another directory after I upload it, and input it into the mysql database too, but when I execute, the file that I upload is not copied in the directory that I want, and is not inputted into the mysql database, how to handle it ?
try to wrap it inside if condition like this
if(move_uploaded_file($filetmp, $filepath)){
echo "success";
}else{
echo "failed";
}
and make sure you set the folder permission
I currently created a system that allowed a user to upload a photo only. The photo the already upload can be replaced if the user want to change it.
The current code shows that there's no error in this function. The URL updated at MySQL database. But the problem is the image doesn't update. Below is my current code:
update_photo_before.php
<?php
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$last_insert_id = null;
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
$defID = "before_" . $report_id;
$imgPath = "images/$defID.png";
$ServerURL = "http://172.20.0.45/tgotworker_testing/android/$imgPath";
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
if ($sql){
move_uploaded_file($_FILES['uploadFile']['name'], $imgPath); //line 28
echo "<script>alert('Saved')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
}else{
echo "Error!! Not Saved";
}
} else {
echo "<script>alert('File not allowed')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
}
?>
My folder images are located at 'tgotworker_testing' --> 'android' --> 'images'.
For update_photo_before.php:
'tgotworker_testing' --> 'pages' --> 'dashboard' --> 'engineer' --> 'view_task' --> 'update_photo_before.php'
Can anyone fix my problem? Thanks!
You check to see if the database gets updated, but not if the image is saved to the server.
move_uploaded_file() returns true on success and false on failure. So you can do a similar test as you have for $sql in your code.
<?php
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$last_insert_id = null;
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
$defID = "before_" . $report_id;
$imgPath = "images/$defID.png";
$ServerURL = "http://172.20.0.45/tgotworker_testing/android/$imgPath";
// Check if image is uploaded to folder
if(move_uploaded_file($_FILES['uploadFile']['name'], $imgPath) === true) {
// If upload succeeds, then update database
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
// Check if database updated
if (!$sql){
echo "Error!! Database not updated.";
} else {
// Success!
header("Location: view_task.php?report_id=".$_POST['report_id']);
}
} else {
// Could not upload file
echo "Error!! Could not upload file to server.";
}
}
When PHP can't upload the file it will throw a warning. If you turn on your warnings while you are debugging, it should give you the reason why it's not working and you will be better able to solve the problem.
Put these lines at the top of the script to show all warnings and errors:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
I've seen questions similar to this but no one seems to have the problem I do.
I've set up a process to check to see if the filename already exists in a MySQL table, and if it does, it puts a timestamp between the filename and the extension (E.G. Test.PDF becomes Test-19:25:36 if it's a duplicate), thus negating any database conflicts.
My issue is that the while the database is updated correctly, the duplicate file isn't uploaded with the timestamp in the name. Instead, it uses the duplicate name and just overwrites the original and creates a ghost "filename" listing in the database.
I've seen you can use move_uploaded_file to rename files in the servers memory before they're uploaded, but I've tried multiple ways and can't get it to rename the file in memory BEFORE attempting to write it to the "/uploads" folder. Here's the upload code:
<?php
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['submit'])) {
// START OF PRE-EXISTING FILE CHECK
$filename = $_FILES['file1']['name'];
$dupeCheck = "SELECT * FROM tbl_files WHERE filename = '$filename'";
if ($output = mysqli_query($con, $dupeCheck)) {
if (mysqli_num_rows($output) > 0) {
$fileArray = pathinfo($filename);
$timeStamp = "-" . date("H:i:s");
$filename = $fileArray['filename'] . $timeStamp . "." . $fileArray['extension'];
}
}
// END OF PRE-EXISTING FILE CHECK
if($filename != '')
{
$trueCheck = true;
if ($trueCheck == true) {
$sql = 'select max(id) as id from tbl_files';
$result = mysqli_query($con, $sql);
//set target directory
$path = 'uploads/';
$created = #date('Y-m-d H-i-s');
$moveTargetVar = "uploads/" . $filename;
move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar);
// insert file details into database
$sql = "INSERT INTO tbl_files(filename, created) VALUES('$filename', '$created')";
mysqli_query($con, $sql);
header("Location: index.php?st=success");
}
else
{
header("Location: index.php?st=error");
}
}
else
header("Location: index.php");
}
?>
Any advice on how to rename a file before it's written to the uploads folder?
I'd suggest not using : to separate your time stamp, because that will cause issue with file name restrictions. Try doing something like:
$timeStamp = "-" . date("H-i-s");
Solved by replacing move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar); with move_uploaded_file($_FILES['file1']['tmp_name'],$path . $filename);
Deprecated $moveTargetVar = "uploads/" . $filename;
I'm trying to upload the file's path into my database. But nothing is being inserted. My file gets uploaded to target directory successfully. I want to insert the path too, but can't do it. I believe I'm doing some mistake in the Insert Into statement. Please let me know what's wrong?
My upload.php code is below:
<?php
// variables
$conn = mysqli_connect('localhost','root','abcdef','trademark');
if(!$conn) {
echo "Not Connected To Server";
}
else {
define('UPLOAD_DIR', 'uploads/');
$fileName = $_FILES['file'];
// check for which action should be taken if file already exist
//Rename file name
if(file_exists(UPLOAD_DIR . $fileName['name']))
{
$updatedFileName = update_file_name(UPLOAD_DIR.$fileName['name']);
move_uploaded_file($fileName['tmp_name'], $updatedFileName);
echo"FILE SUCCESSFULLY UPLOADED!! " . "<br/><br/><br/>"; //after renaming
}
// If no such file already exists, then upload it as it is
else
{
move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);
echo " FILE SUCCESSFULLY UPLOADED!! ". "<br/><br/>";
}
// function to rename file
function update_file_name($file)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = substr($file,0,($dir+1));
$arr = explode('/',$file);
$fName = trim($arr[(count($arr) - 1)],$ext);
$exist = FALSE;
$i = 2;
while(!$exist)
{
$file = $dr.$fName.'_'.$i.$ext;
if(!file_exists($file))
$exist = TRUE;
$i++;
}
return $file;
} // function to rename ends
$sql = "INSERT INTO file (Path) VALUES (' " . mysqli_real_escape_string( UPLOAD_DIR.$fileName['name']) . " ')";
$r = mysqli_query($conn,$sql);
echo 'file info inserted';
}
?>
Check syntax for function mysqli_real_escape_string
getting warning message as,
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1
given in
I am trying to upload a file using php and store the files information in a database. The database part is working correctly, however I am trying to move the files to a directory called videos/, however the files are not moving to this directory. Here is my php code:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('manchesterunited');
if(isset($_POST['submit']))
{
$name = $_FILES['file']['name'];
$temp = $_FILES['file']['tmp_name'];
move_uploaded_file($temp,"videos/".$name);
$url = "localhost/manchesterunited/videos/$name";
mysql_query("INSERT INTO video VALUES ('','$name','$url')");
}
?>
Try the following code with replacing "/full/path/to/" with the actual directory. Usually this is something like "/home/username/public_html/"
if(isset($_POST['submit']))
{
$dir = '/full/path/to/manchesterunited/videos/';
$file = $dir . basename($_FILES['file']['name']);
$temp = $_FILES['file']['tmp_name'];
move_uploaded_file($temp,$file);
$url = "localhost/manchesterunited/videos/$name";
mysql_query("INSERT INTO video VALUES ('','$name','$url')");
}
?>