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.
Related
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.
Hello guys, please help!
I'm having problems with my project, I followed these steps on how to upload(https://www.youtube.com/watch?v=Ipa9xAs_nTg) but something is wrong.
The error is Notice:
Undefined index: tmp_name in C:\xampp\htdocs\LDEVERACATERING\upload_process.php on line 16
Here is my upload.html
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.2.1.min"></script>
<script src="jquery-migrate-1.4.1.min"></script>
<title>
Image Upload
</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="content">
<form method="POST" action="upload_process.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="Say something about this image..."></textarea>
</div>
<div>
<input type="submit" name="upload" value="Upload Image"/>
</div>
</form>
</div>
</body>
</html>
here is my upload_process.php
<?php
$msg = "";
//if upload button is pressed
if (isset($_POST['upload'])) {
//path to store the upload image
$target = "photos/".basename($_FILES['image']['name']);
//connect to database
$db = mysqli_connect("localhost", "root", "", "catering_info");
}
//get all the submitted date from the form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$sql = "INSERT INTO photos_upload(image, text) VALUES('$image', '$text')";
mysqli_query($db, $sql); //stores the submitted date into the database table: images
//now let's move the upload image into the folder: photos
if (move_uploaded_file($_FILES['tmp_name']['name'], $target)) {
$msg = "Image uploaded successfully";
}
else
{
$msg = "There was a problem uploading image";
}
?>
PLEASE HELP ME, I REALLY NEED IT. Also I'm still new to this, I just started web prog last 3 weeks :( Thank you very much!
Please try this
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
Try this by replacing your code
move_uploaded_file($_FILES['tmp_name']['name'], $target)
With these
move_uploaded_file($_FILES['image']['tmp_name'], $target)
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 am working on a project where you have to upload all files on a server in JPEG format but this following code in upload.php is not working, like it is not checking the condition whether there is a name to album or not.
Following file is upload.php with database connect to it with 4 fields in table... id, name, album_id, url.
<html>
<head>
<title>PHP file upload</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<?php include 'connect.php'; ?>
<div id="body">
<?php include 'title_bar.php'; ?>
<div id="container">
<h3>Upload</h3>
<form enctype="multipart/form-data" method="POST">
<?php
if (isset($_POST['upload'])) {
$name = $_POST['name'];
$album_id = $_POST['album'];
$file = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
if(empty($name) || empty($file)){
echo "Please Fill ALL THE FUIELD ";
}else{
echo "working";
}
}
?>
Name : <br />
<input type="text" name="name" />
<br /> <br />
Select Folder : <br />
<select>
<?php
$query = mysql_query("SELECT id , name FROM albums");
while($run = mysql_fetch_array($query)){
$album_id = $run['id'];
$album_name = $run['name'];
echo "<option value='$album_id'> $album_name </option>";
}
?>
</select>
<br /><br />
Select File : <br />
<input type="file" name="file" />
<br /> <br />
<input type="submit" name="Upload" value="Upload" />
</form>
</div>
</div>
</body>
</html>
file type and size haven't defined and upload config array did not initialize
The keys in $_POST are case-sensitive, you're checking for Upload but your input name is upload.
You should either change your input to :
<input type="submit" name="upload" value="Upload" />
Or your first PHP check to :
if (isset($_POST['Upload'])) {
Also, you should set a name attribute for your select or it won't be sent.
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");
}
}
?>