Is it possible to upload images/files by sending the POST or REQUEST, parameters in the URL without HTML content?
I created a PHP file that gets a image from my someone, stores that file into the database, and a in a folder on my computer. It works fine but what I want to do now is remove the html content and only allow someone to send the images/files via the URL. I tried using $_GET but I received a lot of errors. I also researched this and read that only $_POST will work.
Here is my PHP source code with HTML but keep in mind, "I want the page blank and the only way for someone to send the images/files is through URL".
PHP:
if(isset($_POST['submit'])){
if(#getimagesize($_FILES['image']['tmp_name']) ==FALSE){
// Select an image
echo "Please select an image.";
}
else{
// THE PATH TO STORE THE UPLOAD IMAGE
$target = "images/".basename($_FILES['image']['name']);
//CONNECT TO DATABASE
$db = mysqli_connect("localhost", "root", "");
mysqli_select_db($db, "magicsever");
if(mysqli_connect_error()){
die ("Database connection error");
}
//GET ALL THE SUBMITTED DATA
$image = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
//Store te submitted data to database
$sql = "INSERT INTO image_test (name, image)VALUES ('$name','$image')";
$query = mysqli_query($db, $sql);
//Now lets move the uploaded image into the folder
$nullResult = array();
$nullResult['Image'] = (move_uploaded_file($_FILES['image']['tmp_name'], $target))? "Successful": "Unsuccessful";
echo json_encode($nullResult);
}
}
HTML:
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<br></br>
<input type="submit" name="submit" value="Upload">
</form>
$_POST['']; Parameters come from the usually the form that has the method set to POST, like yours has, that input type you have (file, named image) will be returned has $_POST['image'], $_REQUEST on the other hand is the "GET" method, it works in the same way, the only difference is it's not secure and it comes in the url. I would recommend using POST to be honest. Also use PDO because your code is vulnerable to SQL injection. (mentioned by Alex Howansky)
Related
** EDIT: I resolved the issue on my own. Thanks for all your help. **
I'm trying to insert image files to my database for testing, and found that my code stopped working (it was able to do what it did before).
When I submit the image to the database it appends the image id, but not the 'username' and 'img_name'(filename) fields - these two fields just show up as empty strings. Can you tell me what's wrong with my code and how I can fix this? Your help is very appreciated
This is a summary of my database:
Database Name: photos
Table Name: images
Row Names: id[primary key], username, img_name
And my HTML and PHP codes for uploading image file to the database:
<form method="post" action="uploadindex5.php" enctype="multipart/form-data">
<input type="file" name="membimg">
<input type="submit" name="membupload">
</form>
if (isset($_POST['membupload'])) {
$username = $_SESSION['username'];
$membupload = $_POST['membupload'];
$membimg = $_POST['membimg']['name'];
$membtarg = "images/".basename($_FILES['membimg']['name']);
$membmuf = move_uploaded_file($_FILES['membimg']['tmp_name'], $membtarg);
$servername = "localhost";
$sroot = "root";
$password = "";
$dbname = "photos";
$conn = mysqli_connect($servername,$sroot,$password,$dbname);
if (mysqli_connect_errno()) {
throw new Exception(mysqli_connect_error(), mysqli_connect_errno());
}
$sql = "INSERT INTO images (username, img_name) VALUES ('$username', '$membimg')";
$result = mysqli_query($conn, $sql);
if ($membmuf) {
$msg = "Image uploaded";
} else {
$msg = "Upload failed";
}
}
I'd put dummy values in for the session and post values just hard code it and see if the PHP code is working and then determine if those variables are even set once i verified my php code works properly. Once you hard code those questionable variables then you can run the PHP page without submiting it with the form or ajax or however you are calling it. The PHP page will report the errors if you have PHP error reporting on. Javascript console may even tell you if there is a 500 internal server error which indicates the PHP script isn't working.
I was able to develop a code in enabling users to freely upload images, while the pictures would be stored to the MySql database. But I also would like to add to the php and mysql code image categories where before uploading the image, users can select from ether category- All, People, Cities, Nature and Others then click submit. How do I add that to my php code and mysql table? See my original code below:
<?php
$dbCnn = mysql_connect('', '', '');
mysql_select_db('', $dbCnn);
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = addslashes(file_get_contents($_FILES['file']['tmp_name']));
$insStr = "INSERT INTO imagedata(id, image) VALUES ('', '{$image}')";
mysql_query($insStr);
}
Don't store images in database because it's useless. Instead of this, store in database only path to file and file save on server.
So...
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<select name="category">
<option>Nature</opton>
<option>People</option
</select>
</form>
<?php
if(isset($_POST['category']) && isset($_FILES['file']['tmp_name'])){
//mysql connect etc
move_uploaded_file($_FILES['file']['tmp_name'], path/where/to/save/file);
mysql_query("INSERT INTO table VALUES('{$_FILES['file']['name']}', '{$_POST['category']}')");
}
Hello I am here yet again with another problem.
As I followed a tutorial I tried to save images to my database. It all worked fine and dandy with no error messages but for some reason the image refuse the get stored. Nothing show up at all!
<html>
<body>
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image"><input type="submit" name="submit" value="Upload" />
</form>
<?php
if(isset($_POST['submit'])) {
mysql_connect("localhost","root","") or die("Could not find database!");
mysql_select_db("Image") or die("Could not find database!");
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
if(substr($imageType,0,5) == "image") {
mysql_query("INSERT INTO 'blob' VALUES ('','$imageName','$imageData')");
echo "File uploaded!";
}
else
{
echo "Only images are allowed!";
}
}
?>
</body>
</html>
Database:
id, name, image:
int(Auto increment), varchar(40), mediumblob(because of the size)
The only odd thing about this is that "file_get_contents" is blacked out(I use notepad++).
Otherwise I don't see whats wrong, I have checked guides and whatnot but the thing is that I need to use this method in another form that have a large amount of information stored(15 fields including a description). I am still very new to this and its hard to know what to keep and how to write the best way. But anyway if you can help me it would be awesome.
If you have any questions regardning anything or just some tips just comment.
Your table name blob should be surrounded by back-ticks, not apostrophes.
However, I recommend that you change the name of this table to something that is not a reserved word in MySQL.
I am trying to display images from my mysql database using php. The image is not getting displayed fully. It gets cut while trying to display an image more than 200 kb (determined from trials , but not too sure).
HTML Code:
<form enctype="multipart/form-data" action="insertimage.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="10240000" type="hidden">
<input name="image" accept="image/jpeg|image/jpg|image|JPG|image/png|image/gif" type="file">
<input value="Submit" type="submit">
PHP Code:
<?php
require('myconnect.php');
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "Update whyangry.posts set Photo='$data' where Pid=2";
$results = mysql_query($query, $con);
// Print results
print "Thank you, your file has been uploaded.";
$sql = "SELECT * FROM helpme.posts WHERE Pid=2";
$res = mysql_query($sql,$con);
while ($res1=mysql_fetch_assoc($res))
{
$content = $res1['Photo'];
$id=$res1['Pid'];
}
echo '<img src="data:image/png|image/jpeg|image/gif;base64,' . base64_encode( $content ) . '" />';
echo 'Hello world.';
}
else {
print "No image selected/uploaded";
}
?>
Also i am getting the below error while uploading file in phpmyadmin to a blob datatype
UPDATE `helpme`.`posts` SET `Photo` = 0xffd8ffe000104a46494600010201006000600000ffe10f074578696600004d4d002a0000000800060132000200000014000000564746000300000001000300004749000300000001003200009c9d00010000000e00000000ea1c0007000007f40000000087690004000000010000006a000000d4323030393a30333a31322031333a34373a34330000059003000200000014000000ac9004000200000014000000c0929100020000000335340000929200020000000335340000ea1c0007000007b40000000000000000323030383a30333a31342031333a35393a323600323030383a30333a31342031333a35393a3236000005010300030000000100060000011a00050000000100000116011b0005000000010000011e020100040000000100000126020200040000000100000dd90000000000000048000000010000004800000001ffd8ffe000104a46494600010100000100010000ffdb004300100b0c0e0c0a100e0d0e1211101318281a181616183123251d283a333d3c3933383740485c4e404457453738506d51575f626768673e4d71797064785c656763ffdb0043011112121815182f1a1a2f634238426363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363[...]
MySQL said:
2006 - MySQL server has gone away
Please let me know how to fix the issue. The issue is while displaying images. Whether some size issue is there i dont know please help here.
Using addslashes is nowhere near the correct way to do a SQL query. It will not always work correctly with binary data. I don't know what resource you're using, but it's teaching you very bad habits.
Please DO NOT USE mysql_query in new applications. This is a legacy interface from the 1990s that is in the process of being retired because of the hazards involved in using it incorrectly, something all too easy to do. It's best to use either mysqli or PDO in new projects.
Your query should look like this:
Update whyangry.posts set Photo=? where Pid=?
You can bind to those placeholders when executing the query and avoid having encoding problems. There are many examples on how to do this correctly.
Hi I am newish to php and I have created an update page for Content Management System. I have a file upload in this case a picture. I have other inputs that contain text and I can get them to populate my form and thats fine and works great because the user can see what has already been entered. But the file name for the photo can not have a value so if the user doesn't pick the picture from the directory again it will update minus the picture. What I think I need is a isset function that says if the file (picture) input is left blank don't update this field and use whatever what already in the database for it, that way if it was left blank when created it will still be, and if the user has changed it this time it will change; or if they want to leave it the same it won't leave their picture blank. Hope that makes sence.
Here is my coding currently for the Form:
<p>
Photo:
</p>
<input type="hidden" name="MAX_FILE_SIZE" value="350000">
<input type="file" name="photo"/>
Below is my php code for my update if the update button is pressed:
$con = mysql_connect("localhost","******","********");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*******", $con);
// run this only, once the user has hit the "Update" button
if (isset($_POST['update'])) {
// assign form inputs
$name = $_POST['nameMember'];
$position = $_POST['bandMember'];
$pic = $_POST['photo'];
$about = $_POST['aboutMember'];
$bands = $_POST['otherBands'];
// add member to database
$result = mysql_query("UPDATE dbProfile SET nameMember='".$name."',bandMember='".$position."',photo='".$pic."',aboutMember='".$about."',otherBands='".$bands."' WHERE id='".$id."'");
mysql_close($con);
Header("Location: listMember.php");
exit;
}
else { // read member data from database
$result = mysql_query ("SELECT * FROM dbProfile WHERE id='".$id."'");
while($row = mysql_fetch_array($result))
{
$name = $row['nameMember'];
$position = $row['bandMember'];
$pic = $row['photo'];
$about = $row['aboutMember'];
$bands = $row['otherBands'];
}
}
mysql_close($con);
?>
If you could help I would be very please and greatful.
You have to use the $_FILES variable for uploaded files. For further information, see Handling file uploads in the PHP manual.
Try:
if(is_uploaded_file($_FILES['photo']['tmp_name']))
From the manual:
Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.