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.
Related
hi this is the function that upload image inside temp location and save location to session for forther use
function uploadPhoto()
{
$rawImage = $_FILES['advPhoto'];
$uploader = new ImageUploader($rawImage);
$uploader->moveToProjectTempFolder();
//1 save the current image in sassion (save the attachment class inside seesion)
$uploader->saveInSession();
// $temperrary = $uploader->CurrentImgTemperraryLocation();
//2 send reponse the current image location
AjaxHelper::sendAjaxResponse("images/temp/" . $uploader->CurrentImgTemperraryLocation());
//create image tag and set the image source the "temp uploaded image path"
// done
//when the mail form is submitted
//loop through session array
//move the user uploaded/approved images to permanent folder
//save image information inside DB
}
here is the function that cause problem I wanna move the picture from temp folder to permanent location but the php_move_uploaded_file() doesn't work in my case I don't really know what is the problem please help me if you know what is the problem thnks .
function saveAdv()
{
$advTitle = $_POST['advTitle'];
$advContent = $_POST['advContent'];
if (!empty($advTitle) && !empty($advContent)) {
if (DataValidation::isOnlyPersianOrEnglish($advTitle) &&
DataValidation::isOnlyPersianOrEnglish($advContent)) {
DBconnection::insertRow('ADVERTISEMENT', ['title', 'Advertisement', 'advDate'],
[$advTitle, $advContent, date('y/m/d h:i:s')]);
// AjaxHelper::sendAjaxResponse("success");
$projectTemp = $_SESSION['ADVERTISEMENT']['Img'];
move_uploaded_file(
$projectTemp,
DOC_ROOT . "/images/advertisementImg/"
);
AjaxHelper::sendAjaxResponse($projectTemp);
}
} else {
AjaxHelper::sendErrorMessage(AjaxHelper::EMPTY_EMAIL_OR_PASSWORD);
}
}
I don't get any error I've already debuged many times but no warning and no errors at all and the location of the folders are completely correct and also there is no permission problems.
The move_uploaded_file() works pretty well at first step that I move image from system temp location to my project temp location, but doesn't work when I wanna move the image from project temp location to permanent location.
move_uploaded_file() is only for moving files which have just been uploaded in a POST request and are stored in the system temp location. As the documentation (https://php.net/manual/en/function.move-uploaded-file.php) states, it first checks whether the file is a valid upload file meaning that it was uploaded via PHP's HTTP POST upload mechanism (that's a direct quote from the docs). If it's not valid by that definition, it fails.
So, if you're trying to use move_uploaded_file() to copy files from other locations (not the system temp location) which have not been directly uploaded to that location in the current request, then it won't work. Use PHP's general file manipulation functionality for moving other files around, using the rename() function (see https://www.php.net/manual/en/function.rename.php for details).
I have a upload form and also a Dropzone file uploader beside it where users can upload their .csv files .
I want to check whether the file is new or not.
the check should contain if the contents of file are new or not
I store the file names in database for checking new files, but the problem is when the user rename the same file and upload it again.
My solution is hashing the content of each file and store it beside its name in database.
but I don't know how to hash content of .csv file in php , Laravel.
I've tried using
hash_file('md5' , Request::file('myFileName')->getClientOriginalName());
but it results in file or stream not found.
What is the correct way of checking the new file regardless of its name?
Thanks in advance.
Calculating hash of a file is a correct way to go.
Do something like this:
public function uploadFile() {
// check if upload is valid file (example: request()->file('myFileName')->isValid() )
// calculate hash of a file
$fileHash = sha1_file( request()->file('myFileName')->path() );
//search for file in database and block same file upload (Files is Elequent model)
if( Files::where('hash', $fileHash)->firstOrNull() != null) {
abort(400); // abort upload
}
// do something with file and save hash to DB
}
I have a hosted website and i want to upload my images to image directory and link the image to mysql database .
What i did:
Creating form as :
<form method=POST align=center enctype="multipart/form-data">
<input type=file name=image>
Php code :
$uploaddir = 'images/';
// echo $uploaddir;
$target = "$uploaddir".basename($_FILES['image']['name']);
echo $target;
$image = $_FILES['image']['name'];
$sql="insert into News2(image_News2)
values($image)";
$res=mysqli_query($con,$sql);
copy($_FILES['tmp_name']['name'],$target,true);
What this code actually do is only inserting the image into the database not copying the image into the images folder.
What i searched for and found :
You shouldn't specify a http:// URL as $uploaddir but a path relative to the path where the php script is running from.
So i what i really wanted to do is :
1- Copying the image into image folder directory on website.
2- Linking the copied image to the database.
you're missing the name ïmage"
not:
copy($_FILES['tmp_name']['name'],$target,true);
but:
move_uploaded_file($_FILES['image']['tmp_name'], $target);
And maybe you should try the move first, before inserting it in the database, should that action fail (or filesize = 0) etc.
do check on both the file actions and the db actions, should they fail: rollback
extra:
is only 1 column present in your database table?
is it wise to use the uploaded file's name? Duplicates can happen.
I would after checking the file insert the original name into the database. Get the autoincrement id of that record. rename the file to ./1234.jpg
through the database you can then later use the original name. But this numbering might go too var for a simple application
PHP Code :
if (isset($_FILES['image']['name']) && $_FILES['image']['error']
== 0) {
$uploads_dir = '/uploads';
$temp_file = $_FILES['image']['tmp_name'];
$name = basename($_FILES["image"]["name"]);
if(move_uploaded_file($temp_file, "$uploads_dir/$name")){
//Fire Insert Query For Insert image name in your database
}
else
{
echo "Error !! , Your image not uploaded.";
}
}
?>
as per your given data you must close Form tag then give form action ="" attribute to specify url . and if your oprating system is linux then check folder permission in set or not , also check your database table if field name is set unique or not ?
then write below code in given url file
Got the server, got the domain, got the code, getting the images successfully, making the products for the customers from the image files they upload. Yay!
Problem: all my image names are image_0001 etc.
Customers can't rename image files from iPhones and do not care to from PCs.
So I was thinking about putting a short form on the upload page asking for customer's last name and having the PHP code attach that name to the image file(s) being uploaded.
If it's not possible, I'm sorry for the inconvenience.
You can rename files after they have been saved to your server, check out the PHP manual for the rename function - http://www.php.net/manual/en/function.rename.php, or just while you are moving them from the tmp directory, you can specify a different name for the uploaded file. See http://www.php.net/manual/en/function.move-uploaded-file.php
Be careful to include something in your code for dealing with naming conflicts.
This one might help :
$imagename = basename($_FILES['file']['name']);
$ext = pathinfo($imagename , PATHINFO_EXTENSION); //we want to change the file name but not the extension
$newImagename= $imageName.$username.'.'.$ext; //assuming you hold the username in $username
if (move_uploaded_file($_FILES['file']['tmp_name'], "/path/{$newImagename}"))
{
....
}
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);