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
Related
Here is how the site looks like to give you an idea.
I would like to show the image he entered instantly after he clicked Bestand kiezen (= translates to chose file). How it works now is that it only shows the filename, how can I show a preview of the image instantly? The image and the other info is only inserted in the DB after clicking the add post button.
Is this supposed to be done with ajax?
The addpost.php code
<?php
include_once('classes/Post.class.php');
include_once('classes/User.class.php');
User::checklogin();
$post = Post::ShowPosts();
if(! empty($_POST)) {
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed)){
if ($fileError === 0){
if ($fileSize < 10000000){
$fileNameNew = uniqid('', true).".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
print_r($fileDestination);
move_uploaded_file($fileTmpName, $fileDestination);
$feedback = "Post has been saved.";
$title = $_POST['title'];
$desc = $_POST['description'];
$filter = $_POST['filter'];
$date = date("Y-m-d H:i:s");
$location = "";
$userid = $_SESSION['userid'];
$newPost = new Post();
$newPost->setTitle($title);
$newPost->setPicture($fileDestination);
$newPost->setDescription($desc);
$newPost->setDate($date);
$newPost->setUserId($userid);
$newPost->setLocation($location);
$newPost->setFilter($filter);
$newPost->AddPost();
$postId = Post::getLastId();
$string = $_POST['tag'];
$tags = explode(',' , $string);
foreach($tags as $t) {
$newPost->setTag($t);
$newPost->AddTags($postId);
}
} else{
$feedback = "Your file is too big.";
}
} else{
$feedback = "There was an error uploading your file.";
}
} else{
$feedback = "You cannot upload files of this type.";
}
}
?><!DOCTYPE html>
<html lang="en">
<body>
<form action="" method="post" enctype="multipart/form-data">
<h1 form__title>Add post</h1>
<?php if(isset($feedback)): ?>
<div class="feedback">
<p><?php echo $feedback; ?></p>
</div>
<?php endif; ?>
<div class="form__field">
<label for="title" class="label">YOUR SHOT TITLE:</label> <br/>
<input class="form__input" type="text" name="title">
</div>
<div class="form__field">
<label for="file" class="label">UPLOAD PICTURE</label><br/>
<input class="form__input" type="file" name="file" class="fileToUpload">
</div>
<div class="form__field">
<label for="description" class="label">DESCRIPTION</label><br/>
<textarea name="description" cols="25" rows="5"></textarea>
</div>
<div class="form__field">
<label for="tag" class="label">ADD SOME TAGS TO YOUR SHOT (seperated with , )</label><br/>
<input class="form__input" type="text" name="tag">
</div>
<p>JPG, GIF or PNG. Snapshots are 400 × 300 pixels or 800 × 600 (for HiDPI displays). </p><br/><br/>
<div class="form__field">
<label for="tag" class="label">ADD ONE (Instagram) FILTER TO YOUR SHOT </label><br/>
<select name="filter">
<option value="_1977">1977</option>
<option value="aden">aden</option>
<option value="xpro2">xpro2</option>
</select>
</div>
<div class="form__field">
<input class="btn_style" type="submit" name="submit" value="Add post"">
</div>
</form>
</body>
</html>
The Addpost function
public function AddPost(){
$conn = db::getInstance();
$query = "insert into posts (post_title, picture, description, filter, location, user_id, post_date) values (:post_title, :picture, :description, :filter, :location, :user_id, :post_date)";
$statement = $conn->prepare($query);
$statement->bindValue(':post_title',$this->getTitle());
$statement->bindValue(':picture',$this->getPicture());
$statement->bindValue(':description',$this->getDescription());
$statement->bindValue(':filter', $this->getFilter());
$statement->bindValue(':location',$this->getLocation());
$statement->bindValue(':user_id',$this->getUserId());
$statement->bindValue(':post_date',$this->getDate());
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
HTML - Display image after selecting filename
answers the question nicely with a javascript snippet look down at the first answer
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 am planning to have a web gallery. However, it is hard for me to use PHP to insert DB. The following code:
HTML -- I want to make a form which has category and multiple images that can be inserted into DB at the same time.
<form action="upload" method="POST" enctype="multipart/form-data">
<p> Upload : <input type="file" id="file" name="images" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<p> <input type="submit" name="submit" value="Upload!" /> </p>
</form>
DATABASE
I am using imageName as VARCHAR not BLOB TYPE.
PHP
<?php
include ("dbConnect.php");
if(isset($_POST["submit"])) {
$image = $_POST['images']['tmp_name'];
$imageName = $_POST['images']['name'];
$imageSize = $_POST['images']['size'];
$imageType = $_POST['images']['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
?>
The problem is, the category is the only one has inserted into the database successfully. But not with the imageName, imageType, and imageSize. And also i want the image to be stored into database so that I can retrieve the image from DB on the other web page. Any ideas?
You can use 'multiple' property in the 'input' tag like this :
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" multiple='multiple' /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
User can select multiple files and upload them.
And at the server you will do this :
if (isset($_FILES["userfile"]) && !empty($_FILES["userfile"])) {
$image = $_FILES['userfile']['tmp_name'];
$imageName = $_FILES['userfile']['name'];
$imageSize = $_FILES['userfile']['size'];
$imageType = $_FILES['userfile']['type'];
$imageCategory = $_POST['imageCategory'];
$len = count($image);
$path = "images/";
for ($i = 0; $i < $len; $i++) {
if (isset($imageName[$i]) && $imageName[$i] !== NULL) {
if(move_uploaded_file($image[$i], $path.$imageName[$i])) {
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType) VALUES ('$imageName[$i]', '$imageCategory', '$imageSize[$i]' , '$imageType[$i]' )");
}
}
}
}
$mysqli->close();
header("location: index");
First off the file information won't be in the $_POST global variable it will be in the $_FILES
From http://php.net/manual/en/features.file-upload.multiple.php (modified):
Form
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" /> </p>
<p> <input name="userfile[]" type="file" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
Parse the global file variable to an array (we'll assume this is a helper function called parseFiles.php):
<?php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
Move the files and insert the file information into the database :
<?php
include ("dbConnect.php");
include ("parseFiles.php");
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['userfile']);
foreach ($file_ary as $file) {
$image = $file['tmp_name'];
$imageName = $file['name'];
$imageSize = $file['size'];
$imageType = $file['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
}
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
Hopefully that should do the job. I've not tested this I've just blind coded it so there may be some bugs
I try to upload pictures from a form in PHP.
I've got a strange problem regarding my images upload:
My form:
<form id="booking-step" method="post" action="add.php" class="booking" autocomplete="off" enctype="multipart/form-data">
<input type="file" id="AddPhotos1" name="AddPhotos[]" />
<input type="file" id="AddPhotos2" name="AddPhotos[]" />
<input type="file" id="AddPhotos3" name="AddPhotos[]" />
<input type="file" id="AddPhotos4" name="AddPhotos[]" />
<input type="file" id="AddPhotos5" name="AddPhotos[]" />
</form>
My PHP:
if($_FILES['AddPhotos']){
$errorAddPhotos = "";
$validAddPhotos = "";
for($x=0;$x<sizeof($_FILES["AddPhotos"]["name"]);$x++){
$fichier = basename($_FILES['AddPhotos']['name'][$x]);
$taille_maxi = 3000;
$taille = filesize($_FILES['AddPhotos']['tmp_name'][$x]);
$extensions = array('.png', '.jpg', '.jpeg');
$extension = strrchr($_FILES['AddPhotos']['name'][$x], '.');
if(!in_array($extension, $extensions))
{
$errorAddPhotos .= "Wrong extension.<br />";
}
if($taille>$taille_maxi)
{
$errorAddPhotos .= "Wrong size.<br />";
}
if((in_array($extension, $extensions)) && ($taille<$taille_maxi))
{
$fichier = strtr($fichier,
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$fichier = preg_replace('/([^.a-z0-9]+)/i', '-', $fichier);
if(move_uploaded_file($_FILES['AddPhotos']['tmp_name'][$x], $destin . $fichier))
{
$validAddPhotos = 'Success!';
}
else
{
$errorAddPhotos = 'Wrong';
}
}
}
}
echo $validAddPhotos;
echo $errorAddPhotos
My code looks good, but I cant upload my files...
Error: my files stay in condition "if(!in_array($extension, $extensions))".
Could you please help ?
Thanks.
I think you should use this logic is more perform than yours with testing image type and file size. Also, you can custom it with what you want like you did name of the file :)
multiple upload image function php?
i have this page for upload:
<?php
require ('incs/db.php');
require_once ('incs/funcs.php');
?>
<?php
if (array_key_exists('upload', $_POST)) {
$directory = str_replace(basename($_SERVER['PHP_SELF']),'',$_SERVER['PHP_SELF']);
$uploadHandler = $_SERVER['DOCUMENT_ROOT']. $directory . 'images/';
// $uploadHandler = "echtitipi".$_SERVER['HTTP_HOST']. '/images/';
$max_file_size = 30000;
define('UPLOAD_DIR', $uploadHandler);
$ext= end(explode(".", $_FILES['image']['name']));
$name = rand(1111111,9999999).'.'.$ext;
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadHandler. $name))
{
$upload = true;
$title = $_POST ['title'];
$sql = "INSERT INTO photo (id, keyword, photoName)
VALUES ('','$title','$name')
";
$result = mysql_query ( $sql, $con );
}
else
{
$upload = false;
$msg = 'Cant Upload!';
}
}
?>
<?php
include ('incs/header.php');
?>
<?php
getUrlQuery();
?>
<script language="javascript">
<!--
function pick(symbol, path) {
if (window.opener && !window.opener.closed)
window.opener.document.form.img.value = symbol;
window.opener.document.form.imgbox.src = path;
window.close();
}
// -->
</script>
<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">
<p>
<label for="image">
Tanım:
</label>
<input type="text" name="title" id="title" />
<label for="image">
Upload image:
</label>
<input type="file" name="image" id="image" />
</p>
<p>
<input type="submit" name="upload" id="upload" value="Upload" />
</p>
</form>
<?php
if($upload == true)
{
echo "<a hrf(because spam!)=\"javascript:pick('$name','images/$name')\"><im(g) src=\"images/$name\" border=\"0\" alt=\"use\"></a>";
}
?>
<?php
include ('incs/footer.php');
?>
`
this upload image to curretnt root's images folder. My current folder is admin:
root/admin/images
root/images
when i use
$uploadHandler = "http://".$_SERVER['HTTP_HOST']. '/images/';
script doesnot work.
<?php
if($upload == true)
{
echo "<a hrf=\"javascriptick('$name','{$uploadHandler}$name')\"><im(g) src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\"></a>";
}
?>
the image couldnot add to editor. I guess There is a problem with javascript.
what is wrong in script
echo "<a hrf=\"javascriptick('$name','{$uploadHandler}$name')\"><im(g) src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\"></a>";
change into
echo "<img src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\">";
I guess this will help...
Im sorry for bad dictation because i cant write the right script because sending errors(link and images)
above code uploaded code to
/www/admin/images
and save information to database and add image to tinymce editor. But I want to upload code to:
www/images
when I use :
$uploadHandler = $_SERVER['DOCUMENT_ROOT'].'/images/';
and
"<img src=\"images/$name\" border=\"0\" alt=\"use\">"
the image couldnot add to editor. This is my problem.