I am in the early stage of developing a bidding system whereby users are able to insert items that they want to sell. Here is the script to copy the image from the temporary path and store the path of the image to another folder.
define ("MAX_SIZE","10000");
//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
};
//This variable is used as a flag. The value is initialized with 0 (meaning no error found) and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
$errors = 0;
//Checks if the form has been submitted
if (isset($_POST['Submit']))
{
//Reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
//If it is not empty
if ($image)
{
//Get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//Get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//If it is not a known extension, we will suppose it is an error and will not upload the file, otherwize we will do more tests
if (($extension != "jpg") &&
($extension != "jpeg") &&
($extension != "png") &&
($extension != "gif"))
{
//Print error message
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//Get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//Compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*111111111111024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
//We will give an unique name, for example the time in Unix time format
$image_name=time().'.'.$extension;
//The new name will be containing the full path where will be stored (images folder).
$imagepath='C:\\xampp\\htdocs\\biddingsystem\\Images\\' . $image_name;
//We verify if the image has been uploaded, and print an error instead
$copied = copy($_FILES['image']['tmp_name'], $imagepath);
if (!$copied)
{
echo '<h1>Picture upload failed!</h1>';
$errors=1;
}
}
}
}
//If no errors registred, print the success message
if(isset($_POST['Submit']) && !$errors && isset($_POST['image']))
{
echo "<h1>Picture Uploaded Successfully! Try again!</h1>";
}
Then, I inserted the image path along with other data to a MySQL database with the script below and tried to display them back to the user using a table. Other data worked out fine but for the image display (imagepath), only the path of the image gets displayed, not the image itself.
mysql_query("INSERT INTO items
(username, item, price, description, start_date, start_time, imagepath)
VALUES ('$username', '$_POST[item]', '$_POST[price]', '$_POST[description]','$_POST[start_date]', '$_POST[start_time]', '$imagepath') ")
or die ("Error - Couldn't add item");
echo "Item added successfully";
echo "<h1>You have added the following item:</h1>";
$sql = "SELECT item, price, description, start_time, start_date, imagepath FROM items WHERE username = '$username' AND item='$_POST[item]'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo"<table border=2>
<tr><td>Item</td>
<td>Price</td><td>Description</td><td>Start time</td><td>Start date</td><td>Picture</td></tr>
<tr><td> $row[item]</td>
<td> $row[price]</td>
<td> $row[description]</td>
<td> $row[start_time]</td>
<td> $row[start_date]</td>
<td> $row[imagepath]</td>
</tr>
</table></br>";
I have tried using <img src="<?php $imagepath ?>"> to show the image but to no avail. I have even tried storing the actual image itself in the database using the BLOB type. However, the result is a page filled with strange characters. How do I fix this problem?
You are confusing the filesystem path and web URL. You have to store only /biddingsystem/Images/ part or even just only name and generate full path dynamically at display time.
Also note that you aren't formatting your data properly, which will lead to some bugs and security vulnerabilities. I've explained formatting rules in my earlier answer, to Stack Overflow question How to include a PHP variable inside a MySQL insert statement.
If you want to go with the first solution, displaying from a path, make sure you're pointing to the image in an accessible path. From the code you listed, it looks like $imagepath is a file:// path. On a web server, you'll have to map that to a relative web path.
If you decide to go with the BLOB, the best method is to make a separate page that serves images. Your output image tags should point to that and you need to change the content type in the header of the image service page.
Related
I am building a forum with php and MySQL and I want to append current time to each image that users upload for their profile. I used time() function on each image file uploaded and it worked for the image file but I have trouble inserting the new filename into the database. I wanted to give each image a unique name to prevent override.
OK here is what I did: I stored the current time as $time and the filename in a variable, $photo and I tried to insert that variable’s value using $photo .= $time into the database so it has the filename as I did with each uploaded image. However the original filename is inserted into the database in every attempt.
Any workarounds?
$image = $_FILES['photo']['name'];
$time = time();
$image .= $time;
delete the existing photo
delete(image_dir/$row['current_photo.jpg']);
//does not work, but i want something like that
if(move_uploaded_file($_FILES['photo']['tmp_name'], 'image_dir/$image') {
$query = "INSERT INTO profile (user_id, profile_photo) VALUES($id, $image)";
mysqli_query($dbc, $query);
if(mysqli_affected_rows($dbc) == 1) {
echo "added to the database!";
}else {
echo "failed to add photo to the database";
}
}else {
echo "failed to upload photo";
}
how can i give the uploaded image unique the name since the original image name gets inserted in the database in every try i make?
i know the code looks funny :). just want to show the logic.
If you need a unique id, you can use the uniqid function
$name=uniqid();
you may need to use
$filename=uniqid();
I am trying to update images in my upload folder and mysql database the file uploads giving the file name 0.jpg instead of the normal persons id 13.jpg and does not update in mysql database, here is my snippet below what am i doing wrong?
$pic = mysql_real_escape_string(htmlspecialchars($_FILES['photo']['name']));
//This gets all the other information from the form
$pic=($_FILES['photo']['name']);
$file = $_FILES['photo']['name']; // Get the name of the file (including file extension).
$ext = substr($file, strpos($file,'.'), strlen($file)-1);
if(!in_array($ext,$allowed_filetypes))//check if file type is allowed
die('The file extension you attempted to upload is not allowed.'); //not allowed
if(filesize($_FILES['photo']['tmp_name']) > $max_filesize) //check that filesize is less than 50MB
die ('The file you attempted to upload is too large, compress it below 50MB.');
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("office") or die(mysql_error()) ;
//Writes the information to the
$target = "images/" .mysql_insert_id() . $ext;
$staff_id = mysql_insert_id();
$new_file_name = mysql_insert_id() . $ext;
//I removed ,photo='$target' to display only id as picture name
mysql_query("UPDATE development SET photo='$new_file_name' WHERE staff_id=$staff_id");
//Writes the file to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
Instead of this
$staff_id = mysql_insert_id();
$new_file_name = mysql_insert_id() . $ext;
//I removed ,photo='$target' to display only id as picture name
mysql_query("UPDATE development SET photo='$new_file_name' WHERE staff_id=$staff_id");
do something like thus
mysql_query ("INSERT INTO development (photo) VALUES ( '".$new_file_name."' )");
//first insert
$staff_id = mysql_insert_id() ;
// then get the id of the record you've just inserted
Firstly, you're using the mysql_* functions, which are deprecated as of 5.5.
Secondly, you need to look at the manual page for mysql_insert_id. Quote:
Retrieves the ID generated for an AUTO_INCREMENT column by the
previous query (usually INSERT).
This means that you can only call mysql_insert_id() AFTER you've inserted data into or updated your users/persons table. In your case, however, it seems as though you already have the ID of the person stored in the variable $staff_id, so you probably don't even need to use mysql_insert_id. Would this not work instead?
$target = "images/" . $staff_id . $ext;
I'm having issue uploading a BLOB into my MySQL database and get the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄ' at line 1
I know the error is resulting in the image's file contents but I can't figure out what's wrong with the syntax. Any suggestions? Thanks!
Here's the PHP:
$file = $_FILES['image']['tmp_name'];
// If there's no file selected when button is pressed, echo out and tell the user to select an image to upload
if (!isset($file))
echo "<p>Please select an image to upload.</p>";
else {
//mysql escape string
$image = file_get_contents($_FILES['image']['tmp_name']);
//and here
$image_name = $_FILES['image']['name'];
$imagesize = getimagesize($_FILES['image']['tmp_name']);
}
// Checks that the file being uploaded is an image, i.e. has a size attribute with height & width dimensions
if ($imagesize == FALSE)
echo "<p>Please upload only an image file such as .jpg or .png.</p>";
else {
$sql = "INSERT INTO design (id, caption, image) VALUES ('', '$image_name', '$image')";
$result = mysql_query($sql);
if (!$result)
echo "<p>Something went wrong.</p>" . mysql_error();
else {
echo "<p>Thank you for submitting your design.</p>";
}
}
Apparently the image file contents has an apostrophe in it. That's not that surprising. You need to properly escape the input (and all inputs for that matter).
$image = mysql_real_escape_string($_FILES['image']['tmp_name']);
Instead of using ext/mysql, you should use properly parameterized queries with mysqli or PDO. Then you don't have to escape explicitly.
I am only starting with PHP and as a part of exercise I wanted to design small website that allows you to upload image and then display all uploaded images
I got the image upload succesfully working and images are stored in database but I cant find the way to display images in table along with other data
$i=0;
while ($row = mysql_fetch_array($result))
{
echo '<td>'.mysql_result($result,$i,0).'</td>';
echo '<td>'.mysql_result($result,$i,1).'</td>';
echo '<td>'.mysql_result($result,$i,2).'</td>';
echo '<td>'.mysql_result($result,$i,3).'</td>';
echo '<td>'.base64_encode($result,$i,4).'</td>';
echo '<tr>';
$i++;
How to modify the code so the image is displayed?
this is code used to upload image
if (isset($_FILES['photo']))
{
#list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
// Get image type.
// We use # to omit errors
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = 'Error: unknown file format';
if (!isset($msg)) // If there was no error
{
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO {$table}
SET ext='$ext', title='$title',
data='$data'");
This is where I test it enter link description here
I was looking at Stack Overflow examples, but I couldn't find any that has the loop in it with data outputted into a table.
As you are starting with PHP, you should start with the right foot :)
Don't use mysql_* functions, these are deprecated. Instead, use mysqli_* or PDO
Storing images in the DB is "a bad idea", you better store the files in the file system (a-k.a. the HD) and reference the name to a field in the DB.
Instead of mysql_fetch_array, try with mysql_fetch_assoc so you can call the fields by name. i.e.: $row['db_field_name'];
About your problem, you will need a extra script to display the stored image. Something like this:
<?php
...
$row = mysql_fetch_assoc($result);
header("Content-type: image/jpeg"); //Set the correct image type.
echo $row['data'];
exit;
?>
And in your display html:
...
<img src="yourscript.php?image=XX" ...>
...
Hope this help :)
i have been stressing for an hour at this stupid script i am trying to make it uploa an MP3
file to a folder it creates.
It is putting the information into mysql and making the folder bu when i ftp the folder is empty with no music file in there
here is the script thanks so so so much!
BTW $name is the POSTED name and full name is the posted name + ".mp3"
// BEGIN ENTERING INFORMATION TO MYSQL TABLE
$sql = mysql_query("INSERT INTO mattyc (name, date, length, size, link)
VALUES('$name','$date','$length','$size','$link')"
) or die (mysql_error());
mkdir("../music/albums/donjuma/$name", 0777);
$song = ("../music/albums/donjuma/$name/$fullname");
if (file_exists($song)) {
unlink($song);
}
$newname = "$fullname";
$newfile = rename(($_FILES['song']['tmp_name']),($newname));
$place_file = move_uploaded_file( $newfile, "../music/albums/donjuma/$name/"."$newname");
$success_msg = "<font color=\"#009900\">Your SONG has been updated, it may take a few minutes for the changes to show... please be patient.</font>";
echo $success_msg;
}
}
}
$newfile =
rename(($_FILES['song']['tmp_name']),($newname));
$place_file = move_uploaded_file(
$newfile,
"../music/albums/donjuma/$name/"."$newname");
rename() returns a bool, not a filename. So your move_uploaded_file() call is going to fail. Any file renaming should be part of your move_uploaded_file() call, don't try and do anything with your temporary file apart from move it.