I've uploaded different types of files and I save them in a folder and save into DB the path, all files load them well (.doc, xls ...) except (docx, xlsx ...) . The Docx Files It copies it to the directory but it is not possible to get its name, type size etc.
This is my code:
<?php
require_once 'connect.php';
if($_POST) {
$nombre = $_FILES['archivo']['name'];
$tipo = $_FILES['archivo']['type'];
$tamanio = $_FILES['archivo']['size'];
$ruta = $_FILES['archivo']['tmp_name'];
$destino = "../archivos/" . $nombre;
copy($ruta, $destino);
$sql = "INSERT INTO documentos (tipo,tamano,destino,fecha) VALUES ('$tipo', '$tamanio', '$nombre',NOW())";
$query = $connect->query($sql);
$connect->close();
}
My form:
<form class="form-horizontal" action="../../phpcrud/create_documentos.php" method="POST" id="create_documentos_form" enctype="multipart/form-data">
<div class="modal-body">
<div class="message_create_documentos"></div>
<div class="form-group">
<label for="apemat" class="col-sm-2 control-label">Archivo</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="archivo" name="archivo" placeholder="Archivo">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
</form>
Related
I am trying to upload images using php and html form.
<form class="form-horizontal" method="POST" action="products_photo.php" enctype="multipart/form-data">
<input type="hidden" class="prodid" name="id">
<div class="form-group">
<label for="photo" class="col-sm-3 control-label">Photo</label>
<div class="col-sm-9">
<input type="file" id="photo" name="photo" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-flat pull-left" data-dismiss="modal"><i class="fa fa-close"></i> Close</button>
<button type="submit" class="btn btn-success btn-flat" name="upload"><i class="fa fa-check-square-o"></i> Update</button>
</form>
But the issue is png extensions are not being saved to database. jpg and jpeg are stored.
Anyone has an idea how to solve this?
I am using a function to make slug for images, but the extensions for jpg and jpeg are stored in database but not for png files.
the php file:
<?php
if(isset($_POST['upload'])){
$id = $_POST['id'];
$filename = $_FILES['photo']['name'];
$conn = $pdo->open();
$stmt = $conn->prepare("SELECT * FROM products WHERE id=:id");
$stmt->execute(['id'=>$id]);
$row = $stmt->fetch();
if(!empty($filename)){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$new_filename = $row['slug'].'_'.time().'.'.$ext;
move_uploaded_file($_FILES['photo']['tmp_name'], '../images/'.$new_filename);
}
try{
$stmt = $conn->prepare("UPDATE products SET photo=:photo WHERE id=:id");
$stmt->execute(['photo'=>$new_filename, 'id'=>$id]);
$_SESSION['success'] = 'Product photo updated successfully';
}
catch(PDOException $e){
$_SESSION['error'] = $e->getMessage();
}
$pdo->close();
}
else{
$_SESSION['error'] = 'Select product to update photo first';
}
?>
I have an upload image to database code like this:
<form method="post" action="quanly.php" class="form-group justify-content-center" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="image" name="image">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<div class="col text-center">
<button type="submit" name="submit" id="add_btn" class="btn btn-primary mb-2"> <i class="fas fa-plus"></i>Submit</button>
</div>
</form>
And the PHP code:
$image = addslashes($_FILES['image']['name']);
$query = "INSERT INTO tasks (image) VALUES ('$image')";
mysqli_query($db, $query); //db is the mysql connection
Everything upload works just fine, but I have some code to display image using Bootstrap 4 modal
<?php $i = 1; while ($row = mysqli_fetch_array($tasks)) { ?>
<button type="button" class="btn btn-primary btn-sm " data-toggle="modal" data-target="#imagemodal<?php echo $row['id'];?>" <?php if (empty($row['image'])) { echo "disabled"; } ?> ><i class="fas fa-image"></i></button>
<!-- IMAGE MODAL BEGIN -->
<div class="modal fade" id="imagemodal<?php echo $row['id'];?>">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Xem ảnh/ đính kèm</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<?php echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>'; ?>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- IMAGE MODAL END -->
<?php $i++; } ?>
Which image of rows showing a small image square (error), when I view the image url, it's something like this: data:image/jpeg;base64,ei5wbmc=
Store and upload image in folder code
<?php
if(isset($_POST['but_upload'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Insert record
$query = "insert into images(name) values('".$name."')";
mysqli_query($con,$query);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
?>
<form method="post" action="" enctype='multipart/form-data'>
<input type='file' name='file' />
<input type='submit' value='Save name' name='but_upload'>
</form>
Show in display view.
<?php
$sql = "select name from images where id=1";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$image = $row['name'];
$image_src = "upload/".$image;
?>
<img src='<?php echo $image_src; ?>' >
I've done an upload page that should upload the files and set their name in the database. It works just perfect with the pictures , but the sound formats and the other ones doesn't seem to work.
This is how my html part look
<form method="post" enctype="multipart/form-data">
<div class="card card-login">
<?= FH::csrfInput() ?>
<div class="card-header text-center" data-background-color="rose" >
<h3 class="card-title">Upload</h3>
</div>
<div class="card-content">
<div class="input-group">
<span class="input-group-addon">
</span>
<div class="form-group label-floating">
<label class="control-label"><h4>Chose a name for the file</h4></label>
<br>
<input type="textd" name="name" id="name" class="form-control" value="">
</div>
<br><br>
<div class="form-group label-floating">
<label class="control-label"><h4>Choose a file</h4></label>
<br>
<input type="file" id="file" name="file" >
</div>
</div>
</div>
<div class="footer text-center">
<div class="file-upload">
<label for="submit" class="file-upload__label">
<div class="isa_error_class">
<?= FH::displayErrors($this->displayErrors)?>
</div>
<button class="btn btn-wd btn-lg" data-background-color="rose">Submit</button>
</label>
<input type="submit" name="submit" value="Submit" class="file-upload__input">
</div>
</div>
</form>
And there is the php part
if($this->request->isPost())
{
$this->request->csrfCheck();
$upload->assign($this->request->get());
$upload->user_id = Users::currentUser()->id;
$upload->name .= "." . pathinfo($_FILES['file']['name'] , PATHINFO_EXTENSION);
$value = pathinfo($_FILES['file']['name'] , PATHINFO_EXTENSION);
$upload->format = Upload::setFormat($value);
$dir = Users::currentUser()->id;
if(move_uploaded_file($_FILES["file"]["tmp_name"],'files' . DS . $dir . DS . $upload->name ))
{
if($upload->save())
{
Router::redirect('upload');
}
else
{
$upload->addErrorMessage('file','There were a problem saving in the database.');
}
}
else
{
$upload->addErrorMessage('file','There were a problem uploading it.');
}
}
The DS is the separator. The image formats seems to work perfect , but the other formats don't. Any ideas ?
You should check if u have allowed file_uploads = On in your php.ini and also check the maximum file size upload_max_filesize= 20M and to make sure that you are not passing it.
I cannot figure out why my form does not want to submit its data into my recipes table after clicking submit. When I click the submit button the form just refreshes,
I have an echo for successful set but it does not appear along with no error messages and no data in my database.
Here is the HTML
<div class="row">
<div class="main-login main-center">
<h1>Add Recipe</h1>
<form enctype="multipart/form-data" action="#" method="post">
<div class="form-group">
<label for="recipe_name" class="cols-sm-2 control-label">Recipe Name</label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_name" id="recipe_name" placeholder="Recipe Name"/>
</div>
</div>
</div>
<div class="form-group">
<label for="recipe_duration" class="cols-sm-2 control-label"> Recipe Duration </label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_duration" id="recipe_duration" placeholder="Recipe Duration"/>
</div>
</div>
</div>
<div class="form-group">
<label for="recipe_ingredient" class="cols-sm-2 control-label"> Ingredients </label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_ingredient" id="recipe_ingredient" placeholder="Ingredients"/>
</div>
</div>
</div>
<div class="form-group">
<label for="recipe_nutrition" class="cols-sm-2 control-label"> Recipe Nutrition </label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_nutrition" id="recipe_nutrition" placeholder="Recipe Nutrition"/>
</div>
</div>
</div>
<div class="form-group">
<label for="recipe_method" class="cols-sm-2 control-label"> Recipe Directions </label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_method" id="recipe_method" placeholder="Recipe Directions"/>
</div>
</div>
</div>
<div class="form-group">
<label for="profile_image">Recipe Image</label>
<input type="file" name="recipe_image" id="recipe_image">
<p class="help-block">Upload an image of the recipe</p>
<img class="recipeImage" src="./recipe_images/"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg btn-block login-button">Submit</button>
</div>
</form>
</div>
and PHP
<?php
if(isset($_POST['submit'])){
//Insert DB
$query = "INSERT INTO recipes (recipe_name, recipe_duration, recipe_ingredient, recipe_nutrition, recipe_method) VALUES (:recipe_name, :recipe_duration, :recipe_in
gredient, :recipe_nutrition, :recipe_method)";
$result = $DBH->prepare($query);
$result->bindParam(':recipe_name', $_POST['recipe_name']);
$result->bindParam(':recipe_duration', $_POST['recipe_duration']);
$result->bindParam(':recipe_ingredient', $_POST['recipe_ingredient']);
$result->bindParam(':recipe_nutrition', $_POST['recipe_nutrition']);
$result->bindParam(':recipe_method', $_POST['recipe_method']);
if($target_file){
$result->bindParam(':recipeImage', $newFilename);
}
if($result->execute()){
echo '<div class="alert alert-success" role="alert">Recipe Added!</div>';
}
if($_FILES['recipeImage']["name"]){
//Let's add a random string of numbers to the start of the filename to make it unique!
$newFilename = md5(uniqid(rand(), true)).$_FILES["profile_image"]["name"];
$target_file = "./recipe_images/" . basename($newFilename);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["recipeImage"]["tmp_name"]);
if($check === false) {
echo "File is not an image!";
$uploadError = true;
}
//Check file already exists - It really, really shouldn't!
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadError = true;
}
// Check file size
if ($_FILES["recipeImage"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadError = true;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadError = true;
}
// Did we hit an error?
if ($uploadError) {
echo "Sorry, your file was not uploaded.";
} else {
//Save file
if (move_uploaded_file($_FILES["recipeImage"]["tmp_name"], $target_file)) {
//Success!
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
}
?>
Because you have no element with name="submit" and you're testing for it here if(isset($_POST['submit'])){
Your submit should be an input, not a button:
<input type="submit" class="btn btn-success btn-lg btn-block login-button" value="Submit" />
<input type="submit" name="submit" value="Submit"class="btn btn-success btn-lg btn-block login-button">
change the submit button like this
<button type="submit" class="btn btn-success btn-lg btn-block login-button">Submit</button>
instead of
<input type="submit" class="btn btn-success btn-lg btn-block login-button" value="Submit" name="submit">
Change
<button type="submit" class="btn btn-success btn-lg btn-block login-button">Submit</button>
To
<button type="submit" name="submit" class="btn btn-success btn-lg btn-block login-button">Submit</button>
Actually you needed to add a name attribute to the button element, so that you can identify the element in the following php line
if(isset($_POST['submit'])){
The line above checks for a "POST"ed element identified by the name 'submit'.
So I am trying to insert a php script that gets values for a select element into a modal. But The php script works and gets the right info. But whenever i try and load the script into the modal like so:
<?php include 'script.php' ?>
My modal wont show up. These are my files:
Index.php
<div class="modal fade" id="upload" tabindex="-1">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Tilføj en note</h4>
</div>
<form action="scripts/upload.php" method="post" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="name">Navn:</label>
<input type="text" class="form-control" name="name" placeholder="Navn på note..">
</div>
<div class="form-group">
<label for="name">Fag:</label>
<select class="form-control">
<?php include 'scripts/getClasses.php'; ?>
</select>
</div>
<div class="form-group">
<label for="name">Beskrivelse:</label>
<textarea name="description" data-provide="markdown" rows="10"></textarea>
</div>
<label for="file">Vælg fil:</label>
<input type="file" name="file" id="file"><br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Luk</button>
<button type="submit" class="btn btn-success">Upload</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
scripts/getClasses.php
<?php
require 'funcs.php';
$function = new functions;
$class = $function->getClasses();
$numclasses = count($class);
for($i=0;$i<$numclasses;$i++)
{
$id = $class[$i]['id'];
$name = $class[$i]['name'];
echo "<option value='".$id."'>".$name."</option>";
}
?>
snippet of funcs.php
public function getClasses()
//Function that gets all the classes. Used when user adds a new note.
{
require 'connect.php';
$count = 0;
$q = $db->prepare('SELECT * FROM classes ORDER BY name ASC');
$q->execute();
while($row = $q->fetch())
{
$results[$count]['id'] = $row['id'];
$results[$count]['name'] = $row['name'];
$count++;
}
return $results;
}