PHP uploading images using filepath in MySql - php

I am trying to create a script that enter details from a book. The image variable 'image' and 'content' is supposed to be a jpg or PDF. These are selected in the HTML create form of type 'file'.
I've been looking online at other peoples code as I am really struggling to get my head around it.
Heres what I have so far:
require_once __DIR__.'/config.php';
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);
if (isset($_POST['submit'])) {
$title = $_POST["title"];
$authors = $_POST["authors"];
$description = $_POST["description"];
$price = $_POST["price"];
$image = $_POST["image"];
$content = $_POST["content"];
$uploadDir = 'path/to/where/i/can/save/';
if(isset($_POST['submit']))
$fileName = $_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$stmt = $dbh->prepare("INSERT INTO books (title, authors, description, price, image, content ) ".
"VALUES ('$title', '$authors', '$description', '$price', '$filepath', '$content')");
$stmt->execute();
}
Not surprisingly this does not do anything, the database remains empty and the page i'm presented with has nothing on it. Can anyone help me sort this out and also tell me how I could make it so that the content is also saved as a filepath.
Sidenote:
In the database i used VARCHAR to store the variables.

Related

Changing php image upload filename to a specific name

I want to change the uploaded image filename to a certain name for example:
Original name:city.jpg -> D0000_04042018094730121.jpg (D0000 is kodeDosen and the other is a microtime timestamp.)Here is my php code:uploadDosen.php
<?php
include 'connectdb.php';
if (isset($_POST['upload_Btn'])) {
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
$kodeDosen = $_POST['kodeDosen'];
$namaJurnal = $_POST['namaJurnal'];
$tipePublikasi = $_POST['tipePublikasi'];
$status= $_POST['status'];
$gambar = $_FILES['gambar']['name'];
$sql = "INSERT INTO tbl_publikasi (kodeDosen,gambar,namaJurnal,tipePublikasi,status) VALUES ('$kodeDosen','$gambar','$namaJurnal',
'$tipePublikasi','$status')";
// execute query
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['gambar']['tmp_name'],$target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
header("location:uploadTest.php");
}
?>
Instead of using
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
Put your desired name in
$ext = end((explode(".", $_FILES['gambar']['name'])));
$target = "uploaddosen/MYNEWNAME." . $ext
$ext is taking the uploaded file name and getting the file extension. Then adding it together with your new name.
Just change the value of $target to your preferred filename.
You can try:
$extention = explode(".", $_FILES['gambar']['name']);
$extention = end($extention);
$target = $kodeDosen."_".str_replace(array(".", " "), "", microtime() ).".".$extention;

PHP - Sending sql command as a string thru two php files

EDIT: This is a original code, that is working ok. sorry for formating.
<?php
$target = "images/";
if(!is_dir($target)) mkdir($target); $target = $target . basename( $_FILES['photo']['name']);
$uvod = $_POST['uvod']; $text = $_POST['text']; $nadpis = $_POST['nadpis']; $datum = date("Y-m-d");
if (isset($_POST['zobrazeno'])) {
$zobrazeno = 1; } else {
$zobrazeno = 0; }
$fname=($_FILES['photo']['name']); $funiquename = uniqid() . $fname; $tmpName = $_FILES['photo']['tmp_name']; $fileSize = $_FILES['photo']['size']; $fileType = $_FILES['photo']['type'];
$fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp);
if(!get_magic_quotes_gpc()){ $fname = addslashes($fname);}
require_once 'db_config.php'; $db_server=mysql_connect($db_hostname,$db_username,$db_password);
if(!$db_server) die("Unable to connect to MySQL" .mysql_error());
mysql_select_db($db_database,$db_server) or die("Unable to connect to database" .mysql_error());
$sql = "INSERT INTO `aktuality` (`nadpis`, `uvod`, `text`, `datum`, `zobrazeno`, `obr_nazev`, `obr_pripona`, `obr_velikost`, `obr_data`) VALUES ('$nadpis', '$uvod', '$text', '$datum', '$zobrazeno', '$funiquename','$fileType','$fileSize','$content')";
mysql_query($sql);
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
} else {
echo "Sorry, there was a problem uploading your file.";
}
?>
Im a php beginner.
I have a problem with sending sql command as a string thru two php files.
This php file should call function sql_string() in sql.php, but there is nothing happens.
<?php
------some code here-------
include 'sql.php';
mysql_query(sql_string1());
------some code here------
?>
sql.php
<?php
function sql_string1()
{
$sql ="INSERT INTO `aktuality` (`nadpis`, `uvod`, `text`, `datum`, `zobrazeno`, `obr_nazev`, `obr_pripona`, `obr_velikost`, `obr_data`) VALUES ('$nadpis', '$uvod', '$text', '$datum', '$zobrazeno', '$funiquename','$fileType','$fileSize','$content')";
return $sql;
}
?>
Thanks for your help!
Try doing this for the query to work:
<?php
------some code here-------
include 'sql.php';
$sql = sql_string1() ;
mysql_query($sql) or die(mysql_error());
------some code here------
?>
You should also be able to see what the error is if that query failed.

PHP and mysql: previously working code: Saving Data and images to database or filepath

I'm trying to save some data and a couple of images from a form to my database.
I previously had a part of the code that worked (the part that saved the data and images to the database) now for some reason it is not working, - I was messing around with the code and pressed undo one too many times.
require_once __DIR__.'/config.php';
session_start();
/*** connect to db ***/
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);
if(isset($_POST['submit'])) {
$title = $_POST["title"];
$authors = $_POST["authors"];
$description = $_POST["description"];
$price = $_POST["price"];
$image = $_FILES['image']['tmp_name'];
$content = $_FILES['content']['tmp_name'];
$target_dir = "/path/to/dir/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$target_file2 = $target_dir . basename($_FILES["content"]["name"]);
//move file
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file) && move_uploaded_file($_FILES["content"]["tmp_name"], $target_file2) ) {
echo "The files have been uploaded.";
} else {
echo "error";
}
$file_path=$target_dir. basename( $_FILES["image"]["name"]);
$file_path2=$target_dir. basename( $_FILES["content"]["name"]);
echo $file_path;
$stmt = $dbh->prepare("insert into books values('".$_POST["title"]."','".$_POST["authors"]."','".$_POST["description"]."', '".$_POST["price"]."','".$file_path."', '".$file_path2."')");
$stmt->execute();
}
Can anyone see where I have gone wrong here? How can I get the images to upload and the images saving back in the database?
There are no error messages I am just presented with a page that says 'error'as I've echoed in the code

How to use GD enhancer to resize an image in uploading process

I want to do is to resize the the image that i will be moving to upload folder using GD enhancer in my image upload script.
My problem is after i try the GD enhancer in my php code i couldn't make it work.
my current php code:
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
use gdenhancer\GDEnhancer;
include_once 'GDEnhancer.php';
$emailCodeResult = isset($_POST['emailCodeResult']) ? $_POST['emailCodeResult'] : "";
$imageLink = isset($_POST['imageLink']) ? $_POST['imageLink'] : "";
const path = "files/upload/";
$s= explode(path,$imageLink);
unlink("../upload/".$s[1]);
$email = isset($_POST['email']) ? $_POST['email'] : "";
$type = $_FILES["imageInput"]["type"];
$ext = end(explode('/', $type));
$filename = uniqid() . '_' .$emailCodeResult . '.' . $ext;
$image = new GDEnhancer($filename);
$image->backgroundResize(300, 300, 'shrink');
$save = $image->save();
header('content-type:' . $save['mime']);
move_uploaded_file($_FILES["imageInput"]["tmp_name"], "../upload/" . $save);
$location = "files/upload/" . $filename;
if(!empty($_POST['email'])) {
$q = "UPDATE tbl_user SET user_image = '$location' WHERE user_email= :email ";
$query = $db->prepare($q);
$query->bindParam(':email', $email);
$results = $query->execute();
echo "1";
}
?>
First, check this link (example #1 Save image to folder)
Second, you don't have to check image type, GDEnhancer will do this for you.
Third, header('content-type:' . $save['mime']) is not necessary if you save file to disk.

Change name of uploaded file

I have been trying to change the name of a file after an upload with my script.
I want every file to be named as "testing". Later I am going to change "testing" to a
variable that gets a unique name. Now I just want to change the name to "testing".
Also the script always says error although the file are uploaded.
Can I get some help here please?
Here is my code:
<?php
$uploadDir = 'images/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO $db_table ( Image ) VALUES ('$filePath')";
mysql_query($query) or die('Error, query failed');
}
?>
I think you need
$fileName = "testing"; //maybe add extension
instead of getting original filename from $_FILES. Although after the file is moved you may end up with a situation of overwriting existing files as they all has the same name. To prevent that (for testing purposes) you may add something to $fileName, maybe a short random string.

Categories