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");
}
}
?>
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.
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 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.
This code was run on my localhost. The images are uploaded to my mysql server using the localhost wampserver. Everything seems to be good. But when I migrate the code to the hosting site, I can't see the image uploaded in the mysql server. All I can see is my path "images-storage/" as the value of "photo" column, "images-storage" is empty and no image is stored.
This is the code:
My Form:
<form action="add.php" method="POST" enctype="multipart/form-data">
Firstname: <input type="text" name="firstname"><br />
Lastname: <input type="text" name="lastname"><br /><br />
<input type="file" name="image">
<input type="submit" value="Submit">
</form>
My form action:
<?php
include_once('config.php');
$fn = $_POST['firstname'];
$ln = $_POST['lastname'];
$name = $_FILES["image"]["name"];
$type = $_FILES["image"]["type"];
$size = $_FILES["image"]["size"];
$temp = $_FILES["image"]["tmp_name"];
$error = $_FILES["image"]["error"];
if($error > 0) {
echo "Error";
} else {
$add_image = move_uploaded_file($temp,"uploaded/".$name);
$path = 'uploaded/'.$name;
$query = $mysqli->query("INSERT INTO info(fn,ln,name,photo) VALUES('$fn','$ln','$name','$path')");
}
header('Location: index.php');
?>
Just add "name" column in the database. Haha
Im creating a CMS for my site and in my admin page I have an add page that adds new content to my site LOCATED HERE and have added a few form fields.
2 of these are:
IMAGE URL (text box) & UPLOAD IMAGE (select file button)
When I fill in all the fileds and select an image using IMAGE URL and hit add article, it works fine and my form is saved to my database and is then displayed on my site.
When I fill in all the fileds and select an image using UPLOAD IMAGE and hit add article, it adds the image to my selected folder in my cpanel but DOES NOT ADD TO DATABASE.
My question is: How can I get it to add to the database? and save the new images location to the image field on the database?
I have followed this tutorial when adding the upload file button to my page.
Please do not show me links on how to do this as I already have read through them but I stuggle when it comes to adding this to my code.
my add.php code is this.
<?php
session_start();
include_once('../include/connection.php');
if (isset($_SESSION['logged_in'])){
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
if (!empty($_POST['image']))
{
$image = $_POST['image'];
}
else
{
$image = $_POST['imageupload'];
if (isset($_FILES['imageupload']))
{
$errors = array();
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILES['imageupload'] ['name'];
$file_ext = strtolower (end (explode ('.', $file_name)));
$file_size = $_FILES['imageupload'] ['size'];
$file_tmp = $_FILES['imageupload'] ['tmp_name'];
if (in_array ($file_ext, $allowed_ext) === false) {
$errors[] = 'File extension not allowed';
}
if ($file_size > 2097152) {
$errors[] = 'File size must be under 2mb';
}
if (empty($errors)) {
if (move_uploaded_file($file_tmp, 'images/'.$file_name)) {
echo 'File uploaded';
$image = $file_name;
}
}else{
foreach ($errors as $error)
echo $error, '<br />';
}
}
}
$link = $_POST['link'];
$category = $_POST['category'];
$brand = $_POST['brand'];
if (empty($title) or empty($content)) {
$error = 'All Fields Are Required!';
}else{
$query = $pdo->prepare('INSERT INTO mobi (promo_title, promo_content, promo_image, promo_link, promo_cat, promo_name) VALUES(?, ?, ?, ?, ?, ?)');
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->bindValue(3, $image);
$query->bindValue(4, $link);
$query->bindValue(5, $category);
$query->bindValue(6, $brand);
$query->execute();
header('location: index.php');
}
}
?>
<?php
if (isset($_FILES['Filedata']))
{
// And if it was ok
if ($_FILES['Filedata']['error'] !== UPLOAD_ERR_OK)
exit('Upload failed. Error code: ' . $_FILES['image']['error']);
$filename = $_FILES['Filedata']['name'];
$targetpath = "../img/news/" . $filename; //target directory relative to script location
$copy = copy($_FILES['Filedata']['tmp_name'], $targetpath);
}
?>
<html>
<head>
<title>Add Article</title>
<link rel="stylesheet" href="../other.css" />
</head>
<body>
<div class="container">
<b>← Back</b>
<br />
<div align="center">
<h4>Add Article</h4>
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?></small><br /><br />
<?php } ?>
<form action="add.php" method="post" autocomplete="off" enctype="multipart/form-data">
<input type="text" name="title" placeholder="Title" /><br /><br />
<textarea rows="15" cols="50" placeholder="Content" name="content"></textarea><br /><br />
<input name="imageupload" type="file" id="image" placeholder="Imageupload" />
<input type="text" name="image" placeholder="Image" /><br /><br />
<input type="link" name="link" placeholder="Link" /><br /><br />
<input type="category" name="category" placeholder="Category" /><br /><br />
<input type="category" name="brand" placeholder="Brand" /><br /><br />
<input type="submit" value="Add Article" />
</form>
</div>
</div>
</body>
</html>
<?php
}else{
header('location: index.php');
}
?>
Please help.
if (move_uploaded_file($file_tmp, 'images/'.$file_name)) {
echo 'File uploaded';
$image = '/images/'.$filename;//try updating the line like this