I have this code for a form that uploads pictures to my website and saves the information to a mysql database:
<form method='post'>
Album Name: <input type="text" name="title" />
<input type="submit" name="submit" value="create" />
</form>
<h4>Add Photo</h4>
<form enctype="multipart/form-data" method="post">
<?php
require_once 'config.php';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(isset($_POST['upload'])){
$caption = $_POST['caption'];
$albumID = $_POST['album'];
$file = $_FILES ['file']['name'];
$file_type = $_FILES ['file']['type'];
$file_size = $_FILES ['file']['size'];
$file_tmp = $_FILES ['file']['tmp_name'];
$random_name = rand();
if(empty($file)){
echo "Please enter a file <br>";
} else{
move_uploaded_file($file_tmp, 'uploads/'.$random_name.'.jpg');
$ret = mysqli_prepare($mysqli, "INSERT INTO photos (caption, image_url, date_taken)
VALUES(?, ?, NOW())");
$filename = "uploads/" + $random_name + ".jpeg";
mysqli_stmt_bind_param($ret, "ss", $caption, $filename);
mysqli_stmt_execute($ret);
echo "Photo successfully uploaded!<br>";
}
}
?>
Caption: <br>
<input type="text" name="caption">
<br><br>
Select Album: <br>
<select name="album">
<?php
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$result = $mysqli->query("SELECT * FROM albums");
while ($row = $result->fetch_assoc()) {
$albumID = $row['albumID'];
$title = $row['title'];
echo "<option value='$albumID'>$title</option>";
}
?>
</select>
<br><br>
Select Photo: <br>
<input type="file" name="file">
<br><br>
<input type="submit" name="upload" value="Upload">
</form>
This successfully uploads the picture to my 'uploads' folder as well as my mysql database, however, I would like to put in image URL "uploads/(random name generated).jpg"
I have failed to do this with my current code, the information recorded in the 'image_url' column of my photos table is just the random number generated. without the "uploads/" in the beginning and ".jpg" in the end.
I should mention that the schema for my photos table is:
caption, image_url, date_taken, imageID
Any help will be very much appreciated!!
thank you in advance
You are using + (plus) signs to concatenate with, in this line:
$filename = "uploads/" + $random_name + ".jpeg";
PHP uses dots/periods to concatenate with, rather than plus signs which is JS/C language syntax:
$filename = "uploads/" . $random_name . ".jpeg";
Error checking would have signaled the syntax error.
Related
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,
I have created a basic car sales website. I have used the following PHP code to upload my image
$target_folder = "Cars_Photos/";
$target_path = $target_folder . basename( $_FILES['fileToUpload']['name'] );
//echo $target_path . '<br><br><br>';
//print_r($_FILES);
print($_FILES['fileToUpload']['tmp_name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
So the file is being uploaded to the server and that is great (took me ages to get it to work), I am using phpliteadmin as my database manager and I have a field called car_image_url, this is where i paste the url to the image on the server, however I have added a page on the site where users can upload an image themselves, so my question is how can I get this to work.
I am using the following to convert the url to display an image.
echo "<td id='img'><img src=\"". $row["car_image_url"] . "\" /></td>";
However uploading the file is a different story, what code do I use on my website to get the uploaded file to link to the image url.
Here is my PHP code that makes a new car on the main site:
<?php
try {
# Connect to SQLite database
$dbh = new PDO("sqlite:../Car_Sales_Network");
$make = $_POST['Make'];
$model = $_POST['Model'];
$badge = $_POST['Badge'];
$price = $_POST['Price'];
$trans = $_POST['Transmission'];
$ppl = $_POST['P_Plate_Legal'];
$sth = $dbh->prepare('INSERT INTO Cars_On_Network
("car_make","car_model","car_badge","price","trans","P_Plate_Legal")
VALUES
(?, ?, ?, ?, ?, ?)');
$sth->execute(array($make, $model, $badge, $price, $trans, $ppl));
$id = $dbh->lastInsertId();
//header("Location: ../Carsales_Network.php");
}
catch(PDOException $e) {
echo $e->getMessage();
}
$target_folder = "Cars_Photos/";
$target_path = $target_folder . basename( $_FILES['fileToUpload']['name'] );
//echo $target_path . '<br><br><br>';
//print_r($_FILES);
print($_FILES['fileToUpload']['tmp_name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<title>New Vehicle</title>
<link type="text/css" rel="stylesheet" href="New_Car_Form.css"/>
</head>
<body>
<div id="main">
<form action="Insert_Car.php" method="post" enctype="multipart/form-data">
Make:<br>
<input type="text" name="Make">
<br>
Model:<br>
<input type="text" name="Model">
<br><br>
Badge:<br>
<input type="text" name="Badge">
<br>
Price:<br>
<input type="text" name="Price">
<br>
Transmission: <br>
<input type="radio" name="Transmission" value="Manual" checked>Manual
<br>
<input type="radio" name="Transmission" value="Auto">Automatic
<br><br>
P Plate Legal: <br>
<select name="P_Plate_Legal">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<br>
Choose a Picture: <br>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<br>
<br>
<input class="submit" type="submit" value="Submit">
<br>
Let's go back!
<br>
</div>
</body>
</html>
</form>
</body>
</html>
I am sure it is a similar process however I just can't think of how to do it.
Cheers.
it seems to me like youre having trouble with the upload script.
Here is a way that comes in handy (It creates an unique name for all images)
Crate your sql within the WRITE TO DATABASE comment i made:
if(isset($_FILES['fileToUpload'])){
$File = $_FILES['fileToUpload'];
//File properties:
$FileName = $File['name'];
$TmpLocation = $File['tmp_name'];
$FileSize = $File['size'];
$FileError = $File['error'];
//Figure out what kind of file this is:
$FileExt = explode('.', $FileName);
$FileExt = strtolower(end($FileExt));
//Allowed files:
$Allowed = array('jpg', 'png', 'jpeg', 'gif');
//Check if file is allowed:
if(in_array($FileExt, $Allowed)){
//Does it return an error?
if($FileError==0){
//Create new filename:
$NewName = uniqid('', true) . '.' . $FileExt;
//Destination
$UploadDestination = $_SERVER['DOCUMENT_ROOT'] . '/Cars_Photos/' . $NewName;
//Move file to location:
if(move_uploaded_file($TmpLocation, $UploadDestination)){
//Filename = $NewName
//WRITE TO DATABASE:
//encode url:
$Image = urlencode($UploadDestination);
//Redirect:
header("Location: /complete.php?image=$Image&cat=Cars");
}
//File didnt upload:
else{
echo "File didnt upload...";
}
}
//An error occured
else{
echo "An error occured while uploading...";
}
}
//Filetype not allowed
else{
echo "Sorry, the file you tried to upload is not allowed.";
}
}
Complete.php:
<?php
//Your file is here:
echo urldecode($_GET['image']);
I am trying to upload an image with php; but seems doesn't work, and I can't figure out why. When I try to insert only text without an image, it is working fine (I mean if I remove from php part all code for the image uploads); so I guess the error is in this part, but I can't find it.
This is the upload code that I currently use. Any help with this is appreciated.
if (isset($_POST['add'])) {
$text = $_POST['text'];
$title = $_POST['title'];
$category = $_POST['category'];
$fileName = $_FILES['userfile']['userfile'];
$tmpName = $_FILES['userfile']['tmp_name'];
// make a new image name
$ext = substr(strrchr($fileName, "."), 1);
// generate the random file name
$randName = md5(rand() * time());
// image name with extension
$myFile = $randName . '.' . $ext;
// save image path
$path = "/img/" . $myFile;
$result = move_uploaded_file($tmpName, $path);
if (!$result) {
echo "Error uploading image file <br />";
var_dump($_FILES);
exit;
} else {
$db = new mysqli("localhost", "user", "mypass", "mydb");
if (mysqli_connect_errno()) {
printf("Connect failed: %s<br/>", mysqli_connect_error());
}
mysqli_set_charset($db, "UTF8");
$query = "INSERT INTO posts (post_text, image_name, post_image, post_title, category) VALUES (?, ?, ?, ?, ?)";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("ssssi",$text, $myFile, $path, $title, $category);
if (!$conn->execute()) {
echo 'error insert';
} else {
header("Location: index.php");
exit;
}
} else {
die("Error preparing Statement");
}
}
} else {
echo 'error';
}
And here is the form for the upload
<form method="post" action="postblog.php" enctype="multipart/form-data">
Title: <input type="text" name="title" id="title">
Category: <select name="category" id="category">
Desc :<br />
<textarea id="text" name="text" rows="15" cols="80" style="width: 80%"></textarea>
Image: <input type="file" name="userfile" />
<input type="submit" name="add" id="add" value="Добави">
</form>
The error is from here:
if (!$result) { echo "Error uploading image file "; }
change
$fileName = $_FILES['userfile']['userfile']; to $fileName = $_FILES['userfile']['name'];
I want to insert image path into database table so I can later display it on a different place but only thing that is getting inserted into the table is the folder name where pictures are uploaded into and the image name is missing.
Here is my code:
<?php
require "connect.php";
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
$uploaddir = 'uploaded';
if(isset($_POST['submit']))
{
$filename = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$filepath = $uploaddir . $filename;
move_uploaded_file($tmp,$filepath);
$filepath=addslashes($filepath);
mysqli_query($conn,"UPDATE vijesti SET imeslike='$filepath' WHERE id='$id'");
mysqli_close($conn);
}
?>
<div id="main">
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" value="upload"/>
</form>
</div>
Table column named imeslike is supposed to be updated with image path but it only shows uploaded/. It's like it does not accept variables when I put some random string in my query it gets updated and the string value shows up in the imeslike column.
The uploaded folder is in same directory so the relative path is OK and I also tried absolute path like:
$uploaddir="C:/wamp/www/admirovsajt/uploaded"
But same problem.
Verify that image was uploaded before looking for correct path in the database.
instead of:
$uploaddir = 'uploaded';
try
$uploaddir = 'uploaded/';
Try:
<?php
require "connect.php";
if(isset($_GET['id'])) {
echo $id = $_GET['id'];
}
$uploaddir = 'uploaded/';
if(isset($_POST['submit'])) {
$pid = $_POST['pid'];
$filename = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$filepath = $uploaddir . $filename;
move_uploaded_file($tmp,$filepath);
$filepath=addslashes($filepath);
mysqli_query($conn,"UPDATE vijesti SET imeslike='$filepath' WHERE id='$pid'");
mysqli_close($conn);
}
?>
<div id="main">
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="pid" value="<?php echo $id;?>">
<input type="file" name="image"/>
<input name="submit" type="submit" value="upload"/>
</form>
</div>
I'm attempting to upload an image as well as add details such as; title, description and filepath into a database table.
I'm using the following code, but it isn't adding any data to the database;
(The session.php include contains the database connectivity.)
<?php include('includes/session.php');
$uploadDir = 'submitted/pictures/';
if(isset($_POST['submit']))
{
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading <strong>file</strong>";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$title = $_POST['title'];
$description = $_POST['description'];
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";
mssql_query($query);
}
?>
The form code;
<form name="Image" enctype="multipart/form-data" action="upload-pics2.php" method="POST">
Title <input type="text" name="title" maxlength="100" class="textbox" value="<?php echo $form->value("title"); ?>" />
Description <textarea name="description" rows="8" cols="40" class="textbox" value="<?php echo $form->value("description"); ?>"></textarea>
File <input type="file" name="file" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" size="26" class="textbox" />
<input type="submit" name="submit" value="Upload" class="button" />
</form>
I was wondering if someone could tell me what might be going wrong?
Thank you.
This code do not work because of several problems.
First, you should rename one of html fields or change field name when you are checking for upload:
<input type="submit" name="Upload" value="Upload" class="button" />
or
if(isset($_POST['submit']))
Second one, this script will not store any data into DB.
You should get, sanitize and write data into according fields, for example:
$title = mysql_real_escape_string($_POST['title']);
$description = mysql_real_escape_string($_POST['description']);
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";
You should make sure these fields present in DB, if not - you should create them:
ALTER table user_pictures ADD column description text, add column title varchar(255);
You has an error at this line if(isset($_POST['Upload']))
Change this to the if(isset($_POST['submit']))
is the 'submitted/pictures/' writable? also you might want to run is_uploaded_file() for an extra layer of security.
Also your query seems to be wrong
"INSERT INTO $user_pictures ( file ) VALUES ('$filePath')"
$user_pictures needs to be a table
try
"INSERT INTO `user_pictures` ( `file` ) VALUES ('$filePath')"