Aaron Tomlinson Aaron Tomlinson - 1 year ago 74
Ajax Question

How do I apply today's date to images uploaded with ajax and php.

I have been searching the site for a solution and I found a few, but I do not know how to apply it to the code I am using. I want to add the date & time to the images uploaded by the user.

This is my PHP Page that I am ajaxing the image to.

<?php
session_start();

include_once("db_connect.php");

$username = $_SESSION['username'];

if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$sourcePath = $_FILES['userImage']['tmp_name'];
$targetPath = "uploads/".$_FILES['userImage']['name'];

if(move_uploaded_file($sourcePath,$targetPath)) {
$sql = "UPDATE users4 SET profile_photo = '".$targetPath."' WHERE username = '".trim($username)."' ";
mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn)."qqq".$sql);

?>

<div style="background-position: center;;height:155px;width:240px;background-image: url(<?=$targetPath?>);background-size: 100% auto;background-repeat: no-repeat;border-radius: 8px;" ></div>

<?php
}
}
}
?>


This my AJAX FUNCTION

$.ajax({
url: "uploadajax.php",
type: "POST",
data: new FormData(this),
beforeSend: function(){
$(".spinner4").show();
$(".fa-check").hide();
$(".upload-preview").hide();
},
contentType: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
$("#targetLayer").css('opacity','1');
setInterval(function() {
$(".spinner4").hide();
$(".fa-check").delay(3000).fadeIn(200);
$(".button-bottom-container").fadeIn();
},500);
},
error: function()
{
}
});


So I have tried applying.

<?php

if (move_uploaded_file($tmp_name, $location.time().'_'.$name)) {
echo 'file uploaded! ';
}

?>


But with no success. I don't really know where to apply the "time()" function in my code to make it work. Any ideas? I'm sure this is a simple one.

I'm pretty sure the change needs to happen within

if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$sourcePath = $_FILES['userImage']['tmp_name'];
$targetPath = "uploads/".$_FILES['userImage']['name'];

if(move_uploaded_file($sourcePath,$targetPath)) {


but, nothing I try is working. Yet... Thanks if you have some help to offer.

Answer Source

You can just use strtotime()

$targetPath = "uploads/".strtotime("now")."_".$_FILES['userImage']['name'];

To convert back use date("d-m-Y H:i:s", $time);

<?
$file_path = "some/directory/1501113258_file.jpg";
$part = explode ("_", basename($file_path));
$date_time = date ("d-m-Y H:i:s", $part['0']);
// will output 26-07-2017 23:54:18
?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download