When this code below runs, it just returns the echo "Did not move files!";
Goal is to allow users to upload files, just get this working for now.
account.php
<form action="includes/upload.inc.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
upload.inc.php
<?php
if(isset($_POST['submit'])) {
$uploadsDir = '../uploads/';
$name = basename($_FILES["fileToUpload"]["name"]);
$tempName = basename($_FILES["fileToUpload"]['tmp_name']);
$error = $_FILES['fileToUpload']['error'];
if ($error > 0) {
echo "Error: " . $error . "<br />";
} else {
move_uploaded_file($temp_name, "$uploadsDir/$name");
if(move_uploaded_file($temp_name, "$uploadsDir/$name")) {
echo "Successful";
echo "Upload: " . $name . "<br />";
echo "Stored in: Uploads Directory!";
} else {
echo "Did not move files!";
}
}
}
?>
Hosting server off localhost, originally thought my directories did not have permissions to rwx, i ended up changing every directory that is used to have full permissions by any user. This did not change the outcome.
You had 3 errors:
You called move_uploaded_file twice.
You declared $tempName variable, but you used $temp_name in the move_uploaded_file function.
You used basename when declaring the temporary file path variable.
Your final code should look like:
if (isset($_POST['submit'])) {
$uploadsDir = '../uploads/';
$name = basename($_FILES["fileToUpload"]["name"]);
$tempName = $_FILES["fileToUpload"]['tmp_name'];
$error = $_FILES['fileToUpload']['error'];
if ($error > 0) {
echo "Error: " . $error . "<br />";
} else {
if (move_uploaded_file($tempName, "$uploadsDir/$name")) {
echo "Successful";
echo "Upload: " . $name . "<br />";
echo "Stored in: Uploads Directory!";
} else {
echo "Did not move files!";
}
}
}
if(isset($_POST['submit'])) {
$uploadsDir = '/';
$name = ($_FILES["fileToUpload"]["name"]);
$tempName = ($_FILES["fileToUpload"]['tmp_name']);
$error = $_FILES['fileToUpload']['error'];
if ($error > 0) {
echo "Error: " . $error . "<br />";
} else {
if(move_uploaded_file($tempName, __DIR__.'/'.$name)) {
echo "Successful";
echo "Upload: " . $name . "<br />";
echo "Stored in: Uploads Directory!";
} else {
echo "Did not move files!";
}
}
}
Related
i have this code for uploading image and storing in database
i want to rename it to a random name first,then upload it and store in database
how should i change my code?
please help me!
here is my PHP code :
$imageFile=$_FILES['image'];
$file_name = $imageFile['name'];
$target_path = "images/news/".$file_name;
if(move_uploaded_file($imageFile['tmp_name'], $target_path)) {
echo "<div id=\"news\">";
echo "Image : "."<br>".$file_name;
echo "<br>";
echo "Successfuly Uploaded!";
echo "<br>";
$newstitle = $_POST['title'];
$newscontent = $_POST['content'];
$newsimage = "images/news/".$file_name;
$sql="insert into news (news_title,news_content,news_image,news_date) values ('$newstitle', '$newscontent','$newsimage',' $newsdate')";
if ($conn->query($sql) === TRUE)
{
echo "Image Stored in DB!</div>";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Try this
Random file name created using $random = md5(uniqid("") . time());
Here is working code that renames your file
$imageFile = $_FILES['image'];
$file_name = $imageFile['name'];
$random = md5(uniqid("") . time());
$target_path = "images/news/" . $random.$file_name;
if (move_uploaded_file($imageFile['tmp_name'], $target_path)) {
echo "<div id=\"news\">";
echo "Image : " . "<br>". $random . $file_name;
echo "<br>";
echo "Successfuly Uploaded!";
echo "<br>";
$newstitle = $_POST['title'];
$newscontent = $_POST['content'];
$newsimage = "images/news/" . $random. $file_name;
$sql = "insert into news (news_title,news_content,news_image,news_date) values ('$newstitle', '$newscontent','$newsimage',' $newsdate')";
if ($conn->query($sql) === TRUE) {
echo "Image Stored in DB!</div>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
feel free to ask ready to help you
I have made a php code to upload a file....It uploads it sucessfully...but how do i phsicaly go and check where it is...?
NOTE : i am getting fail as output from the move_uploaded_file ()
here's my code :
<?php
$allowedExts = array("c", "cpp", "py", "java");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ( ($_FILES["file"]["size"] < 100000) && in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
mkdir ("./upload");
if (move_uploaded_file($_FILES["file"]["tmp_name"],"./upload/" . $_FILES["file"]["name"]))
{
echo "sucess";
}
else
{
echo "fail";
}
}
}
}
else
{
echo "Invalid file";
}
?>
you first check if move_uploaded_file actually able to move file or not as the directory you are moving must have write permissions otherwise move_uploaded_file fails
http://php.net/manual/en/function.move-uploaded-file.php
so must check like
if(move_uploaded_file($_FILES["file"]["tmp_name"],"./upload/" . $_FILES["file"]["name"])
//file moved
else
//error
I am newish to php. But when i learned to program it was on a TI-83 Calculator. with the TI83 their was an if-then statements the could be used. I am writing some code to check if a directory is already created and if not create it. I need it to run the last half of the code either way. here is the code.
<?php
$dir = "/Applications/XAMPP/xamppfiles/htdocs/upload/$_POST[Itemid]/" ;
if (!file_exists($dir) and !is_dir($dir)) {
$upload_dir = mkdir($dir, 0777);
}else{
foreach ($_FILES["file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$filename = $_FILES["file"]["name"][$key];
$filetemp = $_FILES["file"]["tmp_name"][$key];
$filetype = $_FILES["file"]["type"][$key];
$filesize = $_FILES["file"]["size"][$key];
if (file_exists($dir . $filename))
{
echo $filename . " already exists. <br><br>";
}
else
{
echo "Upload: " . $filename . "<br>";
echo "Type: " . $filetype . "<br>";
echo "Size: " . ($filesize / 1024) . " kB<br>";
echo "Temporarily Stored in: " . $filetemp . "<br>";
move_uploaded_file($filetemp,"$dir/$filename");
echo "uploaded the file \"" . $filename. "\" to the \"/Applications/XAMPP/xamppfiles/htdocs/upload/\" Directory<br>" ;
$con=mysqli_connect("localhost","root","","Inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO ListPics (`1`, `Item_ItemID`)
VALUES
('$dir$filename', '$_POST[Itemid]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo ($filename. " added to Database<br><br>");
mysqli_close($con);
}
}
}
}
?>
Yes I know this code is not secure. It will not ever see the interweb(Reverently bows head and says "Thank you Al Gore") It will sit snugly behind a VPN for personal use only. I just need to know how to execute the PHP equivalent of If Then Statements
This is simple:
if(condition) {
/* do something if condition is true */
}
else {
/* do something else if condition is false */
}
/* do other stuff either way */
You only need the else if there is something that you want to do only if the condition is false. If you want to do it either way, then don't use else at all.
So i have a file upload feature on my site and rather than redirect to the php script page, I want to have an iframe that displays the message returned by the script. So here's my html:
<iframe class="iframe" name="my_iframe" src="upload_file.php" style="display:none;"></iframe>
<form id="uploadForm" action="upload_file.php" method="post" enctype="multipart/form-data" target="my_iframe">
So basically I want to hide my iframe UNTIL I the upload process finishes and the script returns a message. Here's my php script:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
session_start();
$allowedExts = array("doc", "docx");
$extension = pathinfo( $_FILES["upload"]["name"],PATHINFO_EXTENSION);
$username = $_SESSION["username"];
if (($_FILES["upload"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["upload"]["error"] > 0)
{
echo "Return Code: " . $_FILES["upload"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["upload"]["name"] . "<br />";
echo "Type: " . $_FILES["upload"]["type"] . "<br />";
echo "Size: " . ($_FILES["upload"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["upload"]["tmp_name"] . "<br />";
$dir_exists = is_dir("/disks/*/*/*/*/". $_SESSION["FirstName"] ."-".$_SESSION["username"]."/");
$file_exists = file_exists("/disks/*/*/*/*/".$_SESSION["FirstName"] ."-".$_SESSION["username"]."/" . $_FILES["upload"]["name"]);
$folderName=$_SESSION["FirstName"];
$baseDir = "/disks/*/*/*/*/";
// Create directory if it does not exist
if (! $dir_exists) {
if (is_writable($baseDir)) {
mkdir($baseDir . $_SESSION["FirstName"]."-".$_SESSION["username"]);
} else {
trigger_error($baseDir. " is not writeable");
}
}
if ($file_exists) {
echo $_FILES["upload"]["name"] . " already exists. ";
} else {
$link = new PDO('mysql:host=***;dbname=***;charset=UTF-8','***','***');
$proptype = $_POST["prop_cat"];
$stmt = $link->prepare("UPDATE Table SET `PType`=:proptype WHERE Username=:username");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':proptype', $proptype);
$stmt->execute();
move_uploaded_file($_FILES["upload"]["tmp_name"],
$baseDir. $_SESSION["FirstName"] ."-".$_SESSION["username"]."/". $_FILES["upload"]["name"]);
echo "Stored in: " . $baseDir. $_SESSION["FirstName"] ."-".$_SESSION["username"]."/". $_FILES["upload"]["name"];
}
}
} else {
echo "Invalid file";
}
?>
So basically to sum up my question: How can I hide the iframe until upload finishes, and then display it with the message that the user can close like an alert box?
Can you echo the Iframe at the end of the upload instead of trying to hide it then show it at the top?
if ($file_exists) {
echo $_FILES["upload"]["name"] . " already exists. ";
} else {
$link = new PDO('mysql:host=***;dbname=***;charset=UTF-8','***','***');
$proptype = $_POST["prop_cat"];
$stmt = $link->prepare("UPDATE Table SET `PType`=:proptype WHERE Username=:username");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':proptype', $proptype);
$stmt->execute();
move_uploaded_file($_FILES["upload"]["tmp_name"],
$baseDir. $_SESSION["FirstName"] ."-".$_SESSION["username"]."/". $_FILES["upload"]["name"]);
echo "Stored in: " . $baseDir. $_SESSION["FirstName"] ."-".$_SESSION["username"]."/". $_FILES["upload"]["name"];
/// load the iframe now ///////////////
echo '<iframe class="iframe" name="my_iframe" src="upload_file.php"></iframe>';
///////////////////////////////////////
}
Uploading an image into a directory, it seems to always try upload "" which is nothing. Rather then an actual image. What am I doing below. I know the value is "" because of what it inserts into the database.
<li class="formProductImage">
<span>Image:</span>
<input type="file" name="productImage" />
</li>
and the php:
if ($_FILES["productImage"]["error"] > 0)
{
echo "Return Code: " . $_FILES["productImage"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["productImage"]["name"] . "<br />";
echo "Type: " . $_FILES["productImage"]["type"] . "<br />";
echo "Size: " . ($_FILES["productImage"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["productImage"]["tmp_name"] . "<br />";
$filename = mysql_real_escape_string($_FILES['productImage']['name']);
$query = "UPDATE products SET image = '$filename' WHERE name = '$name'";
$result = mysql_query($query);
if (mysql_affected_rows() == 1) {
// Show thank you message
echo '<span style="color:green;">Your image was added to database correctly.</span>';
if (file_exists("uploaded/" . $_FILES["productImage"]["name"]))
{
echo $_FILES["productImage"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["productImage"]["tmp_name"],
"uploaded/" . $_FILES["productImage"]["name"]);
echo "Stored in: " . "uploaded/" . $_FILES["productImage"]["name"];
}
} else {
echo '<font color="red">Image note inserted into database.</font>';
echo mysql_error();
}
}
}
}
Make sure you have enctype="multipart/form-data" in the <form> tag.
change this line:
$filename = mysql_real_escape_string($_FILES['file']['name']);
to :
$filename = mysql_real_escape_string($_FILES['productImage']['name']);