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')");
}
?>
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'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 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
Thank you in advance. I've checked similar questions and they are not helping because the work flow is set up differently.
Trying to get working:
1.user uploads image via form field
2.(SCRIPT 1) on other page script assigns unique name (SCRIPT 2), saves image file to server and image URL is uploaded to SQL. Goes to new page at end of script.
Problem is I'm not getting errors, the script runs and the new page opens but there is no file saved on the server and no data inserted into the SQL table (the entry date adds but not the image URL). My PHP.ini instructions far exceeds the size of the images I've been testing with. The folder location is chamode 0777. I'm posting the whole script because with getting errors it's hard to see where problem lies.
Image processing
<?php
require_once 'unique_gen.php';
$page_path = $_POST['page_path'];
$imgloc = "/avatars/";
//up one directory level
$store_loc = "..".$imgloc;
$link_loc = "http://www.webapge.com".$imgloc;
//Upload and characterize image file
if(isset($_FILES['image'])){
//File
$upload['image'] = $_FILES['image'];
//Verify
if ($upload['image']["error"] > 0){
die ("File Upload Error: " . $upload['image']["error"]);
}else{
//Upload
$img_ext = end(explode('.', $upload['image']['name']));
//Unique code generator
$image_name = implode('.', array(unique_generator(),$img_ext));
while(file_exists($store_loc.$image_name)){
$image_name = implode('.', array(unique_generator(),$img_ext));
}
$image_name = $upload['image']['name'];
//Move file to another location
move_uploaded_file($upload['image']["tmp_name"],$store_loc.$image_name) or exit("<br>Error, IMAGE file not moved!");
//Save location as link
$link_to_img = $link_loc.$image_name;
}
}else{
$image_name = "";
}
//connect to db
$con=mysqli_connect("localhost","usernm","pssword","dbName");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert to SQL
$sql="INSERT INTO comments (avatar, entry_date)
VALUES
('$_POST[link_to_image]', now())";
//verify insert
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
//direct to new page using variable
header('Location: http://www.weBsite.com/' . $page_path);
//close session
mysqli_close($con);
?>
Unique generator
<?php
function unique_generator($lot_size = 15){
$alpha_s = range('a', 'z');
$alpha_l = range('A', 'Z');
$numbers = range(0, 9);
$char = array_merge($alpha_l,$alpha_s,$numbers);
$code = "";
for($i = 0; $i < $lot_size; $i++){
$key = rand(0,count($char)-1);
$code .= $char[$key];
}
return $code;
}
?>
Try putting this at the top of your script:
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');
?>
This at the bottom:
<?php
print_r(array_keys(get_defined_vars()));
print_r(array_values(get_defined_vars()));
?>
The below code, checks in my folder 'mysqls' for .sql files. Then I want it to execute the .sqls into the database.
<?php
$dirf = 'mysqls';
$dir = scandir($dirf);
unset($dir['0']);
unset($dir['1']);
foreach($dir as $file) {
$sql = file_get_contents($file);
$qr = $dbh->exec($sql);
}
?>
I've used die(var_dump($sql)); although it comes up with bool(false)
The code finds all the files that have the .sql extension successfully, although it does not execute it.
You have to add the directory for file_get_contents():
$sql = file_get_contents($dirf . '/'. $file);