I have a code that lets a person upload multiple images through a form.
Problem is, the images upload fine on to the server but not sure how to get the images to be sent into the database.
PHP:
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $targetscreenshots.$name))
$count++; // Number of successfully uploaded file
}
Where do I put the following code?
{
mysql_query("INSERT into Colleges (`files`) VALUES ('$files')"); // inserting data if file is moved
echo "Your screenshots have been uploaded successfully!"
}
This is my own code which i am using in my script.
<?php
$upath="../images/";
//uploads is the name of file array that is being uploaded.
foreach ($_FILES['uploads']['name'] as $key=>$file) {
$target = $upath.$file;
$path=substr($target,3);
// echo $path; THIS CAN BE STORED DIRECTLY TO THE DATABASE
move_uploaded_file($_FILES['uploads']['tmp_name'][$key], $target)
or die();
mysql_query(**YOUR INSERT QUERY HERE. IT WONT BE EXECUTED IF IMAGE IS NOT UPLOADED PROPERLY.**)or die(mysql_error());
}
?>
I read your comment and so i gave this answer... Kindly correct me if i have misinterpreted your question.
You are missing code that is responsible for database modification, I suggest you read some tutorials like this one.
I haven't tested it, but at least it looks like it involves all the steps required.
$files = $_FILES["files"]["tmp_name"][$f]
Just Insert the file path or name in the DB
Related
Am saving a file as a long blob in php by first saving it in a folder then to a db, the problem is that the server has write permissions so i would like to save it directly
This is what i have tried (This works perfectly):
if(isset($_POST['image'])){
$id = 0;
$image = $_POST['image'];
$tmp_image = date('YmdHisu').'.jpg';
file_put_contents($tmp_image, base64_decode($image));
$sql = "INSERT INTO fingerprint(template)
VALUES ('".addslashes(file_get_contents($tmp_image))."')";
try
{
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$rowCount=$command->execute(); // execute the non-query SQL
echo "saved successifully";
unlink($tmp_image);
}
catch(Exception $ex)
{
echo 'Query failed' , $ex->getMessage();
unlink($tmp_image);
}
}
How can i save this in a blob field in mysql without first having to save it in a folder then saving to db
Let's assume you've sent the file via Android using POST method to your server running Yii1.
First of all the physical file is contained in the $_FILES variable and in the $_POST variable, as you said, contains a string of the file encoded in base 64 format (i write this for a clear answer).
$_FILE DOCUMENTATION
Now this is how you can try to upload the file with the standard MVC yii way using yii code:
It's true that you're uploading your file from an external device but Yii came in your help with CUploadedFile Class:
Call getInstance to retrieve the instance of an uploaded file, and then use saveAs to save it on the server. You may also query other information about the file, including name, tempName, type, size and error.
In particular you should use the function getInstancesByName that returns an array of instances starting with specified array name.
$temp = CUploadedFile::getInstanceByName("image"); // $_FILES['image']
and with this you can access to the file data:
$temp->name; // Name of the file
$temp->type; // Type of the file
$temp->size; // Size of the file
// etc etc..
$temp->saveAs("/your/path/" . $tmp_image . $temp->type); // Save your file
for final you can check if the file was saved and execute your query:
if($temp->saveAs("/your/path/" . $tmp_image . $temp->type)) {
// File is saved you can execute the query for save the record in your db
} else {
// Something went wrong.
}
You can also transfer this logic in a model.
check this link for more infos
Hope this will help you.
I am working with adding a file upload system to my website and I cannot seem to get the file links to match up with the file name that is generated. I am adding a time function onto the front of the file name to make it unique (it generates a number based on the time). It does do this, but for some reason, that unique name is not saved in the database. Could someone help me figure this out?
//This is the directory where images will be saved
$target = "files/";
$target = $target. time(). basename( $_FILES['photo']['name']);
echo $target;
//postThis gets all the other information from the form
$tfid=$_POST['tfid'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$hca=$_POST['hca'];
$file=($_FILES['photo']['name']);
//Writes the information to the pic table
mysql_query("INSERT INTO pic
(tfid, file)
VALUES ('$tfid', '$file')")
or die(mysql_error());
ECHO "<strong>pic table has been saved.<br></strong>";
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "<strong>The file has been uploaded</strong>";
}
else {
//Gives an error if its not
echo "<strong>Sorry, there was a problem uploading your file.</strong>";
}
echo '<br>';
require 'insertbuttons.php';
I see what was going on now. Sorry about the comments. You'll want to save the $target variable in your database. The posted variables won't match the target. So, where you have $file in your SQL statement, you'll probably want $target instead. That should give you the name of the file, but without the extension it looks like.
I have a problem with saving PDF files to folders on my server. The code worked at one time and now it doesn't. What I want it to do is to check if someone is trying to upload a PDF when a form is submitted, and if there is a PDF in the file field it uploads it and then saves the path to the mysql database. Code is below:
if (!empty($_FILES['pdf'])){
$idir = "../files/PDF/"; //my directory file is supposed to be saved in
$randomd=rand(0000000,9999999); //creates a random number as filename
$domain = "http://".$_SERVER['HTTP_HOST'];
$file_ext = strrchr($_FILES['pdf']['name'], '.'); grabs file extension. my code checked if the file was a pdf a different way and neither seems to work.
$destination=$randomd.$file_ext; //new filename
if ($file_ext=='pdf') {
move_uploaded_file($_FILES['pdf']['tmp_name'], "$idir" . $destination);
$pdf= $domain."/files/PDF/".$destination; } else { echo("File type not supported.");
mysql_query("UPDATE tbl_listings SET pdf='$pdf' WHERE listing_id='$lid'");
}
The if not empty does not work and it always tries to upload a file, but when I check the folder nothing is in there and it doesnt update the mysql.
$_FILES['pdf'] will never be empty(when the form has been submitted), no matter if a file has been selected or not, it will always return an array.
Check $_FILES['pdf']['error'] , it will be 4 when no file has been uploaded.
I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);
I'm trying to return the name of a file uploaded using PHP after changing image files name upon uploading it.
I thought I could create a $_session['image_name'] and then call that session up on the subsequent "successful upload" page. I can't seem to get it correct. I need the name so that I can store it in the mysql database. Here's the part of my upload code that does the renaming and my attempt at creating a session:
/
/ make a unique filename for the uploaded file and check it is
// not taken... if it is keep trying until we find a vacant one
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
$now++;
$_SESSION['image_name'] = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'];
}
On my successfulUpload php page I was returning:
<p>Congratulations! Your file <? echo $_Session['image_name']; ?> upload was successful</p>
I have session_start(); at the very top of both the uploadProcessing code and the Successful uploads page.
Thanks for any help!
I see now, on your success page, $_SESSION should be capitalized.