uploading multiple photos to specific location - php

I've been trying to create something that will upload multiple photos to a specific location and change it's name, tried to loop through files but something is not working and I quite can't figure out what that is! So please take a look and tell me what is wrong so I can learn and not make the same mistake again ! Thanks
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['product_submit']))
{
if(!empty($_POST['product_name']) && !empty($_POST['product_author']) && !empty($_POST['product_price']) && empty($_POST['product_search']))
{
if(is_numeric($_POST['product_price']))
{
$auth_key = round(microtime(true));
if(isset($_FILES['photos']) && !empty($_FILES['photos']))
{
$image_path = "product_images";
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$_SESSION['sucess'] = "Invalid extension.";
header("location: index.php");
exit();
}
else
{
$size = filesize($_FILES['photos']['tmp_name'][$name]);
if($size > 5120000)
{
$_SESSION['sucess'] = "You have exceeded the size limit.";
header("location: index.php");
exit();
}
$temp = explode('.', $filename);
$newfilename = mt_rand() . '_product.' . end($temp);
$name_path = "product_images/".$newfilename;
$suc = move_uploaded_file($_FILES['photos']['tmp_name'][$name], $name_path);
if($suc)
{
$stmt = $connection->prepare("INSERT INTO images (auth_id, photo_location) VALUES (:code, :location)");
$stmt->bindParam(':code', $auth_key, PDO::PARAM_STR);
$stmt->bindParam(':location', $name_path, PDO::PARAM_STR);
$stmt->execute();
}
else
{
$_SESSION['sucess'] = "Something went wrong!";
header("location: index.php");
exit();
}
}
}
}
$query = "INSERT INTO products (name, author, price, date, code) VALUES (:name, :author, :price, NOW(), :code)";
$stmt = $connection->prepare($query);
$stmt->bindParam(':name', $_POST['product_name'], PDO::PARAM_STR);
$stmt->bindParam(':author', $_POST['product_author'], PDO::PARAM_STR);
$stmt->bindParam(':price', $_POST['product_price'], PDO::PARAM_STR);
$stmt->bindParam(':code', $auth_key, PDO::PARAM_STR);
$stmt->execute();
if($stmt)
{
$_SESSION['sucess'] = "Data inserted to database.";
header("location: index.php");
exit();
}
else
{
$_SESSION['error'] = "Error while submiting data to database.";
header("location: index.php");
exit();
}
}
}
elseif (empty($_POST['product_name']) && empty($_POST['product_author']) && empty($_POST['product_price']) && !empty($_POST['product_search']))
{
$_SESSION['error'] = "You can't leave anything empty!";
header("location: index.php");
exit();
}
}
}

if your input file's name is photo[] you should use:
for($i = 0; $i < count($_FILES['photo']); $i++)
and then:
$_FILES['photo'][$i]['tmp_name']
and so on

Related

Displaying images from Database not working

I have tried a number of methods but my code still doesn't show images from the database on my website. When I click upload, I get an output of only the file name and file details but no photos are shown.
Here is my code that has to display the images.
<main>
<section align='center'>
<h1 id="rcorner2"align='center'style="font-size:30px; position:fixed;">Photo Library</h1>
<br><br>
<div class="wrapper">
<!--h2 align='left'>Photos</h2-->
<div class="photo-container">
<?php
include_once 'dbh.php';
$sql = "SELECT * FROM photos ORDER BY orderPhotos DESC";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "Error updating photo library!";
}else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
echo '<a href="#">
<div style="background-image: url(../libraries/photos/'.$row["imageFullName"].');"></div>
<h3>'.$row["filetitle"].'</h3>
<p>'.$row["filedescription"].'</p>
</a>';
}
}
?>
</div>
</div>
</section>
</main>
Connection to database
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "portal uploads";
$conn = mysqli_connect($servername, $username, $password, $dbname);
?>
And here is the database connection from the html form.
<?php
if(isset($_POST['upload'])) {
$newFileName = $_POST['filename'];
if(empty($newFileName)){
$newFileName = "photo";
}else{
//Replacing spaces in filename with underscores
$newFileName = strtolower(str_replace(" ", "-", $newFileName));
}
$filetitle = $_POST['filetitle'];
$filedescription = $_POST['filedescription'];
$file = $_FILES['file'];
$fileName = $file["name"];
$fileType = $file["type"];
$fileTempName = $file["tmp_name"];
$fileError = $file["error"];
$fileSize = $file["size"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png");
//Error handling for allowed file types
if(in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if($fileSize < 10000000) {
//Make file unique through naming
$imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
$fileDestination = "../libraries/photos/" . $imageFullName;
include_once "dbh.php";
//Checking for error handling when fields have been left empty
if(empty($filetitle) || empty($filedescription)) {
header("location:photos_edit.php?upload=empty");
exit();
} else {
$sql = "SELECT * FROM photos;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
}else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setPhotoOrder = $rowCount + 1;
$sql = "INSERT INTO photos (filetitle, filedescription, imageFullName, orderPhotos) VALUES (?, ?, ?, ?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
}else{
mysqli_stmt_bind_param($stmt, "ssss", $filetitle, $filedescription, $imageFullName, $setPhotoOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
header("location: photos_edit.php?upload=success");
}
}
}
}else{
echo "Photo is too big!";
exit();
}
}else{
echo "An error ocurred while uploading your image!";
exit();
}
}else{
echo "File type not supported";
exit();
}
}
?>
For example, if you use this code, you can load an image from DB (MySQL) :)
<?php
$connection =mysql_connect("localhost", "root" , "");
$sqlimage = "SELECT * FROM userdetail where `id` = '".$id1."'";
$imageresult1 = mysql_query($sqlimage,$connection);
while($rows = mysql_fetch_assoc($imageresult1))
{
echo'<img height="300" width="300" src="data:image;base64,'.$rows['image'].'">';
}
?>

Why is the following picture weird when trying to upload a picture profile

I have managed to get the picture uploaded into the upload's folder but for some reason, I am getting the following 404 error. From my understanding, it is not recognising the file type and I thought that my code is correct?
I think by doing a profile image, I need two files, one in my header or login page and the other one process the page...
This is the code in one of my files:
<?php
include_once __DIR__.'/header2.php';
include_once __DIR__.'/includes/dbh.php';
$id = $_SESSION['u_id'];
$status = 0;
if (isset($_POST['submit'])) {
$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', 'pdf');
if (!in_array($fileActualExt, $allowed)) {
echo "<meta http-equiv='refresh' content='0;url=header2.php?upload_form=error'>";
exit();
} else {
if ($fileError === 1) {
echo "<meta http-equiv='refresh' content='0;url=header2.php?upload_form=error'>";
exit();
} else {
if ($fileSize > 500000) {
echo "<meta http-equiv='refresh' content='0;url=header2.php?upload_form=filesizeerror'>";
exit();
} else {
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg
SET status = ?
WHERE userid = ?
;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt, "ii", $status, $id);
mysqli_stmt_execute($stmt);
echo "<meta http-equiv='refresh' content='0;url=header2.php?upload_form=success'>";
exit();
}
}
}
}
}
And this is the code in my other file:
$sql = "SELECT * FROM users WHERE user_uid = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL error';
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $_SESSION['u_uid']);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['user_id'];
$one = 1;
$sqlImg = "SELECT * FROM profileimg WHERE userid = ? limit 1;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sqlImg)) {
echo 'SQL error';
exit();
} else {
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$resultImg = mysqli_stmt_get_result($stmt);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
if ($rowImg['status'] == 0) {
$filename = "uploads/".$id."*";
$fileinfo = glob($filename);
$fileext = explode(".", $fileinfo[0]);
$fileactualext = $fileext[1];
echo "<img class='profile_picture' src='uploads/profile".$id.".".$fileactualext."?".mt_rand()."'>";
} else {
echo "<img class='default_picture' src='uploads/profiledefault.jpg'>";
}
echo '<div class="welcome">Welcome back '.$row['user_uid'].'!</div>';
}
}
}
}

PHP Login nouser

Im making a login system for my website, in newer to php coding and when i press my login button it sends me with the "login.php?error=nouser" in the url when my email is in my database, im not sure if i messed up with some code or something needs to be moved around or not. I am new to php and dont have a eye good enough to spot some of these problems.
<?php
if (isset($_POST['login-submit'])) {
require 'dbh.inc.php';
$emailuid = $_POST['emailuid'];
$password = $_POST['pwduid'];
if (empty($emailuid) || empty($password)) {
header("Location: ../login.php?error=emptyfields&emailuid=".$emailuid);
exit();
} else {
$sql = "SELECT * FROM users WHERE emailUsers=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../login.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $emailuid, $emailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if ($pwdCheck == flase) {
header("Location: ../login.php?error=wrongpassword");
exit();
} elseif ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userfnId'] = $row['fnidUsers'];
$_SESSION['userlnId'] = $row['lnidUsers'];
header("Location: ../login.php?login=success");
exit();
} else {
header("Location: ../login.php?error=wrongpassword");
exit();
}
} else {
header("Location: ../login.php?error=nouser");
exit();
}
}
}
} else {
header("Location: ../login.php");
exit();
}
Any type of help is appreciated, im learning how this all works. thanks for the understanding.
You've only specified one placeholder in your query:
$sql = "SELECT * FROM users WHERE emailUsers=?";
But you've tried to bind two parameters:
mysqli_stmt_bind_param($stmt, "ss", $emailuid, $emailuid);
You probably just want this:
mysqli_stmt_bind_param($stmt, "s", $emailuid);
Also, spelling:
if ($pwdCheck == flase) {
Also, this makes no sense:
if ($pwdCheck == false) {
...
} elseif ($pwdCheck == true) {
...
} else {
...
}
Just do this:
if ($pwdCheck == false) {
...
} else {
...
}
Or better:
if (password_verify($password, $row['pwdUsers']) === true) {
...
} else {
....
}

How to put the code of upload_image to insertion function with PDO?

I have here the script for insertion of records in database.i have have here two script one is for insertion of records only and the other is also an insertion function the difference is that the second script is inserting image.now what i want to happen here is that to store the first script and the second script in just one table and should be look like this user_id,username,password,province,FILE_NAME,FILE_SIZE,FILE_TYPE.but i don't know how to do that..can someone please help me with it?
here is the script for the insertion of records
public function create($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO login(username,password,province) VALUES(:username, :password, :province)");
$stmt->bindparam(":username",$username);
$stmt->bindparam(":password",$password);
$stmt->bindparam(":province",$province);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
and here is for upload_image
if(isset($_FILES['files'])){
$query = "INSERT into tish_images(`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`)
VALUES(:FILE_NAME,:FILE_SIZE,:FILE_TYPE)";
$stmt = $DB_con->prepare($query);
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $error ){
if ($error != UPLOAD_ERR_OK) {
$errors[] = $_FILES['files']['name'][$key] . ' was not uploaded.';
continue;
}
$file_name = $key.$_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[] = 'File size must be less than 2 MB';
continue;
}
try{
$stmt->bindParam( ':FILE_NAME', $file_name , PDO::PARAM_STR );
$stmt->bindParam( ':FILE_SIZE', $file_size, PDO::PARAM_STR );
$stmt->bindParam( ':FILE_TYPE', $file_type, PDO::PARAM_STR );
$stmt->execute();
$desired_dir="image_uploads";
if(is_dir($desired_dir)==false){
mkdir($desired_dir, 0700);// Create directory if it does not exist
}
if(is_file($desired_dir.'/'.$file_name)==false){
move_uploaded_file($file_tmp,$desired_dir.'/'.$file_name);
}else{ //rename the file if another one exist
$new_file=$desired_dir.'/'.$file_name.time();
move_uploaded_file($file_tmp,$new_file) ;
}
}catch(PDOException $e){
$errors[] = $file_name . 'not saved in db.';
echo $e->getMessage();
}
}
if(empty($error)){
echo "Success";
}
}
here is the index.php
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$province = $_POST['province'];
if($crud->create($username,$password,$province))
{
echo "<script type='text/javascript'>alert('Saved!');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Insertion Failed!');</script>";
}
}
?>
Personally I would not put it together into one large script, but put each in a seperate function and call them from the same function. It would be a more Object Oriented way to do.
Like this:
public function createUser($username, $password, $provence)
{
createDatabaseUser($username, $password, $provence);
uploadImages();
}
public function createDatabaseUser($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO login(username,password,province) VALUES(:username, :password, :province)");
$stmt->bindparam(":username",$username);
$stmt->bindparam(":password",$password);
$stmt->bindparam(":province",$province);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function uploadImages()
{
if(isset($_FILES['files'])){
$query = "INSERT into tish_images(`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`)
VALUES(:FILE_NAME,:FILE_SIZE,:FILE_TYPE)";
$stmt = $DB_con->prepare($query);
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $error ){
if ($error != UPLOAD_ERR_OK) {
$errors[] = $_FILES['files']['name'][$key] . ' was not uploaded.';
continue;
}
$file_name = $key.$_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[] = 'File size must be less than 2 MB';
continue;
}
try{
$stmt->bindParam( ':FILE_NAME', $file_name , PDO::PARAM_STR );
$stmt->bindParam( ':FILE_SIZE', $file_size, PDO::PARAM_STR );
$stmt->bindParam( ':FILE_TYPE', $file_type, PDO::PARAM_STR );
$stmt->execute();
$desired_dir="image_uploads";
if(is_dir($desired_dir)==false){
mkdir($desired_dir, 0700);// Create directory if it does not exist
}
if(is_file($desired_dir.'/'.$file_name)==false){
move_uploaded_file($file_tmp,$desired_dir.'/'.$file_name);
}else{ //rename the file if another one exist
$new_file=$desired_dir.'/'.$file_name.time();
move_uploaded_file($file_tmp,$new_file) ;
}
}catch(PDOException $e){
$errors[] = $file_name . 'not saved in db.';
echo $e->getMessage();
}
}
if(empty($error)){
echo "Success";
}
}
}

Uploading image and form to database

So, i've been wondering for this script and still can't get it right. For some reason it won't save to my database. Any ideas why it's not working? Would appreciate any help. Thanks! Here's my script.
<?php
include_once ("database.php"); ?>
<?php
if (isset($_POST['anisave'])) {
$id = $_POST['id'];
$title = $_POST['title'];
$genre = $_POST['genre'];
$description = $_POST['description'];
$start = $_POST['start'];
$stop = $_POST['stop'];
$image_file = $_FILES['image']['name'];
$type = $_FILES['image']['type'];
$size = $_FILES['image']['size'];
if (empty($image_file) || empty($id)) {
echo "Sorry, form is not complete yet!";
header('Location: add.php');
}
else{
$query_id = mysql_query("SELECT * FROM anidata WHERE id = '$id'");
$check = mysql_num_rows($query_id);
if ($check > 0) {
echo "Sorry, Anime ID not available";
header('Location: add.php');
}
else{
if ($type != "image/gif" && $type != "image/jpg" && $type != "image/jpeg" && $type != "image/png") {
echo "Invalid image file, please use JPEG,JPG,PNG or GIF to upload the image."
header('Location: add.php');
}
if ($size > 10000) {
echo "Affordable file is under 10mB."
header('Location: add.php');
}
else{
$upload_directory = 'upload/';
$temp = $upload_directory.$image_file;
if (move_uploaded_file($_FILES['image']['tmp_name'] , $temp)) {
$sql = "INSERT INTO anidata VALUES ('$id', '$title', '$temp', '$genre', '$description','$start', '$stop')";
$query = mysql_query($sql)
if ($query) {
header('Location: view.php');
}
else{
echo mysql_query();
}
}
else{
echo "<p> Upload Failed, error code = " . $_FILES['location']['error']. "</p>";
}
}
}
}
}
else{
unset($_POST['anisave']);
}
?>

Categories