I am trying to upload a pdf file and an image in php mysql but it seems that the move_uploaded_file function can only work with one file. I have tried to make it work with both files but it doesn't seem to me working. It moves just the images to the target folder and adds both image name and pdf name to the database but it doesn't move the pdf to target folder. This is the code. pls help
<?php
session_start();
require_once("includedfunctions.php");
include 'dbh.php';
if (isset($_POST['submit'])){
$title=$_POST['title'];
$author=$_POST['author'];
$target = "img/pic_book/";
$target2 = "img/pdf/";
$imgname = basename($_FILES["cphoto"]["name"]);
$bookname = basename($_FILES["book"]["name"]);
$newname = $target.basename($_FILES["cphoto"]["name"]);
$newname2 = $target2.basename($_FILES["book"]["name"]);
$img_type = pathinfo($newname,PATHINFO_EXTENSION);
$book_type = pathinfo($newname2,PATHINFO_EXTENSION);
if($img_type!='jpg' && $img_type!='JPG' && $img_type!='png' && $img_type!='PNG'){
$message="Please ensure you are entering an image";
}else{
if($book_type != 'pdf'){
$message="books must be uploaded in pdf format";
}else{
if(!preg_match("/^[a-zA-Z'-]+$/",$author)){
$message = "<p style='color:red'>Please enter the real name of the author; not a nickname.</p>";
}else{
if (move_uploaded_file($_FILES["cphoto"]["tmp_name"], $newname)) {
if(move_uploaded_file($_FILES["book"]["tmp_name"], $newname2));{
$sql = "INSERT INTO books (Title, Author, pathtopdf, pathtoimage) VALUES ('$title', '$author', '$bookname', '$imgname')";
$result = mysqli_query($conn, $sql);
if($result){
$message = "upload successful";
}else{
$message = "upload failed1";
}
}
}else{
$message = "upload failed";
}
}
}
}
}
else{
$message="";
$title="";
}
?>
<html>
<head>
<title>Libraria</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/contactcss.css" rel="stylesheet">
<script src="js/respond.js"></script>
</head>
<body>
<br><br><br><br><br>
<!-- content -->
<div class="container">
<?php
echo '<p>Welcome ' . $_SESSION['name']. '</p><br>';
echo '<p>' . $message. ' </p>';
?>
<br><br>
<!--form-->
<div class="row">
<form action="admin2.php" method = "post" enctype="multipart/form-data">
<label for="Title">Title</label><br>
<input type="text" id="fname" value ="<?php echo $title; ?>" name="title" placeholder="Title of the book" required><br>
<label for="author">Author</label><br>
<input type="text" id="lname" name="author" placeholder="Author of the book" required><br>
<label for="Cover photo">Cover photo</label><br>
<input type="file" id="cphoto" name="cphoto" required><br>
<label for="book">Book</label>
<input type="file" id="book" name="book" required><br>
<button class="submit" type="submit" name="submit"><b>Upload</b></button>
</form>
</div>
</div>
</body>
</html>
Code is all correct. just check pdf size. if size is more than 4MB than it will not allowed to upload. you need to increase upload file size in php.ini file or apache config settting file.
Have a great day :)
application/pdf is the mime type for pdf not just pdf.
Related
I created a page that can add new records to my database, everything is working fine but when I'm trying to upload a pdf file, it doesn't store to the correct folder. It should be stored in my "uploads". When I check my database, it doesnt link properly it should be ../uploads/example.pdf instead of example.pdf only
<?php
require('db.php');
include("auth.php");
$status = "";
if(isset($_POST['new']) && $_POST['new']==1)
{
$trn_date = date("Y-m-d H:i:s");
$fname =$_REQUEST['fname'];
$lname = $_REQUEST['lname'];
$memo = $_REQUEST['memo'];
$file = $_REQUEST['file'];
$submittedby = $_SESSION["username"];
$ins_query="insert into user (`trn_date`,`fname`,`lname`,`memo`,`submittedby`,`file`) values ('$trn_date','$fname','$lname','$memo','$submittedby','$file')";
mysqli_query($con,$ins_query) or die(mysql_error());
$status = "New Record Inserted Successfully.</br></br><a href='view.php'>View Inserted Record</a>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert New Record</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>Dashboard | View Records | Logout</p>
<div>
<h1>Insert New Record</h1>
<form name="form" method="post" action="">
<input type="hidden" name="new" value="1" />
<p><input type="text" name="fname" placeholder="Enter Date" required /></p>
<p><input type="text" name="memo" placeholder="Enter Memorandum" required /></p>
<p><input type="text" name="lname" placeholder="Enter Title" required /></p>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit"/>
</form>
<?php
if(isset($_FILES['file'])){
$errors= array();
$file_name = $_FILES['file']['name'];
$file_size =$_FILES['file']['size'];
$file_tmp =$_FILES['file']['tmp_name'];
$file_type=$_FILES['file']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['file']['name'])));
$expensions= array("pdf");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a pdf file.";
}
if($file_size > 2097152){
$errors[]='File size must not exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"../uploads/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
<p><input name="submit" type="submit" value="Submit" /></p>
</form>
<p style="color:#FF0000;"><?php echo $status; ?></p>
</div>
</div>
</body>
</html>
That's because you set only to save file name
$file = $_REQUEST['file'];
Instead it should be
$file = "../uploads/".$_REQUEST['file'];
There are quite a few logical errors in your code.
You are inserting a record into the MySQL database before you do your check on the file extension and file size.
You just insert the file name into MySQL ($file = $_REQUEST['file'];), hence only the file name appears there. The correct code would be:
$file = "../uploads/".$_FILES['file']['name'];
A bit more down you need to adjust the file move part:
move_uploaded_file($file_tmp, $file);
In the error checking after the sql insert you use mysql_error(), not mysqli_error($con)
You do not check if the move_uploaded_file($file_tmp,"../uploads/".$file_name); call was successful and the file was moved to its final location.
Also pls consider using prepared statements to prevent sql injection attacks.
I try upload image to mysql database and display it along with the description of image using php. After i upload the image and display it , a broken image was displayed but the description of the image was displayed without any error. How can I solve this problem ? Appreciate your help
<?php
$msg = "";
//if upload button is pressed
if(isset($_POST['upload']))
{
// the path to store the uploaded image
$target = "images/".basename($_FILES['image']['name']);
// connect to database
$db = mysqli_connect("localhost","root","","product");
// Get all the submitted data from the form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$sql = "INSERT INTO product_list (image, text) VALUES ('$image','$text')";
mysqli_query($db,$sql); // stores the submitted data into the database table : product_list
// move uploaded image to the folder : image
if (move_uploaded_file($_FILES['image']['tmp_name'],$target))
{
$msg = "Image and text uploaded successfully";
}else
{
$msg = "There was a problem uploading image";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload With Description</title>
<link rel="stylesheet" type="text/css" href="formstyle.css">
</head>
<body>
<div id="content">
<?php
$db = mysqli_connect("localhost","root","","product");
$sql = "SELECT * FROM product_list";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result))
{
echo "<div id='img_div'>";
echo "<img src='".$row['image']."'>";
echo "<p>".$row['text']."</p>";
echo "</div>";
}
?>
<form method="post" action="try.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea name="text" cols="40" rows="4" placeholder="Details of product"></textarea>
</div>
<div>
<input type="submit" name="upload" value="Upload Image">
</div>
</form>
</div>
</body>
</html>
This is my result :
You are storing it in the DB without the images directory. You either need to store it with that, or always remember to call it that way in your image calls.
echo "<img src='images/".$row['image']."'>";
or make your the record you are writing the same as the filesystem location.
$image = 'images/' . $_FILES['image']['name'];
Note you are open to SQL injections and file inclusion injections with this code.
try this
<?php
$msg = "";
//if upload button is pressed
if(isset($_POST['upload']))
{
// the path to store the uploaded image
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path = $destination_path . basename( $_FILES["image"]["name"]);
// connect to database
$db = mysqli_connect("localhost","root","","product");
// Get all the submitted data from the form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$sql = "INSERT INTO product_list (image, text) VALUES ('$image','$text')";
mysqli_query($db,$sql); // stores the submitted data into the database table : product_list
//#move_uploaded_file($_FILES['image']['tmp_name'], $target_path)
// move uploaded image to the folder : image
if (move_uploaded_file($_FILES['image']['tmp_name'],$target_path))
{
$msg = "Image and text uploaded successfully";
}else
{
$msg = "There was a problem uploading image";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload With Description</title>
<link rel="stylesheet" type="text/css" href="formstyle.css">
</head>
<body>
<div id="content">
<?php
$db = mysqli_connect("localhost","root","","product");
$sql = "SELECT * FROM product_list";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result))
{
echo "<div id='img_div'>";
echo "<img src='".$row['image']."'>";
echo "<p>".$row['text']."</p>";
echo "</div>";
}
?>
<form method="post" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea name="text" cols="40" rows="4" placeholder="Details of product"></textarea>
</div>
<div>
<input type="submit" name="upload" value="Upload Image">
</div>
</form>
</div>
</body>
</html>
I have checked out other questions of same topic on this site and tried to find the solution but unsuccessful. Images are stored in database and loaded in folder successfully but are not displayed
Here is my code:
<html>
<body>
<form action="image.php" method="post" enctype="multipart/form-data">
<input type="text" name="image_description" placeholder="Enter name" required>
<input type="file" name="myfile">
<input type="submit" name="upload" value="upload">
</form>
</body>
</html>
<?php
include("db.php");
if(isset($_POST['upload'])) {
$image_description = $_POST['image_description'];
$name = $_FILES["myfile"]["name"];
$type = $_FILES["myfile"]["type"];
$size = $_FILES["myfile"]["size"];
$temp = $_FILES["myfile"]["tmp_name"];
$error = $_FILES["myfile"]["error"];
$upload=move_uploaded_file($temp, "uploaded/" . $name);
$query= "INSERT INTO image(image_description,image_name,image_type,image_size) VALUES ('$image_description','$name','$type','$size')";
if(mysqli_query($conn,$query) && $upload) {
echo "successfully uploaded";
}
else
die(mysqli_error($conn));
}
$query = mysqli_query($conn,"SELECT * FROM image");
while($row = mysqli_fetch_array($query))
{?>
<img style="width: 200px;height: 200px;" src="<?php echo 'uploaded/' .$row['image_name'] ?>">
<?php
echo $row['image_description'] . "<br>";
}?>
Images are displayed as in picture
This is database table
The URL of your page is index.php/; notice the trailing slash.
A relative URL (e.g. src="uploaded/..") will resolve to index.php/uploaded/...
That folder obviously does not exist on your disk.
Use root-relative URLs: src="/uploaded/.."
or use relative URLs but go to the right folder: src="../uploaded/.."
or fix your weird URL and make it index.php, from which even relative URLs will resolve correctly.
I'm using Linux Debian
trying to make Login & Registration System With php
on control page
index.php:
<?php
include("connect.php");
global $tf_handle;
$error = "";
if (isset($_POST['submit']))
{
$firstName = $_POST['fname'];
$lastName = $_POST['lname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$tmp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
if($image == "")
{
$error = "Please Upload Image ";
}
else
{
$insertQuery = "INSERT INTO users (firstName,lastName,email,password,image)
VALUES ('$firstName','$lastName','$email','$password','$image')";
if(mysqli_query($tf_handle,$insertQuery))
{
if(move_uploaded_file($tmp_image,"images/$image"))
{
$error = "You're successfully registered";
}
else
{
$error = "Image isn't Uploaded";
}
}
}
}
?>
<!doctype html>
<html>
<head>
<title>Registration Page</title>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<div id="error"><?php echo $error;?></div>
<div id="wrapper">
<div id="formDiv">
<form method="POST" action="index.php" enctype="multipart/form-data">
<label>First Name:</label><br/>
<input type="text" name="fname" required /><br/><br/>
<label>Last Name:</label><br/>
<input type="text" name="lname" required /><br/><br/>
<label>Email:</label><br/>
<input type="text" name="email" required /><br/><br/>
<label>Password:</label><br/>
<input type="password" name="password" required /><br/><br/>
<label>Re-enter Password:</label><br/>
<input type="password" name="passwordConfirm" required /><br/><br/>
<label>Image:</label><br/>
<input type="file" name="image" required /><br/><br/>
<input type="submit" name="submit" value="Registration" />
</form>
</div>
</div>
</body>
</html>
While running the script
The Query Works Fine and it inserts information into Database
the problem it doesn't move the image to (images) Folder
move_uploaded_file($tmp_image,"images/$image");
do i use it in wrong way ??
Result:
Warning: move_uploaded_file(images/snapshot46.png): failed to open stream: Permission denied in /var/www/html/LoginRegistrationSystem/index.php on line 51
I wonder what are you getting when you print the $error:
<div id="error"><?php echo $error;?></div>
From the php manual you get that:
If filename is not a valid upload file, then no action will occur, and
move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some
reason, no action will occur, and move_uploaded_file() will return
FALSE. Additionally, a warning will be issued.
So I would say:
1- Check the return based on your $error variable and you'll know if the file is a valid upload file.
2- Check the params you're using on move_uploaded_file are (string $filename , string $destination)
3- Check the permissions and path to your folder (if the problem lies in the permissions take a look at this post)
From the manual, the first "move_uploaded_file" example (check how $uploads_dir and $name are being used):
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
i got some forms in php so i can upload data into a mysql database, i already do the trials on a localhost server with xampp, but when i upload my files into my host ftp the forms doesnt work,so, i was thinking it has something to do with the fact that i put this file and the "connect.php" one too under password restriction, and that has something to do with the file permissions too but i already grant permission to the user of the database and permission to the file and i also had tried without the password protected thing, and nothing, always had the same result, so i start to experiment a little and i figured out that the image uploads fine into the database but nothing else did it, knowing that i try to "echo out" the other input results but non of it show something, and i came into the conclusion that my form is sending empty data, SOMEONE CAN TELLME IF IM RIGHT?, WHY THIS IS HAPPENING! PLEASE HELP ,heres my code...
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="slider_upload">
<h1>Slider principal</h1>
<div class="forma">
<form action="sliderPrincipal.php" method="post" enctype="multipart/form-data">
<p><label for="encabezado">Encabezado</label>
<input type="text" id="encabezado" name="encabezado" /></p><br>
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
<p><label for="fileupload">File to upload</label>
<input type="file" id="fileupload" name="fileupload" /></p><br>
<p><label for="articulo">Articulo</label>
<textarea id="articulo" name="articulo" rows="26" style="width: 100%;" >Escribir aqui</textarea></p><br>
<button type="submit" name="submit" value"send">Upload File</button>
</form><br><br>
</div>
</div>
<div class="message">
<?php
$file_dir = "../uploaded";
if (isset($_POST['encabezado'])){
$encabezado = mysql_real_escape_string($_POST['encabezado']);
$articulo = mysql_real_escape_string($_POST['articulo']);
}
foreach($_FILES as $file_name => $file_array){
//echo "path: ".$file_array['tmp_name']."<br />\n";
//echo "name: ".$file_array['name']."<br/>\n";
//echo "type: ".$file_array['type']."<br/>\n";
//echo "size: ".$file_array['size']."<br/><br/>\n";
//echo "encabezado ".$encabezado;
if(is_uploaded_file($file_array['tmp_name'])){
move_uploaded_file($file_array['tmp_name'], "$file_dir/".$file_array['name']) or die ("Your image couldnt be uploaded <br>");
$newpath = addslashes("uploaded/".$file_array['name']);
include "connect.php";
$addfile = "INSERT INTO slider (encabezado, image, articulo) VALUES ('$encabezado','$newpath', '$articulo')";
$result = mysql_query($addfile);
if ( $result === FALSE ) {
echo "your post could not be uploaded but we already got your image in our files ";
} else{
echo '<p style="padding: 20px;"><h1>Your post was successfully uploaded <h2></p><br><br>';
}
mysql_close();
} else "No file found";
}
?>
</div>
</div>
</body>
</html>
$file_dir = "../uploaded";
if($_REQUEST['submit']) {
$encabezado = mysql_real_escape_string($_POST['encabezado']);
$articulo = mysql_real_escape_string($_POST['articulo']);
foreach($_FILES as $file_name => $file_array){
if(is_uploaded_file($file_array['tmp_name'])){
move_uploaded_file($file_array['tmp_name'], "$file_dir/".$file_array['name']) or die ("Your image couldnt be uploaded <br>");
$newpath = addslashes("uploaded/".$file_array['name']);
include "connect.php";
$addfile = "INSERT INTO slider (`encabezado`, `image`, `articulo`) VALUES ('$encabezado','$newpath', '$articulo')";
$result = mysql_query($addfile);
if ( $result === FALSE ) {
echo "your post could not be uploaded but we already got your image in our files ";
} else{
echo '<p style="padding: 20px;"><h1>Your post was successfully uploaded <h2></p><br><br>';
}
mysql_close();
} else "No file found";
}
}
Try above code.
Note: not tested.