Insert image MYSQL based on radio button choice with PHP - php

I have a website. In this website I can upload images that are then placed into my SQL database. From here I select the images from the database and show them as thumbnails in the photo gallery, when clicked on the image it shows a large version where you can vote/like and comments etc.
Now what I am trying to do is make 3 category pages, basically 3x the photo gallery that shows the thumbnails.
I have 3 different tables in my database where I insert the images in to.
So I copied the photo gallery 3x and the original upload table in the database 3x.
How ever I do not want to create 3 upload.php files for each photo gallery.php file.
What I'm trying to do is have 3 radio button choices on my upload page and with the choice made there, the image gets uploaded into the matching database table (photo1, 2 or 3).
I have been trying to do this with Functions etc. but I just can't get it to work, I am probably doing something really simple, really stupid.
This is the code i have for the radio button and getting the image:
$titel = "Image";
$query = "SELECT * FROM `i268296_studie`.`fotos` ORDER BY foto_ID DESC";
$result = mysqli_query($conn, $query) or die("query error " . mysqli_error($conn) );
$fotos = array();
//create array from images in database
while($data = mysqli_fetch_assoc($result))
{
$fotos[] = array('src' => $data['src'], 'id' => $data['foto_ID']);
}
?>
<section id="upload">
<form method="post" action="upload.php" enctype="multipart/form-data">
<label for="bestand">Upload image:</label><br><br>
<input type="file" name="bestand" id="file"><br><br>
<label for="categorie"> Categorie: </label>
<input type="radio" name="cat" value="cat1">Portrait
<input type="radio" name="cat" value="cat2">Landscape
<input type="radio" name="cat" value="cat3">Other
<input type="submit" name="submit" value="Upload">
</form>
</section>
<?php
}
?>
<section class="images">
<?php
//show image thumbnails in photogallery
foreach($fotos as $foto)
{
?>
<img class="image" src="<?php echo 'upload/thumb/t_'.$foto['src'];?>">
<?php
}
?>
</section>
The above code I have 3 times (surrounded by HTML etc. as the photo gallery pages).
This is my Upload file (i'll leave most of the thumbnail making code out of it since it's only about the upload part).
$titel = "Image";
$dir='upload/';
$allowedExts = array("jpg", "jpeg", "gif", "png");
$answer= $_POST['cat'];
//Properties of the to be uploaded file
$fileName = $_FILES["bestand"]["name"]; //file name
$fileType = $_FILES["bestand"]["type"]; //file format
$fileSize = $_FILES["bestand"]["size"]; //file size
$tmpName = $_FILES["bestand"]["tmp_name"]; //temporary save location for file
$error = $_FILES["bestand"]["error"]; //error check for file
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
//select image from database and check if it already exists
$sql = "SELECT * FROM `i268296_studie`.`fotos` WHERE src = '$fileName'";
$result = mysqli_query($conn, $sql) or die("query error " . mysqli_error($conn) );
$data = mysqli_fetch_assoc($result);
$num_rows=mysqli_num_rows($result);
if($num_rows > 0)
{
echo 'File already exists <br>';
echo '<a href="fotogallerij.php">Return to homepage/a>';
}
else
{
// if file doesn't exist move to database, create thumbnail path
if (move_uploaded_file( $tmpName,$dir.$fileName))
{
function category($cat, $titel, $filename)
{
global $conn;
$query = "INSERT INTO `i268296_studie`.`$cat` (`titel`, `src`) VALUES ('$titel', '$fileName')"; //INSERT file into database
$result = mysqli_query($conn, $query) or die("query error " . mysqli_error($conn) );
}
$tname = 't_'.$fileName;
$tpath = $dir.'thumb/';
$tnamestate = $tpath.$tname;
$tptype = substr($fileType,6);
$ttype = "imagecreatefrom$tptype";
$name = $fileName;
$path = $dir;
$namestate = $path.$name;
$width = 100;
$height = 100;
list($width_orig, $height_orig) = getimagesize("$namestate");
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig)
{
$width = $height*$ratio_orig;
}
else
{
$height = $width/$ratio_orig;
}
How ever I am staring myself blind on how to fix it or where to place it so it works.
I hope my explanation and question is clear to you guys trying to help me, if not please let me know what I can change or do to help :)
edit:
The errors I am getting are:
Undefined variable: titel
Undefined variable: fileName
Undefined variable: conn
mysqli_query() expects parameter 1 to be mysqli, null given
When I do not pick a radio button but just upload it directly i just get 1 error:
Undefined index: cat
And it uploads it into the 3rd category
Edit 2:
Changed the function with the global $conn in it.

1 function category($cat, $titel, $fileName) {
2 global $conn;
3 $query = "INSERT INTO `i268296_studie`.`$cat` (`titel`, `src`) VALUES ('$titel', '$fileName')";
4 $result = mysqli_query($conn, $query) or die("query error " . mysqli_error($conn) );
5 }
1: you need these variables from the context calling the function
2: you need the global $conn variable in the function context to be able to run the query
3: use a function parameter for the table to upate call
4: it would be better to return results instead of breaking inside the function
The calling code would be like the following:
if ($answer == "cat1") {
category("fotos", $titel, $fileName); // or "foto2", $titel, $fileName .....
}
Please mind the comments about injection vulnerabilities.
Also read this: http://php.net/manual/it/language.variables.scope.php

Related

Can we insert three images using three input type file in a single php form?

since i'm a newbie in PHP i'm asking this question. I can do a single insert image with a nice validation but i want to do this with 3 image. (leave the validation part). Just correct me if i'm wrong. Any help is appreciated.
Can i insert three images with the following format? It takes 7 days to ask next question, please help me out guys.
<?php
if (isset($_POST['upload']))
{
$fileName1 = $_FILES["uploaded_one"]["name"];
$fileTmp1 = $_FILES["uploaded_one"]["tmp_name"];
$fileType1 = $_FILES["uploaded_one"]["type"];
$fileSize1 = $_FILES["uploaded_one"]["size"];
$fileName2 = $_FILES["uploaded_two"]["name"];
$fileTmp2 = $_FILES["uploaded_two"]["tmp_name"];
$fileType2 = $_FILES["uploaded_two"]["type"];
$fileSize2 = $_FILES["uploaded_two"]["size"];
$fileName3 = $_FILES["uploaded_three"]["name"];
$fileTmp3 = $_FILES["uploaded_three"]["tmp_name"];
$fileType3 = $_FILES["uploaded_three"]["type"];
$fileSize3 = $_FILES["uploaded_three"]["size"];
if (!preg_match("/.(jpeg|jpg|png)$/i", $fileName1 || $fileName2 || $fileName3) )
$folder = "upload/";
$moveResult1 = move_uploaded_file($fileTmp1, "$folder/$fileName1");
$moveResult2 = move_uploaded_file($fileTmp2, "$folder/$fileName2");
$moveResult3 = move_uploaded_file($fileTmp3, "$folder/$fileName3");
$insert = "SQL INSERT QUERY TIRED TO TYPE";
$run = mysqli_query($db,$insert);
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="uploaded_one" />
<input type="file" name="uploaded_two" />
<input type="file" name="uploaded_three" />
<button name="upload">Submit</button>
</form>
And I think my preg_match() is giving error. is there a better way to do this?
You could create an array with the name suffix and loop through the array while you check each file separately.
foreach(['one', 'two', 'three'] as $item)
$name = $_FILES["uploaded_{$item}"]["name"];
$tmp = $_FILES["uploaded_{$item}"]["tmp_name"];
$type = $_FILES["uploaded_{$item}"]["type"];
$size = $_FILES["uploaded_{$item}"]["size"];
if (!preg_match("/.(jpeg|jpg|png)$/i", $name))
$folder = "upload/";
$result = move_uploaded_file($tmp, "$folder/$name");
}
Can you use just an input multiple for upload your 3 files un the same input ?

php,mysql_query, mysql_fetch_array while loop of <a href>

I am kinda new to PHP and I am buliding a music library as a school project.
There is a Table 'albums' which holds 'id' and 'name'.
and a table 'songs' containing 'id','name','album_id' and 'path'.
Long story short,I am trying to display all the songs that are in the selected album.
user creates an album and then uploads songs into it.that part works great and the DB is filled in correctly.
problem is, once I select an album to view the songs that are in it I get nothing.
<?php
$album_id = $_GET['id'];
//display songs from selected album
$query = mysql_query("SELECT * FROM songs WHERE album_id = $album_id");
while ($fetch_songs = mysql_fetch_array($query)) {
$song_name = $fetch_songs['name'];
$song_path = $fetch_songs['path'];
?>
play song
<br/>
<b><?php echo $song_name; ?></b>
<?php
}
?>
</div>
I believe using a href would be the simplest option, yet I've tried also audio controls and even trying to upload an image with img src istead of an MP3 and still no success, I just get an empty page.
this is the code for song uploading to DB.
if (isset($_POST["upload"])) {
$name = $_POST['name'];
$album_id = $_POST['album'];
$file_name = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$random_name = rand();
if (empty($name) || empty($file_name)) {
echo "Please fill all fields in the form ! <br/>";
} else {
move_uploaded_file($file_tmp, 'music/' . $random_name . '.mp3');
mysql_query("INSERT INTO songs VALUES ('','$name','$album_id','$random_name.mp3')");
echo "File uploaded ! </br></br>";
}
}
?>
Thanks for any help.
try this code :
while ($fetch_songs = mysql_fetch_array($query, MYSQL_ASSOC))
more information : http://php.net/manual/en/function.mysql-fetch-array.php

PHP image upload and assignment of unique file name

Thank you in advance. I've checked similar questions and they are not helping because the work flow is set up differently.
Trying to get working:
1.user uploads image via form field
2.(SCRIPT 1) on other page script assigns unique name (SCRIPT 2), saves image file to server and image URL is uploaded to SQL. Goes to new page at end of script.
Problem is I'm not getting errors, the script runs and the new page opens but there is no file saved on the server and no data inserted into the SQL table (the entry date adds but not the image URL). My PHP.ini instructions far exceeds the size of the images I've been testing with. The folder location is chamode 0777. I'm posting the whole script because with getting errors it's hard to see where problem lies.
Image processing
<?php
require_once 'unique_gen.php';
$page_path = $_POST['page_path'];
$imgloc = "/avatars/";
//up one directory level
$store_loc = "..".$imgloc;
$link_loc = "http://www.webapge.com".$imgloc;
//Upload and characterize image file
if(isset($_FILES['image'])){
//File
$upload['image'] = $_FILES['image'];
//Verify
if ($upload['image']["error"] > 0){
die ("File Upload Error: " . $upload['image']["error"]);
}else{
//Upload
$img_ext = end(explode('.', $upload['image']['name']));
//Unique code generator
$image_name = implode('.', array(unique_generator(),$img_ext));
while(file_exists($store_loc.$image_name)){
$image_name = implode('.', array(unique_generator(),$img_ext));
}
$image_name = $upload['image']['name'];
//Move file to another location
move_uploaded_file($upload['image']["tmp_name"],$store_loc.$image_name) or exit("<br>Error, IMAGE file not moved!");
//Save location as link
$link_to_img = $link_loc.$image_name;
}
}else{
$image_name = "";
}
//connect to db
$con=mysqli_connect("localhost","usernm","pssword","dbName");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert to SQL
$sql="INSERT INTO comments (avatar, entry_date)
VALUES
('$_POST[link_to_image]', now())";
//verify insert
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
//direct to new page using variable
header('Location: http://www.weBsite.com/' . $page_path);
//close session
mysqli_close($con);
?>
Unique generator
<?php
function unique_generator($lot_size = 15){
$alpha_s = range('a', 'z');
$alpha_l = range('A', 'Z');
$numbers = range(0, 9);
$char = array_merge($alpha_l,$alpha_s,$numbers);
$code = "";
for($i = 0; $i < $lot_size; $i++){
$key = rand(0,count($char)-1);
$code .= $char[$key];
}
return $code;
}
?>
Try putting this at the top of your script:
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');
?>
This at the bottom:
<?php
print_r(array_keys(get_defined_vars()));
print_r(array_values(get_defined_vars()));
?>

$_FILES Uploads Only First File When Parsed

Ok guys this might seem like such a newbie issue but I've got looping issues that I just can't seem to work around. I'm simply trying to upload multiple images on my first project site.
When I posted this test php page up, it uploads all the files that I requested of it fine
; with all images that I wish to upload being uploaded at the directory intended.
<?php
$files = $_FILES['fileField'];
for ($x = 0; $x < count($files['name']); $x++)
{
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
move_uploaded_file($tmp_name, "property_images/$property_name/" . $name);
header("location: property_list.php");
exit();
}
?>
However when I tried including my parser, though it goes into the correct directory, only the first file gets uploaded
<?php
if(isset($_POST['property_name'])){
$property_name = mysql_real_escape_string($_POST['property_name']);
$district = mysql_real_escape_string($_POST['district']);
$address = mysql_real_escape_string($_POST['address']);
$property_type = mysql_real_escape_string($_POST['property_type']);
$sql = mysql_query("SELECT id FROM mydb WHERE property_name='$property_name' LIMIT 1");
$propertyMatch = mysql_num_rows($sql);
if($propertyMatch > 0)
{
echo 'Sorry, you tried to place a duplicate "Property Name" into the system, click here';
exit();
}
$sql = mysql_query("INSERT INTO mydb (property_name, district, address, property_type) VALUES ('$property_name','$ district','$address','$property_type')")or die (mysql_error());
if (!file_exists("property_images/$property_name"))
{
mkdir("property_images/$property_name");
}
$files = $_FILES['fileField'];
for ($x = 0; $x < count($files['name']); $x++)
{
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
move_uploaded_file($tmp_name, "property_images/$property_name/" . $name);
header("location: property_list.php");
exit();
}
}
?>
The count code works fine so I think its either these {} buggers or I need to get my eyes fixed. Any help would be uber appreciated.
you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at http://www.php.net/manual/en/features.file-upload.multiple.php
hope this will sure help you.

php file upload not working right

I have been assigned the task of fixing an older php site since it has been moved to a newer server. The server it is on now doesn't allow globalized variables and that's pretty much all this site was running off of. When trying to upload an image, my sql statement is showing everything but the id for the listing I am adding the image to. I was hoping someone could help me figure this out.
This is my upload function:
function upload(){
global $imagefolder, $id;
global $tbl_units;
include "globalizePOSTGET.php";
// $uid = uuid();
$minsize = 5000; // 5kb
$maxsize = 3000000; // 3mb
$ext = explode('.',basename($_FILES['userfile']['name']));
$ext = $ext[count($ext)-1];
$ext = strtolower($ext);
if ($ext != "jpg" && $ext != "jpeg" && $ext != "png") {
echo "<script> alert('Image is not a png or jpeg format'); </script>";
return false;
}
$imagename = $_POST['id']."_img".$_FILES['img'].".$ext";
$imagename2 = "X_".$imagename;
$uploadfile = $imagefolder . $imagename;
$uploadfile2 = $imagefolder . $imagename2;
$uploadthumb = $imagefolder . "tn_" . $imagename;
if (file_exists($uploadfile)) unlink($uploadfile);
if (file_exists($uploadthumb)) unlink($uploadthumb);
if (file_exists($uploadfile)) {
echo "<script> alert('Image already exists!'); </script>";
}
else
{
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
// check the file is less than the maximum file size
if($_FILES['userfile']['size'] < $maxsize) {
$imgData = addslashes(file_get_contents($_FILES['userfile']['tmp_name'])); // prepare the image for insertion
$size = getimagesize($_FILES['userfile']['tmp_name']); // get the image info..
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile2)) {
$Image = #imagecreatefromjpeg($uploadfile2);
if ($Image) {
$img_height = imagesy($Image);
$img_width = imagesx($Image);
imagedestroy($Image);
}
if ($img_height > $img_width) { // portrait
$tempMultiplier = 150 / $img_height;
$tempMultiplierFull = 600 / $img_height;
} else {
$tempMultiplier = 150 / $img_width;
$tempMultiplierFull = 600 / $img_width;
}
$imageHeight = $img_height * $tempMultiplier;
$imageWidth = $img_width * $tempMultiplier;
$fullimageHeight = $img_height * $tempMultiplierFull;
$fullimageWidth = $img_width * $tempMultiplierFull;
createthumb($imagename2,"tn_".$imagename,$imageWidth,$imageHeight);
if($_FILES['userfile']['size'] > $minsize) {
createthumb($imagename2,$imagename,$fullimageWidth,$fullimageHeight);
if (file_exists($uploadfile2)) unlink($uploadfile2);
} else {
rename($uploadfile2, $uploadfile);
}
$sql = "UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id'];
echo $sql;
if(!mysql_query($sql)) {
echo "<script> alert('Unable to upload file'); </script>";
} else {
?> <script>location.replace('memonly.php?action=edit_record&id=<?php echo $id; ?>');</script> <?php
}
}
} else {
// if the file is not less than the maximum allowed, print an error
$file_n = basename($_FILES['userfile']['name']);
$file_s = $_FILES['userfile']['size'];
?>
<script> alert("File exceeds the maximum limit of <?php echo $maxsize; ?>\nFile <?php echo $file_n; ?> is <?php echo $file_s; ?>");</script>
<?php
}
}
}
}
I am echoing the sql statement on the line that is giving me the error, I think. After clicking on submit, the page tells me Unable to upload file'. Which is why I echoed the sql there. I end up with a sql statement looking like this:UPDATE member_units SET photo = "_img.jpg" WHERE id = `
Someone please help me! I am very inexperienced in PHP and I have no idea what to do here.
Here is the form that is doing the uploading:
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="hidden" name="_submit_check" value="1" />
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="hidden" name="img" value="<?php echo $img; ?>" />
Image URL: <input type="file" name="userfile" value="" style="font-size: 10px; width: 100%;">
<input type="submit" value="Submit" onClick="return validate();">
<input type="button" value="Cancel" onClick="location.href='/memonly.php?action=edit_record<?php echo "&id=$id&memberid=$memberid"; ?>';">
</form>
The first thing you need to do with this kind of problem is work through where the issues seem to be happening. So take your echoed statement...
UPDATE member_units SET photo = "_img.jpg" WHERE id = `
This corresponds to...
UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id'];
We can see by comparison that it is clear that $_FILES['img'] is and empty variable as far as converting it to a string goes. The same is said for $_POST['id'], while $imagename gives a short _img.jpg file name.
Tracking back you can then see that $imagename comes from...
$_POST['id']."_img".$_FILES['img'].".$ext";
This is where your photo = "_img.jpg" comes from. Again, $_FILES['img'] and $_POST['id']
The fact that you're reaching the echo statement means that something is uploading, but it is through the $_FILES['userfile'] array, with all of it's associated variables, for example $_FILES['userfile']['name'] which would give you the filename of the image being uploaded.
What you need to ask yourself next is where you are expecting $_POST['id'] to come from, since it is missing or empty, and what field in your HTML form delivers that variable. Then you need to ask yourself what you are trying to achieve with your naming system. For example if you want an image file to look like: 1_imgLolCat.jpg then your variable will need to look more like
$imagename = $_POST['id']."_img".$_FILES['userfile']['name'];
However the final part of my answer below makes me think that instead of the file name, what you're looking for is actually a POST variable that denotes a category or type of image, in which case you may want to work from...
$imagename = $_POST['id']."_img".$_POST['img'].".$ext";
...if a HTML field exists with the name "img"!
Finally take a look at your SQL statement...
SET photo".$_FILES['img']." = \"" . $imagename . "\"
And double check your tables, since what you appear to be trying to do is set a unique variable in your table that would depend on something passed from the form. I may be wrong here but I assume (as I said above) you want $_POST['img'] in there.
Word of warning, you need...NEED to sanitise these variables before you input them in to a SQL statement like this. Someone could easily take
SET photo".$_POST['img']
and delete your whole table if permissions were set up for your database use to do so. There are plenty of other answers around as to how to do this properly. :)
It seems like 'id' field is not sent in the HTML form. I guess it should be a hidden input ?
Be careful, your script can be the target of an SQL injection : you use a user input ($_POST['id']) directly in an SQL query. You should check if this input is actually set and numeric.

Categories