I'm trying to create a social network site and I've been watching tutorials where the users can upload their profile picture and change their avatar. However, whenever I try to upload a picture it gives me an error 'File upload failed' I'm not very sure how to fix it or what exactly to do. Where exactly do I need to dump all the pictures the users have uploaded?
photo_system.php
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
$sql = "SELECT avatar FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../user/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file($fileTmpLoc, "../user/$log_username/$db_file_name");
if ($moveResult != true) {
header("location: ../message.php?msg=ERROR: File upload failed");
exit();
}
user.php
$profile_pic = "";
$profile_pic_btn = "";
$avatar_form = "";
// Check to see if the viewer is the account owner
$isOwner = "no";
if($u == $log_username && $user_ok == true){
$isOwner = "yes";
$profile_pic_btn = 'Toggle Avatar Form';
$avatar_form = '<form id="avatar_form" enctype="multipart/form-data" method="post" action="php_parsers/photo_system.php">';
$avatar_form .= '<h4>Change your avatar</h4>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '</form>';
}
Create directory first if not exist
if($avatar != ""){
$picurl = "../user/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
if(!file_exists($picurl)){
mkdir($picurl, 0777,true);
}
}
Related
I'm a PHP beginner and i managed to muscle up a code which has a person upload up to 4 documents to a designated folder on a server. I'm now having trouble writing code which takes these 4 document names and adds them to that person's column with the rest of input data. I believe the right approach is to go with a "foreach" loop which increments variable name every time it goes through uploaded file names. I've tried doing this with $documentname[$i] = $file_name; but it's not working.
This is what I have so far:
$upload_dir = 'uploads/';
$allowed_types = array(
'doc',
'docx'
);
$maxsize = 4 * 1024 * 1024;
if (!empty(array_filter($_FILES['files']['name']))) {
// var_dump($_FILES);
// die();
$i=1;
foreach ($_FILES['files']['tmp_name'] as $key => $value) {
$file_tmpname = $_FILES['files']['tmp_name'][$key];
$file_name = $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
$filepath = $location . $file_name;
$documentname[$i] = $file_name;
if (in_array(strtolower($file_ext), $allowed_types)) {
if ($file_size > $maxsize)
echo "Greška, datoteke su veće od dozvoljene vrijednosti (4MB)";
if (file_exists($filepath)) {
$filepath = $location . time() . $file_name;
if (move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} uspješno uploadan <br />";
} else {
echo "Error uploading {$file_name} <br />";
}
} else {
if (move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} uspješno uploadan <br />";
} else {
echo "Error uploading {$file_name} <br />";
}
}
} else {
// If file extention not valid
echo "Error uploading {$file_name} ";
echo "({$file_ext} file type is not allowed)<br / >";
}
}
} else {
// If no files selected
echo "No files selected.";
}}
And this is the sql code:
if (isset($_POST['signup'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$documentname1 = $_POST['documentname1'];
$documentname2 = $_POST['documentname2'];
$documentname3 = $_POST['documentname3'];
$documentname4 = $_POST['documentname4'];
$msg = mysqli_query($con, "insert into users(fname,lname,documentname1,documentname2,documentname3,documentname4)
values('$fname','$lname','$documentname1','$documentname2','$documentname3','$documentname4')");
So the question is: is it possible to iterate through the uploaded files name array and assign each file name a variable like #documentname1,#documentname2,... to write these names in the database?
Thank you in advance!
Change your code to look like this. And also use prepared statement - PDO
if (isset($_POST['signup'])) {
$upload_dir = 'uploads/';
$allowed_types = array(
'doc',
'docx'
);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$countfiles = count($_FILES['files']['name']);
$doc_name = [];
$maxsize = 4 * 1024 * 1024;
if (!empty(array_filter($_FILES['files']['name']))) {
// var_dump($_FILES);
// die();
for ($i=0;$i<$countfiles;$i++) {
$file_tmpname = $_FILES['files']['tmp_name'][$i];
$file_name = $_FILES['files']['name'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
$filepath = $location . $file_name;
$doc_name[] += $_FILES['files']['name'][$i];
if (in_array(strtolower($file_ext), $allowed_types)) {
if ($file_size > $maxsize)
$error[] = "Greška, datoteke su veće od dozvoljene vrijednosti (4MB)";
if (file_exists($filepath)) {
$filepath = $location . time() . $file_name;
if (move_uploaded_file($file_tmpname, $filepath)) {
$success[] = "{$file_name} uspješno uploadan <br />";
} else {
$error[] = "Error uploading {$file_name} <br />";
}
}
} else {
// If file extention not valid
$error[] = "Error uploading {$file_name} ";
$error[] = "({$file_ext} file type is not allowed)<br / >";
}
}
} else {
// If no files selected
$error[] = "No files selected.";
}}
if (!isset($error)) {
$documentname1 = $doc_name[0]
$documentname2 = $doc_name[1]
$documentname3 = $doc_name[2]
$documentname4 = $doc_name[3]
$msg = mysqli_query($con, "insert into users(fname,lname,documentname1,documentname2,documentname3,documentname4)
values('$fname','$lname','$documentname1','$documentname2','$documentname3','$documentname4')");
}
}
to show errors on your html
if(isset($error)){
foreach($error as $error){
echo '<div class="alert alert-danger" role="alert">
<button class="close" data-dismiss="alert"></button>' .$error.'<br /> </div>';
}
}
to show success
if(isset($success)){
foreach($success as $success){
echo '<div class="alert alert-success" role="alert">
<button class="close" data-dismiss="alert"></button>' .$success.'<br /> </div>';
}
}
I want a logged in user to add a profile picture. if the user havent added a picture, the default image should display.
here is the code I tried. The default image is not showing and it is displaying the amount of users in the database. I know I should use prepared statements, but dont know how to with adding a file.
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'pt');
if(isset($_POST['upload_submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmp = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$filesError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.',$_FILES['file']['name']);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg','jpeg','png','pdf');
if(in_array($fileActualExt,$allowed)){
if($_FILES['file']['error'] === 0){
if($_FILES['file']['size'] < 1000000){
$fileNameNew =
"profile".$_SESSION['username'].".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($_FILES['file']
['tmp_name'],$fileDestination);
$sql = "UPDATE users SET status = 0 WHERE
username='$_SESSION[username]';";
$result = mysqli_query($db, $sql);
header("Location: pic.php");
}else{
echo "Your file is too big!";
}
}else{
echo "You have an error uploading your file!";
}
}else{
echo "You cannot upload files of this type!";
}
}
?>
<?php
$sql = "SELECT * from users";
$result = mysqli_query($db, $sql);
if(mysqli_num_rows($result)> 0){
while ($row = mysqli_fetch_assoc($result)){
$sqlimg = "SELECT * FROM users WHERE
username='$_SESSION[username]'";
$resultimg=mysqli_query($db,$sqlimg);
while($rowimg = mysqli_fetch_assoc($resultimg)){
echo "<div class=container>";
if($rowimg['status'] == 0){
echo "<img src=
'uploads/profile".$_SESSION['username'].".jpg'>";
}else{
echo "<img src='uploads/male.jpg'>";
}
echo "<p>".$_SESSION['username']."</p>";
echo "</div>";
}
}
}else{
echo "There are no users yet!";
}
if(isset($_SESSION['username'])){
echo "<form action='pic.php'
method='POST'enctype='mutlipart/form-
data'>
<input type='file' name='file'>
<button type='submit' name='upload_submit'>Upload</button>
</form>";
}else {
echo "You are not logged in!";
}
?>
This is my code
$actual_name = pathinfo($filename,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$filetype=$_FILES['file']['type'];
$target="../wp-content/themes/childtheme/img/";
if($filetype=='image/jpeg' or $filetype=='image/png' or
$filetype=='image/gif')
{
$i = 1;
while(file_exists($target.$actual_name.".".$extension)){
$actual_name = $original_name.$i;
$filename = $actual_name.".".$extension;
$i++;
}
$target = $target.basename( $filename ) ;
move_uploaded_file($_FILES['file']['tmp_name'],$target);
$insert="INSERT INTO EnterSchool(SliderImg ) VALUES('".$target."' )";
if (mysqli_query($db, $insert)) {
echo "saved ";
}
else {
echo "Error: " . $insert . "" . mysqli_error($db);
}
$db->close();
}}
html
<input type="file" name="file" id="file" >
I am used to writing AJAX using the following structure, where I would end up sending variables to PHP
function requestToggle(type, user, elem) {
_(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "request_system.php");
ajax.onreadystatechange = function () {
if (ajaxReturn(ajax) == true) {
if (ajax.responseText == "request_sent") {
_(elem).innerHTML = 'OK Request Sent';
} else if (ajax.responseText == "unrequest_ok") {
_(elem).innerHTML = '<button onclick="requestToggle(\'request\',\'<?php echo $u; ?>\',\'requestBtn\')">Request Number</button>';
} else {
alert(ajax.responseText);
_(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type=" + type + "&user=" + user);
}
The example that I want to work on is for a photo upload form and the PHP script is using the $_FILES array but I am unsure how I would go about passing this array to the PHP using AJAX.
Here is the PHP
<?php
$result = "";
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
$result = "That image has no dimensions";
echo $result;
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 1048576) {
$result = "Your image file was larger than 1mb";
echo $result;
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
$result = "Please only JPG, GIF or PNG images";
echo $result;
exit();
} else if ($fileErrorMsg == 1) {
$result = "An unknown error occurred";
echo $result;
exit();
}
$sql = "SELECT profilePicture FROM User WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
//delete old pic if set
if($avatar != ""){
$picurl = "users/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
//move file from temp folder to users folder
$moveResult = move_uploaded_file($fileTmpLoc, "users/$log_username/$db_file_name");
if ($moveResult != true) {
$result = "File upload failed";
echo $result;
exit();
}
include_once("image_resize.php");
//replace original file with resized version
$target_file = "users/$log_username/$db_file_name";
$resized_file = "users/$log_username/$db_file_name";
$wmax = 400;
$hmax = 600;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE User SET profilePicture='$db_file_name' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
//header("location: user.php?u=$log_username");
$result = "upload_success";
echo $result;
exit();
}
?>
UPLOAD FORM
$avatar_form = '<div class="bhoechie-tab-content" id="uploadphoto">';
$avatar_form .= '<center>';
$avatar_form .= '<form id="avatar_form"" method="post" enctype="multipart/form-data">';
$avatar_form .= '<h1>Change avatar</h1>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '<p id="status"></p>';
$avatar_form .= '</form>';
$avatar_form .= '</center></div>';
You can easily enough pass an array eg ajax.send("type=" + type + "&user=" + user + "&files=" + files);
Having not seen the rest of your code I can't provide a full answer, but I'm assuming you're somehow creating a files array in js and want to pass that to the php? If so, the variable 'files' would then be using in PHP like:
$files= $_REQUEST['files'];
This is my code, and the image is uploaded where i want it to, but its named 0."file extension" everytime, but i want the image to have the same name as the id of the object im submitting with this form.
id: 3
img name: 3."file extension"
My php:
<?php
if (isset($_POST['submit_newProduct'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data and avoid sql injection
$product_name = trim(mysqli_real_escape_string($connection, $_POST['product_name']));
$product_price = trim(mysqli_real_escape_string($connection, $_POST['product_price']));
$product_desc = trim(mysqli_real_escape_string($connection, $_POST['product_desc']));
$product_category = trim(mysqli_real_escape_string($connection, $_POST['product_category']));
$product_attribute = trim(mysqli_real_escape_string($connection, $_POST['product_attribute']));
$query = "INSERT INTO products
(product_name, product_price, product_desc,
product_category, product_attribute)
VALUES ('{$product_name}', '{$product_price}',
'{$product_desc}', '{$product_category}',
'{$product_attribute}')";
$filename = $_FILES["product_img"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["product_img"]["size"];
$allowed_file_types = array('.png','.jpg','.jpeg','.gif');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000)) {
// Rename file
$pid = mysqli_insert_id($connection);
$newfilename = $pid . $file_ext;
if (file_exists("img/product_img/" . $newfilename))
{
// file already exists error
echo "You have already uploaded this file.";
}
else
{
move_uploaded_file($_FILES["product_img"]["tmp_name"], "img/product_img/" . $newfilename);
echo "File uploaded successfully.";
}
}
elseif (empty($file_basename))
{
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 200000)
{
// file size error
echo "The file you are trying to upload is too large.";
}
else
{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
header("location:product_list.php"); //maskes sure item is not recreated on refresh
$result = mysqli_query($connection, $query);
if ($result) {
$message = "Produkt oprettet.";
} else {
$message = "Der skete en fejl";
$message .= "<br />" . mysqli_error($connection);
}
}
?>
My html form:
<form action="" method="post" enctype="multipart/form-data">
<div class="col-md-6">
<h4>Produkt navn</h4>
<input type="text" name="product_name" class="form-control"> <br>
<h4>Produkt pris</h4>
<input type="text" placeholder="DKK" name="product_price" class="form-control" style="width:30%;"><br>
<h4>Produkt beskrivelse</h4>
<textarea type="text" name="product_desc" rows="3" class="form-control"></textarea> <br>
<h4>Produkt kategori</h4>
<select name="product_category" class="form-control">
<option></option>
<option>Gummi ænder</option>
<option>Påklædning</option>
<option>Accessories</option>
</select> <br>
<h4>Produkt attribut</h4>
<input type="text" name="product_attribute" class="form-control" value=""> <br>
<input type="file" name="product_img"><br>
<input type="submit" name="submit_newProduct" class="btn btn-warning pull-right" value="Tilføj produkt">
</div>
</form>
Since, Query is executing after mysqli_insert_id(); Thats why it is returning 0.
Place your query before mysqli_insert_id(), then only you will get inserted id.
I placed / edited your code in my way. You can change it accordingly.
<?php
if (isset($_POST['submit_newProduct'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data and avoid sql injection
$product_name = trim(mysqli_real_escape_string($connection, $_POST['product_name']));
$product_price = trim(mysqli_real_escape_string($connection, $_POST['product_price']));
$product_desc = trim(mysqli_real_escape_string($connection, $_POST['product_desc']));
$product_category = trim(mysqli_real_escape_string($connection, $_POST['product_category']));
$product_attribute = trim(mysqli_real_escape_string($connection, $_POST['product_attribute']));
$query = "INSERT INTO products (product_name, product_price, product_desc, product_category, product_attribute)
VALUES ('{$product_name}', '{$product_price}', '{$product_desc}', '{$product_category}', '{$product_attribute}')";
$result = mysqli_query($connection, $query);
if ($result) {
$filename = $_FILES["product_img"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["product_img"]["size"];
$allowed_file_types = array('.png','.jpg','.jpeg','.gif');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000)) {
// Rename file
$pid = mysqli_insert_id($connection);
$newfilename = $pid . $file_ext;
if (file_exists("img/product_img/" . $newfilename)){
// file already exists error
echo "You have already uploaded this file.";
} else {
move_uploaded_file($_FILES["product_img"]["tmp_name"], "img/product_img/" . $newfilename);
echo "File uploaded successfully.";
}
}
elseif (empty($file_basename)){
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 200000){
// file size error
echo "The file you are trying to upload is too large.";
}
else{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
$message = "Produkt oprettet.";
}
else {
$message = "Der skete en fejl";
$message .= "<br />" . mysqli_error($connection);
}
header("location:product_list.php"); //maskes sure item is not recreated on refresh
}
?>