PHP: Image not uploading to folder - php

Hey guys I think i need a fresh set of eyes on this. I have an insert script that inserts data to the database along with the URL of an image that gets uploaded to a folder called uploads. The problem is that while all the information goes into the database the image never gets uploaded to the folder. Does anyone know why?
<?php
$date=$_POST['date'];
$title=$_POST['title'];
$body=$_POST['body'];
$month=$_POST['month'];
$file = $_FILES['file'];
$name = $file['name'];
$path = "uploads/" . basename($name);
$sql="INSERT INTO content (date, title, body, month, pic_id) VALUES ('$date','$title', '$body', '$month', '" . mysql_real_escape_string($path) . "')";
$result=mysql_query($sql);
if($result && move_uploaded_file($file['tmp_name'], $path) ){
echo 'Query has been inputted into the database';
}
else{
echo 'An error occured';
}
?>
My html looks like this:
<h1>Post A Blog </h1></br>
<form name="personal_information" method="post" enctype="multipart/form-data" action="insert.php">
<label>
<span>Date:<br></span><input id="date" type="date" name="date" />
</label><br><br>
<label>
<span>Title:<br></span><input id="title" type="text" name="title" />
</label><br><br>
<label>
<span>Body:<br></span><textarea id="body" type="text" name="body"/></textarea>
</label><br><br>
<label>
<span>Month:<br></span><input id="month" type="text" name="month" />
</label><br><br>
<br>
Upload file:</br>
<input type="file" name="file" id="fileupload"></br></br>
<input type="submit" name="submit" value="Submit" id="submit"/>

I'm on my phone so can't give you an example but I'm pretty sure that you have to use the fullpath as destination.
try __DIR__ . '/'. $path or use document_root

move_uploaded_file() - Moves an uploaded file to a new location.
is_uploaded_file() - Tells whether the file was uploaded via HTTP POST
This will work for you:
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
}
More detail and example

Related

Upload and save the image path to mysql

I want to upload an image to my server and save the image path to my database,
How can I rename the file to its auto-incrementing id? And save the path to DB
I mean if I have a file image.jpg. when I upload the image I want to rename it automatically to corresponding id.jpg (eg 1.jpg, 2.jpg 3.jpg etc ) and save that path to the database.
Here's the code I've now. But it's not working.
<?php
include 'db.php';
$title = $_POST['title'];
$description = $_POST['description'];
$lang = $_POST['lang'];
$fileName = $_FILES['file']['name'];
$target = "img/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["file"]["tmp_name"];
$result =
move_uploaded_file($tempFileName,$fileTarget);
$add = mysqli_query($conn,"INSERT INTO files(title,description,imgname,imgurl,date,lang) VALUES('$title','$description','$fileName',$fileTarget',CURDATE()),'$lang'");
if($add){
echo "File uploaded successfully";
}
else{
echo "Sorry upload failed.";
}
?>
Here's my form
<html>
<body>
<form name="upload" method="POST" action="upload.php" onsubmit="return validateform()" enctype="multipart/form-data">
<input type="text" name="title"><br>
<input type="text" name="description"><br>
<select name="lang">
<option value="Malayalam">Malayalam</option>
<option value="Tamil">Tamil</option>
<option value="Telugu">Telugu</option></select><br>
<input type="file" name="file">
<input type="submit" value="upload">
</form>
</body>
</html>
I think you have an issue with your insert query check here what the mistake I found...
$add = mysqli_query($conn,"INSERT INTO files(title,description,imgname,imgurl,date,lang) VALUES('$title','$description','$fileName','$fileTarget',CURDATE(),'$lang')");
There ')' is wrongly added near to CURDATE() and also a ' missed for $fileTarget and not well-ended insert query you create use above code for the same,

Create a PHP contact form with multiple image upload

I need to create an html contact form which collects some data and uploads 8 images through a PHP script
This is my HTML:
<form action="formmail.php" onsubmit="return controlloform()" id="form" name="form" method="POST" enctype="multipart/form-data">
<input name="email" id="email" placeholder="Email address" type="text" value="" maxlength="40">
<input name="tel" id="tel" type="text" placeholder="Order number" value="" maxlength="20">
<textarea name="msg" placeholder="Message" value="" maxlength="300"></textarea>
Upload a photo:
<p>
<p>
<input name="file" id="file" class="button" type="file" value="">
<p>
<p>
<td colspan="2">
<input type="submit" class="button" value="Submit" />
</td>
</tr>
</table>
</form>
I don't know how to create the upload script, what I need to do is uploading 2 blocks of 4 images, check the extension of the file (only jpg and png allowed) and the size (max 500 kb for image).
I've already found some upload scripts (not 100% suitable for what I need) but I don't know how to include the upload part into the rest of the code
If anyone could help me would be great
Thanks a lot
This code make multiple upload
$total = count($_FILES['photo_file']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['photo_file']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['photo_file']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
if you want to check file size insert this code
if ($_FILES["photo_file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
this code make validation
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['photo_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
$uploadOk = 0;
}

PHP: Image is not displaying from SQL datdabase

I have checked out other questions of same topic on this site and tried to find the solution but unsuccessful. Images are stored in database and loaded in folder successfully but are not displayed
Here is my code:
<html>
<body>
<form action="image.php" method="post" enctype="multipart/form-data">
<input type="text" name="image_description" placeholder="Enter name" required>
<input type="file" name="myfile">
<input type="submit" name="upload" value="upload">
</form>
</body>
</html>
<?php
include("db.php");
if(isset($_POST['upload'])) {
$image_description = $_POST['image_description'];
$name = $_FILES["myfile"]["name"];
$type = $_FILES["myfile"]["type"];
$size = $_FILES["myfile"]["size"];
$temp = $_FILES["myfile"]["tmp_name"];
$error = $_FILES["myfile"]["error"];
$upload=move_uploaded_file($temp, "uploaded/" . $name);
$query= "INSERT INTO image(image_description,image_name,image_type,image_size) VALUES ('$image_description','$name','$type','$size')";
if(mysqli_query($conn,$query) && $upload) {
echo "successfully uploaded";
}
else
die(mysqli_error($conn));
}
$query = mysqli_query($conn,"SELECT * FROM image");
while($row = mysqli_fetch_array($query))
{?>
<img style="width: 200px;height: 200px;" src="<?php echo 'uploaded/' .$row['image_name'] ?>">
<?php
echo $row['image_description'] . "<br>";
}?>
Images are displayed as in picture
This is database table
The URL of your page is index.php/; notice the trailing slash.
A relative URL (e.g. src="uploaded/..") will resolve to index.php/uploaded/...
That folder obviously does not exist on your disk.
Use root-relative URLs: src="/uploaded/.."
or use relative URLs but go to the right folder: src="../uploaded/.."
or fix your weird URL and make it index.php, from which even relative URLs will resolve correctly.

PHP Form - File Upload Field for Signup

I have created a PHP signup form for visitors to fill and submit that asks for their basic information.
I am trying to accomplish the following two tasks;
Add Image/File Upload Field
Redirect them to a confirmation page
I have been unable to make it work. Below is what I have.
My Code
HTML Form
<form name="form1" method="post" action="signup.php">
Username: <input type="text" name="user">
<br>Email: <input type="text" name="mail">
<br>Experience: <select name="exp"> <option value="beginner">Beginner</option>
<option value="intermediate">Intermediate</option> <option value="advanced">Advanced</option>
</select><br> <input type="submit" name="Submit" value="Sign Up">
</form>
Signup.php
<?php
$username = $_POST['user'];
$email = $_POST['mail'];
$experience = $_POST['exp'];
//the data
$data = "$username | $email | $experience\n";
//open the file and choose the mode
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
//close the file
fclose($fh);
print "User Submitted";
?>
It seems like you lack an input field in your HTML to begin with.
here's an example of a form for uploading files.
<form action="upload.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">
</form>
Once you've done that you're not quite there yet because your file is stored in a temporary folder, you will need to move the file to your uploads folder like so:
$target_file = "uploads/" . basename ($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
I hope this helps!
Ta add an upload you need to add enctype="multipart/form-data" to your form tag,then add the upload field. For the Email field change the type to HTML5 type="email", this will do a little validaation check that it is in the correct format. At the bottom of the php file add a location header if all went well. You could put it all in one file with an if statement at the top.You should also sanitize your inputs
this is a upload file script which will loop through all the data of a file and insert
if(isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name']. "uploaded successfully." . "</h1>";
}
$csv_file=$_FILES['filename']['tmp_name'];
$type=$_FILES['filename']['type'];
$handle = fopen($csv_file, "r");
$i=0;
while (($data = fgetcsv($handle)) !== FALSE) {
if($i>0) {
$import="insert into `table_name`(col1,col2,col3,col4,col5,col6,col7)values('".addslashes($data[0])."','".addslashes($data[1])."','".addslashes($data[2])."','".addslashes($data[3])."','".addslashes($data[4])."','$data[5]','$data[6]')";
mysql_query($import) or die(mysql_error());
}
$i=1;
}
echo "Success";
echo "<br>";
echo $_FILES['filename']['type'];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="" id="">
Choose File:<br>
<input name="filename" type="file" />
<input type="submit" name="submit" value="submit" />
</form>

php file upload in Jquery Mobile

Apologies if this is a duplicate question it just seems that every article i visit doesnt work for me.
I have a basic form which has two fields and a file.
<form action="make_announce.php" method="post" enctype="multipart/form-data" data-ajax="false">
<label>Enter Subject Line (500char max):
<input name="subject" type="text" id="subject" size="50"/></label>
<label>Announcement :
<textarea name="announce" cols="50" rows="10" id="announce"></textarea></label>
<label>Post Image (Leave Blank for NONE)<br>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="file" name="image" /><br /></label>
<div align="center">
<input type="submit" name="Submit" value="OK" />
</div>
</form>
And my PHP File minus most of the variables.
if (!empty($_FILES["image"])) {
$myFile = $_FILES["image"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
$sql="...
mysqli_query($con,$sql);
exit;
}
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
$sql="...
mysqli_query($con,$sql);
exit;
}
else
{
chmod(UPLOAD_DIR . $name, 0644);
$sql="...
mysqli_query($con,$sql);
exit;
}
}
mysqli_close($con);
Although this may not be the best way to do this it does work fine on a basic php web page. however when i put it into a jquery mobile web page it again works but doesnt seem to be posting the file im uploading. even after finding lots of articles telling me to add the data-ajax="false" to my form.
Any help would be very much appreciated.
Thanks in advance.
Turn off Ajax navigation using data-ajax="false" on your form definition because you can't upload files using Ajax.

Categories