Uploading image and form to database - php

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']);
}
?>

Related

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>';
}
}
}
}

How to fix Upload image using php and mysqli

I tried replacing mysql to mysqli, but I encountered an error in this code, it worked on mysql before. What is wrong?
Php:
<?php include "../../../_includes/config.php"; ?>
<?php
session_start();
if(!empty($_FILES['userAvatar']['name'])){
$uploadedFile = "";
if(!empty($_FILES["userAvatar"]["type"])){
$filename = $_FILES['userAvatar']['name'];
$valid_extensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["userAvatar"]["name"]);
$file_extension = end($temporary);
if((($_FILES["userAvatar"]["type"] == "image/png") || ($_FILES["userAvatar"]["type"] == "image/jpg") || ($_FILES["userAvatar"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)){
$sourcePath = $_FILES['userAvatar']['tmp_name'];
$targetPath = "../../../uploads/image/".$filename;
if(move_uploaded_file($sourcePath, $targetPath)){
$uploadedFile = $filename;
}
}
}
$display_name = $_POST['display_name'];
$biography = $_POST['biography'];
$sql = mysqli_query($connect, "UPDATE tb_users SET userDisplayName = '$display_name', userBiography = '$biography', userAvatar = '$uploadedFile' WHERE userLogin = '".$_SESSION['is_logged_in']['userLogin']."'") or die(mysqli_error());
if($sql){
echo "ok";
}else{
echo "err";
}
}else{
echo "err";
}
?>
Result always "err".
try this code:-
$sql = mysqli_query($connect, "UPDATE tb_users SET userDisplayName = '$display_name', userBiography = '$biography', userAvatar = '$uploadedFile' WHERE userLogin = '".$_SESSION['is_logged_in']['userLogin']."'") or die(mysqli_error($connect));
// no need of this
if($sql){
echo "ok";
}else{
echo "err";
}
Try this code below
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$dbname = 'your db';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
session_start();
if(!empty($_FILES['userAvatar']['name'])){
$uploadedFile = "";
if(!empty($_FILES["userAvatar"]["type"])){
$filename = $_FILES['userAvatar']['name'];
$valid_extensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["userAvatar"]["name"]);
$file_extension = end($temporary);
if((($_FILES["userAvatar"]["type"] == "image/png") || ($_FILES["userAvatar"]["type"] == "image/jpg") || ($_FILES["userAvatar"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)){
$sourcePath = $_FILES['userAvatar']['tmp_name'];
$targetPath = "../../../uploads/image/".$filename;
if(move_uploaded_file($sourcePath, $targetPath)){
$uploadedFile = $filename;
}
}
}
$display_name = $_POST['display_name'];
$biography = $_POST['biography'];
$sql ="UPDATE tb_users SET userDisplayName = '$display_name', userBiography = '$biography', userAvatar = '$uploadedFile' WHERE userLogin = '".$_SESSION['is_logged_in']['userLogin']."'";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
}else{
//echo "err";
}
?>

Image Removed while updating other record in php mysqli

While updating the record if I do not upload the image and click on update button the current image will be removed.
Here is the code
<?php
if (isset($_POST['update_record'])){
$edit_id = $_GET['edit'];
$username = $_POST['name'];
$email = $_POST['email'];
$city = $_POST['city'];
$file_name = $_FILES['file']['name'];
$file_tmp_name = $_FILES['file']['tmp_name'];
$file_error = $_FILES['file']['error'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$allowed = ['png' , 'jpg' , 'jpeg'];
$pathinfo = pathinfo($file_name , PATHINFO_EXTENSION);
$destination = "uploads/" . $file_name ;
if (in_array($pathinfo , $allowed)){
if ($file_size < 100000){
if ($file_error === 0){
move_uploaded_file($file_tmp_name, $destination) ;
} //error close here
else{
echo "Some kind of error";
}
} //size close here
else{
echo "File Size is too big!";
}
} //type close here
else{
echo "File type is wronng";
}
$update_query = "UPDATE crud
SET `name`='$username' , `email`='$email' ,
`city`='$city', `image`='$destination'
WHERE id=$edit_id";
$run = mysqli_query($connect, $update_query) ;
if ($run){
header("Location: show_record.php") ;
} else{
echo "Error in Updating the data";
}
} //main if isset close here
?>
verify that a file exists before proceeding. if no file exist, then DO NOT update the $destination in your update query
//use a flag
$fileExists = false;
if(!empty($_FILES['file'])) { //check here
$fileExists = true;
//rest of the file upload code
}
if($fileExists === true){
// a file was uploaded. now update $destination variable in update query as well
}

My 'move_uploaded_file()' does not move my image to my specified folder

<?php
include("config.php");
//Get the name of the input type submit
if(ISSET($_POST['sign_up'])) {
$username = trim($_POST['user']);
$password = trim($_POST['pass']);
$gender=$_POST['gen'];
$firstname =($_POST['first']);
$lastname = trim($_POST['last']);
$y=$_POST['y'];
$m=$_POST['m'];
$d=$_POST['d'];
$dob=$y."-".$m."-".$d;
$imgpath=$_FILES['file']['name'];
$imgFile = $_FILES['file']['name'];
$tmp_dir = $_FILES['file']['tmp_name'];
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$userpic = rand(1000,1000000).".".$imgExt;
if(!empty($username) && !empty($password)) {
$sql = mysql_query("SELECT * FROM users WHERE user_name = '$username'") or die(mysql_error());
if(mysql_num_rows($sql) > 0) {
$msg_error = "Username already registered!";
} else {
if(in_array($imgExt, $valid_extensions)){
mysql_query("INSERT INTO users
values('','$username','".MD5($password)."', '$gender',
'$dob', '$imgpath', 'guest',
'$firstname', '$lastname')")
or die(mysql_error());
$uuid=mysql_query("SELECT * FROM users");
while ($puid=mysql_fetch_array($uuid)){
$pid = $puid['user_id'];
mkdir("userImages/$pid");
move_uploaded_file($_FILES["file"]["tmp_name"], "userImages/$pid/" . $_FILES["file"]["name"]);
}
//image uploaded should be moved to my specified
//folder after the code above is executed
$_SESSION['sname']=$_POST['user'];
$msg_success = "You are now registered!";
}
else{
$msg_error = "Invalid image!";
}
}
}else{
$msg_error = "All fields are required!";
}
}
?>
this is my php code. Can someone help me in figuring out why my 'move_uploaded_file()' is not working?
Check your destination folder permissions. error_get_last could give you some clue to why it doesn't work. Check this example
$targetFile = "userImages/$pid/" . $_FILES["file"]["name"];
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
echo "<P>FILE UPLOADED TO: $target_file</P>";
} else {
echo "<P>MOVE UPLOADED FILE FAILED!</P>";
print_r(error_get_last());
}

uploading multiple photos to specific location

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

Categories