I want to save my pictures in different folders and it belongs to my mysql db entries.
Code:
<?php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name']; // 1
#session_start();
$_SESSION['recipe_id'] = 5;
if (isset($_SESSION['recipe_id']))
{
$location = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'.$_SESSION['recipe_id'] .'/';
if(!is_dir($location))
{
mkdir($location);
}
$targetPath = $location;
include 'db_connect.php';
$sql = "SELECT recipes_id FROM IMAGE WHERE recipes_id="+$_SESSION['recipe_id'];
$result = mysql_query($sql,$db) or exit("QUERY FAILED!");
$anzahl = mysql_num_fields($result);
$anzahl++;
$targetFile = str_replace('//','/',$targetPath) . $anzahl.$_FILES['Filedata']['tmp_name'];
move_uploaded_file($tempFile,$targetFile);
}
else
{
echo "Server Error";
}
}
?>
The folder will be created but no picture is in the correct folder.
Uploadify settings:
'script' : '/uploadify/uploadify.php',
'uploader' : '/uploadify/uploadify.swf',
'cancelImg' : '/uploadify/cancel.png',
'folder' : '/img/recipes',
'auto' : true
Please help
I think it is not taking file name at last. Try this it might work for you:
<?php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name']; // 1
#session_start();
$_SESSION['recipe_id'] = 5;
if (isset($_SESSION['recipe_id'])) {
$path = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'.$_SESSION['recipe_id'] .'/';
if(!is_dir($path)) {
mkdir($path);
}
$targetPath = $path;
include 'db_connect.php';
$sql = "SELECT recipes_id FROM IMAGE WHERE recipes_id="+$_SESSION['recipe_id'];
$result = mysql_query($sql,$db) or exit("QUERY FAILED!");
$anzahl = mysql_num_fields($result);
$anzahl++;
$file_temp = $_FILES['Filedata']['tmp_name'];
$file_name = $anzahl.prep_filename($_FILES['Filedata']['name']);
$file_ext = get_extension($_FILES['Filedata']['name']);
$real_name = $file_name;
$newf_name = set_filename($path, $file_name, $file_ext);
$file_size = round($_FILES['Filedata']['size']/1024, 2);
$file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES['Filedata']['type']);
$file_type = strtolower($file_type);
$targetFile = str_replace('//','/',$targetPath) . $newf_name;
move_uploaded_file($tempFile,$targetFile);
}
else {
echo "Server Error";
}
}
?>
Related
I am trying to upload 3 separate images to upload on the server using. the code doesn't throw any error but only 1st image gets uploaded. The other two images are not uploaded on the server but Its name gets inserted into the database.
here is my code to upload the images:
<?php
include("common_code.php");
include("database_connection.php");
$property_id = $_POST['id'];
if (!$_FILES['file1']['size'] == 0) {
$temp = explode(".", $_FILES["file1"]["name"]);
$extension = end($temp);
$fileName1= mt_rand(). "_". time(). "." .$extension;
$image_tmp_name = $_FILES['file1']['tmp_name'];
$folder = "images/property_images/";
$folder = $folder . $fileName1;
move_uploaded_file($image_tmp_name, $folder);
$uploadQuery = "INSERT INTO property_photos (filenames,property_id) VALUES ('$folder','$property_id')";
$run = mysqli_query($connection, $uploadQuery);
}
if (!$_FILES['file2']['size'] == 0) {
$temp2 = explode(".", $_FILES["file2"]["name"]);
$extension2 = end($temp2);
$fileName2= mt_rand(). "_". time(). "." .$extension2;
$image_tmp_name = $_FILES['file2']['tmp_name'];
$folder2 = "images/property_images/";
$folder2 = $folder2 . $fileName2;
move_uploaded_file($image_tmp_name2, $folder2);
$uploadQuery2 = "INSERT INTO property_photos (filenames,property_id) VALUES ('$folder2','$property_id')";
$run2 = mysqli_query($connection, $uploadQuery2);
}
if (!$_FILES['file3']['size'] == 0) {
$temp3 = explode(".", $_FILES["file3"]["name"]);
$extension3 = end($temp3);
$fileName3= mt_rand(). "_". time(). "." .$extension3;
$image_tmp_name = $_FILES['file3']['tmp_name'];
$folder3 = "images/property_images/";
$folder3 = $folder3 . $fileName3;
move_uploaded_file($image_tmp_name3, $folder3);
$uploadQuery3 = "INSERT INTO property_photos (filenames,property_id) VALUES ('$folder3','$property_id')";
$run3 = mysqli_query($connection, $uploadQuery3);
}
header("Location:property_reg_successful.php?id=$property_id");
Only file1 gets uploaded into a server!
file2 and file3 not uploaded.
You've just got a simple variable-naming error:
$image_tmp_name = $_FILES['file2']['tmp_name'];
[...]
move_uploaded_file($image_tmp_name2, $folder2);
Note the different variable names "$image_tmp_name" and "$image_tmp_name2".
I have searched far and wide and cannot find an answer to my question in terms that I can understand. I am trying to make my code upload all text input fields and if not image is in the file input, then upload all except the image and upload all including the image when an image is present. Below is my working code for when an image is present. All help will be greatly appreciated.
<?php
session_start();
error_reporting(E_ALL);
include_once 'dbconnect.php';
$userID = $_SESSION['usr_id'];
if(!empty($_FILES["uploadedimage"]["tmp_name"])) {
$eTitle = mysqli_real_escape_string($con, $_POST['etitle']);
$eDate=mysqli_real_escape_string($con, $_POST['edate']);
$eDesc=mysqli_real_escape_string($con, $_POST['edesc']);
$file_tmp = $_FILES['uploadedimage']['tmp_name'];
$file_ext = strtolower(end(explode('.',$_FILES['uploadedimage']['name'])));
$date = date("d-m-Y");
$imagename = $date."-".time().".".$file_ext;
$target_path = "event_images/".$imagename;
$move = move_uploaded_file($file_tmp, $target_path);
if($move) {
if($_FILES['uploadedimage']===false){
$not = "NULL";
}ELSE{
$not = $imagename;
}
$sql =mysqli_query($con, "INSERT INTO `events` (eventID,eventImage,eventTitle,eventDate,eventDescription) values (NULL,'".$not."','".$eTitle."','".$eDate."','".$eDesc."')");
$db = mysqli_query($sql, $con);
$msg = "Song has been uploaded successfully";
header("Location: websiteeditor.events.php");
}
else {
$msg = "Not uploaded because of error #".$_FILES["file"]["error"];
}
}
else {
$msg = "Failed to Upload<br/>Not uploaded because of error #".$_FILES["file"]["error"];
}
?>
<?=$msg;?>
Following code should work the way you need it.
<?php
session_start();
error_reporting(E_ALL);
include_once 'dbconnect.php';
$userID = $_SESSION['usr_id'];
$eTitle = mysqli_real_escape_string($con, $_POST['etitle']);
$eDate = mysqli_real_escape_string($con, $_POST['edate']);
$eDesc = mysqli_real_escape_string($con, $_POST['edesc']);
$date = date("d-m-Y"); // where is this used?
$not = null;
if (!empty($_FILES["uploadedimage"]["tmp_name"])) {
$file_tmp = $_FILES['uploadedimage']['tmp_name'];
$file_ext = strtolower(end(explode('.', $_FILES['uploadedimage']['name'])));
$imagename = $date . "-" . time() . "." . $file_ext;
$target_path = "event_images/" . $imagename;
$move = move_uploaded_file($file_tmp, $target_path);
if ($move) {
$not = $imagename;
} else {
$msg = "Not uploaded because of error #" . $_FILES["file"]["error"];
}
}
$sql = mysqli_query($con, "INSERT INTO `events` (eventID,eventImage,eventTitle,eventDate,eventDescription) values (NULL,'" . $not . "','" . $eTitle . "','" . $eDate . "','" . $eDesc . "')");
$db = mysqli_query($sql, $con);
$msg = "Song has been uploaded successfully";
header("Location: websiteeditor.events.php");
?>
<?php
session_start();
require "database.php";
$db = new database();
$operation = $_REQUEST['action'];
$file = uniqid() . " - " . $_FILES['document']['name'];
$result = move_uploaded_file(
$_FILES['document']['tmp_name'],
"uploads/" . $file );
switch ($operation)
{
case 'Add':
$name = $_REQUEST['name'];
$image = "uploads/" . $file;
$result = $db->insert($name,$image);
break;
case 'update':
$id = $_SESSION['user_id'];
$name = $_REQUEST['name'];
$image = "uploads/" . $file;
$result = $db->update($id,$name,$image);
break;
case 'delete':
$result = $db->delete($_REQUEST['id']);
break;
default:
echo "invalid request";
break;
}
header("Location:display.php");
?>
Use is_uploaded_file() function to check whether a file is uploaded with the form or not. So accordingly, change your code in the following way,
...
$operation = $_REQUEST['action'];
$file = null;
if(is_uploaded_file($_FILES['document']['tmp_name'])){
$file = uniqid() . " - " . $_FILES['document']['name'];
$result = move_uploaded_file($_FILES['document']['tmp_name'], "uploads/" . $file );
}
switch($operation){
case 'Add':
$name = $_REQUEST['name'];
$image = ($file == null) ? null : "uploads/" . $file;
$result = $db->insert($name,$image);
break;
case 'update':
$id = $_SESSION['user_id'];
$name = $_REQUEST['name'];
$image = ($file == null) ? null : "uploads/" . $file;
$result = $db->update($id,$name,$image);
break;
case 'delete':
...
}
...
And your update method would be like this,
public function update($id, $name, $image) {
$query = "UPDATE customers SET name='$name'";
if($image != null){
$query .= ", image ='$image'";
}
$query .= " WHERE id=$id";
return mysqli_query($this->connect,$query);
}
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.
If I upload a same named image, my code works fine to rename it in my location but when it's fetched from database, the duplicate image is broken. My code for renaming and storing the image is:
insert_image.php
$image = $_FILES['image'];
$name = $_FILES['image']['name'];
$temp_name = $_FILES['image']['tmp_name'];
$newname = $name;
//print_r($_FILES);
$location = realpath(dirname(__FILE__)).'/images/'.basename($name);
$image_path = realpath(dirname(__FILE__)).'/images/';
$extention = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
if(file_exists($location)){
$increment = 0;
list($name, $extention) = explode('.', $location);
while(file_exists($location)) {
$increment++;
$location = $name. $increment . '.' . $extention;
//print_r($location);
$newname = $name. $increment . '.' . $extention;
}
}
mysqli_query($dbc, "INSERT INTO post(username, post, image) VALUES('$uname', '$post', '$newname')");
if(isset($newname)){
if(move_uploaded_file($_FILES['image']['tmp_name'], $location) && is_writable($location)){
//echo 'File uploaded successfully';
}
else{
//echo "Failed to move...";
}
}
any kind of better suggestions will be really helpful.
In location variable (inside while loop) your are storing only file name. You also want full path. change your code as below
$image = $_FILES['image'];
$name = $_FILES['image']['name'];
$temp_name = $_FILES['image']['tmp_name'];
$newname = $name;
//print_r($_FILES);
$location = realpath(dirname(__FILE__)).'/images/'.basename($name);
$image_path = realpath(dirname(__FILE__)).'/images/';
$extention = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
if(file_exists($location)){
$increment = 0;
list($name, $extention) = explode('.', $name);
while(file_exists($location)) {
$increment++;
$location = realpath(dirname(__FILE__)).'/images/'.$name. $increment . '.' . $extention;
$newname = $name. $increment . '.' . $extention;
}
}
mysqli_query($dbc, "INSERT INTO post(username, post, image) VALUES('$uname', '$post', '$newname')");
if(isset($newname)){
if(move_uploaded_file($_FILES['image']['tmp_name'], $location) && is_writable($location)){
//echo 'File uploaded successfully';
}
else{
//echo "Failed to move...";
}
}
Please am trying to upload docs, .docx, .pdf, .jpg files using php but each time I click on the upload button, I get this message: "uploadedFile format not supported! uploaded".
Please where is the problem coming from? It is supposed to be either 'uploaded' or 'file format not supported'.
Thanks.
<?php
require_once "include/db_handle.php";
if (isset($_POST['upload'])) {
if (!empty($_FILES['_file']['name'])) {
if ($_FILES['_file']['type'] == 'application/msword') {
$upload_folder = "./file_doc/";
$pic_name = time() . ".doc";
$pic_path = $upload_folder . $pic_name;
move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path);
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
if ($_FILES['_file']['type'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
$upload_folder = "./file_doc/";
$pic_name = time() . ".doc";
$pic_path = $upload_folder . $pic_name;
move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path);
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
if ($_FILES['_file']['type'] == 'application/pdf') {
$upload_folder = "./file_doc/";
$pic_name = time() . ".pdf";
$pic_path = $upload_folder . $pic_name;
move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path);
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
if ($_FILES['_file']['type'] == 'application/vnd.openxmlformats-officedocument.presentationml.presentation') {
$upload_folder = "./file_doc/";
$pic_name = time() . ".pptx";
$pic_path = $upload_folder . $pic_name;
move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path);
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
if ($_FILES['_file']['type'] == 'image/jpeg') {
$upload_folder = "./profile_pix/";
$pic_name = time() . ".jpg";
$pic_path = $upload_folder . $pic_name;
require_once "include/resize.php";
if (move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path)) {
$image = new Resize($pic_path);
$image->resizeImage(180, 180, 'crop');
$image->saveImage($pic_path);
//thumbnail
$image = new Resize($pic_path);
$image->resizeImage(50, 50, 'crop');
$image->saveImage($upload_folder . "thumb/" . $pic_name);
}
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
else{
echo "File format not supported!";
}
}
}
?>
HTML Form
<p class="points" > Add Files</p>
<form name="" action="" method="post" enctype="multipart/form-data">
<input type="file" name= "_file" />
<input type= "submit" name="upload" value="upload"/>
</form>