I'm creating a form where I've a place for attaching files. But, files with specific extensions like .xls, .sql etc., are not getting attached. But, other files like .docx, .pdf etc., are getting attached. This is how I tried:
function file_upload($control_id, $target_directory) {
if(isset_file($control_id)) {
if(file_exists($target_directory) == false) {
mkdir($target_directory, 0777, true); //to be create the directory recursively
}
$file_name = basename($_FILES[$control_id]["name"]); //to be get file name
write_log($file_name);
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION); //to be get file extension
write_log($file_extension);
$file_size = $_FILES[$control_id]["size"]; //to be get file size in bytes
write_log($file_size);
$target_file_name = round(microtime(true) * 1000).".".$file_extension; //to be get target file name
$target_file_path = $target_directory.$target_file_name; //to be get target file
if(file_exists($target_file_path) == true) {
chmod($target_file_path, 0755); //Change the file permissions if allowed
unlink($target_file_path); //remove the file
}
if (move_uploaded_file($_FILES[$control_id]["tmp_name"], $target_file_path) == true) {
$arr = array(
"status" => true,
"message" => "The file ".$file_name." has been uploaded.",
"file_name" => $file_name,
"file_extension" => $file_extension,
"file_size" => $file_size,
"uploaded_file_name" => $target_file_name,
"uploaded_file_path" => $target_file_path
);
} else {
$arr = array(
"status" => false,
"message" => "Sorry, there was an error uploading your file."
);
}
} else {
$arr = array(
"status" => false,
"message" => "Please select file"
);
}
//echo json_encode($arr);
return $arr;
}
$id = intval(mysqli_real_escape_string($mysqli, $_REQUEST["id"]));
$upload_directory = "uploads/attachments/";
$result = file_upload("contract_attachment", "../".$upload_directory);
if($result[status] == true) {
$query = "insert into `attachments`
(
`id`,
`file_name`,
`file_extension`,
`file_size`,
`uploaded_file_name`,
`uploaded_file_path`
)
values
(
'id',
'".addslashes($result['file_name'])."',
'".$result[file_extension]."',
'".$result[file_size]."',
'".$result[uploaded_file_name]."',
'".$upload_directory.$result[uploaded_file_name]."'
)";
mysqli_query($mysqli, $query) or throwexception(mysqli_error($mysqli));
}
echo json_encode(array("message" => "Record submitted successfully"));
exit;
The problem is, when ever I try to attach a file with extension .xls or .sql, the $file_name, $file_extension, $file_size will get a value. For example, if the file I'm attaching is format.xls, it showed $file_name = format, $file_extension = .xls and $file_size = 0. Since the file size it's taking is zero, the condition "$result[status]" fails. So, the file is not getting attached.
If I attach files like .pdf or .docx I get the correct values. For example, if I attach file like format.pdf, it showed $file_name = format, $file_extension = .pdf, $file_size = 9824. And the file is also getting attached.
But, I don't know what's wrong with this code, since files with extensions .xls and .sql are not getting attached. Can someone correct this and tell whats wrong with this?
Related
Im a noobie in php but still im trying :) Im making bulk video uploader/importer to database. Looking ideas how to extract thumbnails from videos on upload and add those thumbnails to mysql database for each video... :/ Im trying using ffmpeg, but i dont found the way how to implement it to my code...
<?php
// Database
include 'config/database.php';
if(isset($_POST['submit'])){
$url = "localhost/";
$uploadsDir = "uploads/";
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
// Velidate if files exist
if (!empty(array_filter($_FILES['fileUpload']['name']))) {
// Loop through file items
foreach($_FILES['fileUpload']['name'] as $title=>$val){
// Get files upload path
$fileName = $_FILES['fileUpload']['name'][$title];
$tempLocation = $_FILES['fileUpload']['tmp_name'][$title];
$targetFilePath = $uploadsDir . $fileName;
$fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
$withOutExtension = pathinfo($fileName, PATHINFO_FILENAME);
$uploadDate = date('Y-m-d H:i:s');
$uploadOk = 1;
if(in_array($fileType, $allowedExts)){
if(move_uploaded_file($tempLocation, $targetFilePath)){
$sqlVal = $withOutExtension;
$sqlVal2 = $url . $uploadsDir . $fileName;
$sqlVal3 = null;
$randomID = rand(1000, 999999);
$sqlVal4 = ('<p><video controls="" src="/' . $sqlVal2 . '" width="640" height="360" class="note-video-clip"></video><br></p>');
$slug = str_replace(' ', '-', $withOutExtension);;
$file = $uploadsDir . $fileName;
$filesize = filesize($file); // bytes
$filesize = round($filesize / 1024 / 1024, 1);
} else {
$response = array(
"status" => "alert-danger",
"message" => "File coud not be uploaded."
);
}
} else {
$response = array(
"status" => "alert-danger",
"message" => "I want mp4 file."
);
}
// Add into MySQL database
if(!empty($sqlVal)) {
$insert = $conn->query("INSERT INTO applications (id, title, description, custom_description, details, image, slug, file_size, license, developer, url, buy_url, type, votes, screenshots, total_votes, counter, hits, category, platform, must_have, featured, pinned, editors_choice, created_at, updated_at) VALUES ('$randomID', '$sqlVal', 'Video .mp4 Live Wallpaper. Animated wallpaper is a cross between a screensaver and desktop wallpaper. Like a normal wallpaper, an animated wallpaper serves as the background on your desktop, which is visible to you only when your workspace is empty, i.e. no program windows block it from view.', '$sqlVal3', '$sqlVal4', '99999.jpg', '$slug', '$filesize MB', 'free', 'n/a', '$sqlVal2', '$sqlVal3', '1', '0.00', '', '0', '0', '1', '22', '6', '1', '1', '0', '1', '2021-11-11 16:55:36', '2021-11-11 16:55:36')");
if($insert) {
$response = array(
"status" => "alert-success",
"message" => "Files successfully uploaded."
);
} else {
$response = array(
"status" => "alert-danger",
"message" => "Files coudn't be uploaded due to database error."
);
}
}
}
} else {
// Error
$response = array(
"status" => "alert-danger",
"message" => "Please select a file to upload."
);
}
}
?>
Concerning the FFMpeg part, I think a good way to start is to actually use the PHP-FFMpeg library. The Basic Usage section in the documentation contains an example on how to generate a frame for a given video:
require 'vendor/autoload.php';
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open('video.mpg');
$video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(10))
->save('frame.jpg');
A simplified process would be as follows:
The user uploads a video, after which the video gets moved to a different
directory.
Now you can use the snippet above, with the frame method to get a thumbnail for your video.
After the image saving is done, you just need to add it to your database.
If the thumbnails refer to the image column in your table, you can get away with just inserting the filename, frame.jpg (or even the complete filepath, /public/path/to/frame.jpg).
If the thumbnails refer to the screenshots column in your table, and you want to have multiple thumbnails for your video, then you should consider creating a new table with a one-to-many relationship (from your video/application to a new table, e.g. thumbnails)
Then when the user gets to a page where the image should be displayed, just select it from the table and display it with an <img> tag (with the public filepath).
I would also strongly recommend not to save the complete <video> tag into your database, but instead add it to the page where you actually want to show your video.
Example:
<?php
$result = $conn->query('SELECT ...');
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<video src="<?php echo $row['video-column-path']; ?>"</video>
<?php
}
} else {
?>
No videos here
<?php
}
$conn->close();
?>
Found solution, now need to understand how to import generated thumbnail url to database field for video...
// Velidate if files exist
if (!empty(array_filter($_FILES['fileUpload']['name']))) {
// Loop through file items
foreach($_FILES['fileUpload']['name'] as $title=>$val){
// Get files upload path
$fileName = $_FILES['fileUpload']['name'][$title];
$tempLocation = $_FILES['fileUpload']['tmp_name'][$title];
$targetFilePath = $uploadsDir . $fileName;
$fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
$withOutExtension = pathinfo($fileName, PATHINFO_FILENAME);
$uploadDate = date('Y-m-d H:i:s');
$uploadOk = 1;
$randomID = rand(1000, 999999);
//Get one thumbnail from the video
$ffmpeg = "C:\\ffmpeg\\bin\\ffmpeg";
//echo $ffmpeg;
$imageFile = 'pic/thumb_'.time().'_'.$randomID.'.jpg';
$size = "120x90";
$getFromSecond = 1;
echo $cmd = "$ffmpeg -i $tempLocation -an -ss $getFromSecond -s $size $imageFile";
echo "<br>";
if(!shell_exec($cmd)){
echo "Thumbnail Created!";
}else{
echo "Error creating Thumbnail";
}
I'm new to php and I can't seem to upload .docx files to the path specified.
It goes directly to invalid file type.
enter code here
if(!empty($_FILES["file"]["name"])) {
$allowed_types = ["application/msword"];
if(in_array($_FILES["file"]["type"], $allowed_types)) {
$input_name = "file";
$upload_path = "../finaid_organization/assets/documents";
$file_name = (!empty($_FILES[$input_name]["name"]) ? basename($_FILES[$input_name]["name"]) : "");
$file_name = "ld_".date("YmdHis").".".pathinfo($file_name)["extension"];
$path = $this->do_upload($input_name, $upload_path, $file_name);
$path = "/assets/documents/".$path;
$data += ["location_path" => $path];
$this->model_loan_doc->insert($data);
$ret = [
"success" => true,
"msg" => "<span class='fa fa-check'></span> Success"
];
} else {
$ret = [
"success" => false,
"msg" => "<span class='fa fa-warning'></span> Invalid file type"
];
}
}
You'd probably added a docx document, which you have to check with a different filetype
For docx check this MIME type:
application/vnd.openxmlformats-officedocument.wordprocessingml.document
so your array should be:
$allowed_types = ["application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"];
I have this script that is uploading file to directory and form data to database. But some how the file is not uploading and says the
variable '$filedestination' is undefined.
if(!isset($error)){
try{
if(isset($_FILES['cv'])){
$file = $_FILES['cv'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('pdf', 'doc');
$cl_name = e($_POST['cl_name']);
if(in_array($file_ext, $allowed)){
if($file_error === 0){
$new_file_name = 'cv-'.$cl_name.'-'.$file_ext;
$file_destination = 'cv/' . $new_file_name;
if(move_uploaded_file($file_tmp, $file_destination)){
} else{
$error[] = 'No se podido subir el c.v.';
}
}else{
$error[] = 'Problema';
}
}
}
$handler = $db->prepare('INSERT INTO work_with_us (work_area, cl_name, cl_last_name, cl_dir, cl_city, cl_provincia, cl_tel, cl_email, work_comentario, is_cv, cv_url) VALUES (:work_area, :cl_name, :cl_last_name, :cl_dir, :cl_city, :cl_provincia, :cl_tel, :cl_email, :work_com, :is_cv, :cv_url)');
$handler->execute(array(
':work_area' => e($_POST['work_area']),
':cl_name' => e($_POST['cl_name']),
':cl_last_name' => e($_POST['cl_last_name']),
':cl_dir' => e($_POST['cl_dir']),
':cl_city' => e($_POST['cl_city']),
':cl_provincia' => e($_POST['cl_provincia']),
':cl_tel' => (int)$_POST['cl_tel'],
':cl_email' => e($_POST['cl_email']),
':work_com' => e($_POST['work_comentario']),
':is_cv' => 'Si',
':cv_url' => $file_destination
));
}catch(PDOException $e){
$error[] = $e->getMessage();
}
}
Thing is i have the same script used, in other file and for uploading pictures and it works fine but this one for .pdf and .doc its somehow not working.
You are only allowing pdf and doc :
$allowed = array('pdf', 'doc');
So png is not allowed. As for the word file, make sure you are uploading a .doc file and not a .docx since it will not be allowed. You can add a list of allowed extensions that covers all Microsoft word extensions.
As for Microsoft extensions, check this link.
just define your $filedestination variable globally means out of if block. Your Code is OK.
Give R/W permission to the folder in which you want to move/upload your file.
Actually due to R/W permission your file is not moving try Chmod command for giving R/W permission ; if you are working on linux.
Kindly check if there is any content in $error or check $error variable value...
my another suggestion is rather than to check $file['error'],
check (getimagesize($_FILES["fileToUpload"]["tmp_name"]!==false)
Please make sure that a folder named 'cv' exists in your localserver.
And, I just noticed in your code:
$new_file_name = 'cv-'.$cl_name.'-'.$file_ext;
You will have an output like this: myfile-doc
When it is supposed to be: myfile.doc
So, I suppose it should be:
$new_file_name = 'cv-'.$cl_name.'.'.$file_ext;
I do not know if this could help you but I just notice it.
I'm using MashApe API to upload images to Imgur using PHP as follows:
$valid_file_extensions = array(".jpg", ".jpeg", ".gif", ".png");
$file_extension = strrchr($_FILES["file"]["name"], ".");
if (in_array($file_extension, $valid_file_extensions)) {
if (#getimagesize($_FILES["file"]["tmp_name"]) !== false) {
$filename = $_FILES['file']['tmp_name'];
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
$response = Unirest\Request::post("https://imgur-apiv3.p.mashape.com/3/image",
array(
"X-Mashape-Key" => "key",
"Authorization" => "Client-ID ID",
"Content-Type" => "application/x-www-form-urlencoded"
),
array(
"image" => base64_encode($data)
)
);
var_dump(base64_encode($data));
$result = json_decode($response->raw_body);
if ($result->success) {
var_dump($result);
} else {
$Pointer->Bootstrap()->Alert($result->data->error, "danger");
}
}
}
but it always give me the following error: Image is corrupted or format is not supported.
If you downloaded a webm and changed the file type to gif when you saved it, the conversion is too corrupt for imgur. Try Cloudconvert until one of us figures out how to do it offline.
I recommend ShareX for automatic uploads to imgur.
Very new to this and have been trying to get it to work.
I have a bucket called app. I have followed the instructions to give my app permissions to the GCS (https://developers.google.com/appengine/docs/python/googlestorage/index#Prerequisites). It seems to be setup correctly.
I followed How do I upload images to the Google Cloud Storage from PHP form? which has worked for others. I haven't really diverted from it.
I get move_uploaded_file returning TRUE, but no file in GCS.
The output is "MoveResult did succeed".
Anyone see anything I am doing wrong. Am I missing some setup code or something?
Here is the code:
if(!is_uploaded_file($_FILES['file']['tmp_name'])) {
$profile_pic_path='default';
}
else { //file exists
$gs_name = $_FILES["file"]["tmp_name"];
$fileType = $_FILES["file"]["type"];
$fileSize = $_FILES["file"]["size"];
$fileErrorMsg = $_FILES["file"]["error"];
$fileExt = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
// change name if you want
$fileName = 'profile_pic.jpg';
// put to cloud storage
$image = file_get_contents($gs_name);
$options = [ "gs" => [ "Content-Type" => "image/jpeg"]];
$ctx = stream_context_create($options);
//file_put_contents("gs://app/".$fileName, $gs_name, 0, $ctx);
if(!move_uploaded_file($gs_name, 'gs://app/'.$fileName)){
echo json_encode(array('success' => 0,'error_message' => "MoveResult did not succeed"));
exit;
}
else{
//Get image key in or path or what not. THIS IS THE NEXT STEP
//$profile_pic_path=<something>;
echo json_encode(array('success' => 1,'info_message' => "MoveResult did succeed"));
exit;
}
}