Send image to php script using Form - php

hi i want to save image to mysql using php script and form html but in this code i see that the image is not sent to php can you help me please i am beginer in php.
Form.html
<form action="upload_image.php" method="post" enctype="multipart/form-data">
<p>
<input type="file" name="photo" />
<input type="submit" value="Submit" name="submit"/>
</p>
</form>
<b>
Afficher la premiere image de la base de donnes
</b>
php script :
<?php
echo ini_get( 'file_uploads' );
if($_SERVER['REQUEST_METHOD']=='POST'){
$con = mysqli_connect("localhost","root","","othmane");
if ($con->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$img = $_POST['photo'];
if($img!=null){
$sql = "INSERT INTO images (image) VALUES (?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"s",$img);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check == 1){
echo "Image Uploaded Successfully";
}else{
echo "Error Uploading Image";
}
}else{
echo "image not found";
}
mysqli_close($con);
}else{
echo "Error";
}
?>
Why is the image not sent to script ? i got always image not found in php.

The right way to access to file element by POST method is not $img = $_POST['photo']. You should use $_FILE var, for example $img = $_FILE['photo']['name'] to get the name of file.
There are some different info you can get from $_FILE var:
$_FILES['photo']['name']
The original name of the file on the client machine.
$_FILES['photo']['type']
The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['photo']['size']
The size, in bytes, of the uploaded file.
$_FILES['photo']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['photo']['error']
The error code associated with this file upload.
Look here: http://php.net/manual/en/features.file-upload.post-method.php
Pay attention: If you need to store the image in DB you need to convert file in binary data and store in DB as BLOB type.
Look here: http://dev.mysql.com/doc/refman/5.0/en/blob.html
As alternative, a good way is to store the file in a folder on your host and save the path in a DB.

Related

Upload file to remote FTP server errors

Lately, I have been working on an upload form. The idea is that users can upload their files to a remote FTP server. However, it does not work as expected.
Before I even start uploading the file, I get the following error: "Cannot move uploaded file to working directory". Again, I have not yet started uploading a file.
Here is my PHP code:
<?php
//FTP variabelen met de values
$host = "radioprogrammabank.nl";
$user = "***";
$pass = "***";
//location I want to send the uploaded file to (it is remote)
$destDir = "/domains/radioprogrammabank.nl/public_html/wp/wp-content/uploads";
$dehost = $_POST[$host];
$deuser = $_POST[$user];
$depass = $_POST[$pass];
$dedestDir = $_POST[$destDir];
$workDir = "\Users\stagiaire01\Uploads"; // definieer het lokale systeem
// get temporary file name for the uploaded file
$tmpName = basename($_FILES['file']['tmp_name']);
// copy uploaded file into the current directory
move_uploaded_file($_FILES['file']['tmp_name'], $workDir."/".$tmpName) or die('Cannot move uploaded file to working directory');
// maak connectie, als het niet werkt. Die en geef een melding
$conn = ftp_connect($host) or die ("Cannot initiate connection to host");
// send access parameters
ftp_login($conn, $user, $pass) or die("Cannot login");
// Voer de file upload uit
$upload = ftp_put($conn, $destDir."/".$_FILES['file']['name'], $workDir."/".$tmpName, FTP_BINARY);
// check upload status
// display message
if (!$upload) {
echo "Upload mislukt";
} else {
echo "Upload geslaagd";
}
// sluit de FTP connectie
ftp_close($conn);
// verwijder de lokale kopie van het bestand
unlink($workDir."/".$tmpName) or die("Cannot delete uploaded file from working directory -- manual deletion recommended");
?>
My HTML code:
<html>
<body>
<h2>U kunt hier uw album uploaden</h2>
<form enctype="multipart/form-data" method="post" action="upload.php">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000" />
File <br />
<input type="file" name="file" /><p />
<input type="submit" name="submit" value="Upload Album" />
</form>
</body>
[xyz-ips snippet="verbindftp"]
</html>
You may wonder why I have a shortcode in my HTML. The code is written in Wordpress. I use a plugin in which I can write PHP. The code works when writing this shortcode.
I have also tried doing a var_dump of $_FILES which tells me the following:
"array(0) { } Upload misluktCannot delete uploaded file from working directory -- manual deletion recommended"
I do not know why I get this message when doing a var_dump. I have set my host, username, password, and direction in my values above. The password and username are not shown because of security reasons.
I could not find any answers to this question on StackOverflow. However, I do hope I provided you with enough information to help me out. I expect to be able to upload a file to a remote FTP server.
Greetings,
Parsa_237
You need to check if an upload is occurring, otherwise, it will try to connect to the FTP server when the page is loaded, even if the user hasn't started uploading yet.
e.g.
if ( empty( $_FILES['file'] ) ) {
return;
}
As a side note, I notice you're using the PHP Snippets plugin, this plugin and others like it are incredibly dangerous. Instead, use add_shortcode in a PHP file to embed snippets of PHP inside of pages.
This is why you get this problem, the original tutorial assumed you would put the PHP code in a PHP file named upload.php, so it would only run when the form got submitted. But that's not the case with this plugin

base64 image upload validation

I'm making a feature on my website that a user uploads an image either by loading it from file or by using their computer's built-in webcam.
I take a picture with either my webcam or I load it from file
I store the base64 in an input which is submitted to the server along with other information.
The server validates the base64 (looks for hacks)
The image is stored on the server
I understand the validation method I used:
Takes a lot of processing speed on the server (encoding and decoding)
Has bugs / not reliable
Is probably not secure enough
Is there any more secure, "server-friendly", and reliable way of validating the base64??
(I couldn't find any promising methods in other posts.)
It fails when I face the camera at certain places (somehow the base64 is affected by certain pictures)
Thanks so much for any help!
-- dragonfire
upload.php script:
<?php
$uploaded_file_b64 = htmlspecialchars($_POST['b64_img_url']); // string containing base64 of uploaded image
$FileName = "the_unique_uploaded_file_name.png";
$file_path = "/uploads/" . $FileName;
$file_relative_path = "../uploads/" . $FileName; // BUG: need to use relative path rather than absolute since absolute path doesn't work. Why???
//Must get actual base64 out of string by splicing it
$uploaded_file_actual_b64 = explode("base64,",$uploaded_file_b64);
//We need to get the second value from the array returned from explode() since there are two commas before the actual base64
$uploaded_file_actual_b64 = $uploaded_file_actual_b64[1];
// First try to decode then re-encode the base64. If works then perfect!
if ($uploaded_file_actual_b64 == base64_encode(base64_decode($uploaded_file_actual_b64))) {
// It worked!
echo "Valid base64!";
}
else {
// It failed! THIS IS WHERE IT ALWAYS ERRORS!! WHY???
echo "Not base64!";
}
// Try creating an image from the base64. If works then perfect!
$is_image = imagecreatefromstring(base64_decode($uploaded_file_actual_b64));
//doing this will help confirm it's an image, but it is still possible to inject php or js into
//the body of the image, but as long as we don't execute the image on the server
//then we should be fine
if ($is_image != false) {
echo "Valid image!";
} else {
echo "Not an image!";
}
// If we get up to here, then nothing has been tampered with!
echo "Secure!";
// Store the image on the server
if (file_put_contents($file_relative_path, base64_decode($uploaded_file_actual_b64))) {
echo "Upload success!";
} else {
echo "Upload failed!";
}
?>
Client side code:
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="text" id="b64_img_url" name="b64_img_url" style="display: none;"/>
<input type="submit" class="btn btn-success" value="Submit" />
<div id="btn_cam_capture" onclick="capture_webcam();">Capture</div>
<canvas id="camera-stream-canvas"></canvas>
<img id="img-drop-preview"/>
<script>
var canvas = document.getElementById("camera-stream-canvas");
function capture_webcam() {
// Executed when user takes shot.
// Previews the image by converting the canvas to a base64 image.
document.getElementById("img-drop-preview").src = canvas.toDataURL();
// The input which stores the base64
document.getElementById("b64_img_url").value = canvas.toDataURL();
}
</script>
</form>

"Undefined index" when trying uploading file using PHP

This is suppose to be pretty straight forward and is driving me mad!
I'm trying to upload a file in PHP and writing the file to MySQL as a blob.
Problem is that the site throws a "Undefined index" all the time when I'm trying to use the
$_FILES['file']['tmp_name'] property.
Here is my code :
<head>
<title>Upload Worksheet</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000" />
File :
<input type="file" name"file" id="file"><input type="submit" value="Upload">
</form>
<?php
//connect to db
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("autoedi") or die(mysql_error());
//file properties
$file = $_FILES['file']['tmp_name'];
if(!isset($file))
echo "Please choose a file.";
else {
$uploadfile = addslashes(file_get_contents( $_FILES['file']['name']));
$uploadfilename = addslashes($_FILES['file']['tmp_name']);
}
?>
</body>
This is what the error message looks like :
I haven't even gotten to the database side, as I can't get past this stage.
I'm a PHP noob, so any help would be greatly appreciated!
You recieve that error message because the form is not sent, yet. When you hit the upload button, the form is sent to your server and PHP populates the $_POST and $_FILES array with data. However, the arrays are empty until that point. It is therefore good practice to check whether or not your data is set, like so:
if (isset ($_POST['upload']))
{
// upload logic here
if(!isset($_FILES['file']) || ($_FILES['file']['tmp_name'] == ''))
echo "Please choose a file.";
else {
$uploadfile = addslashes(file_get_contents( $_FILES['file']['name']));
$uploadfilename = addslashes($_FILES['file']['tmp_name']);
}
}
This assumes you have a submit button named "upload".
The Above answer is perfect because you should check the for post values in order to run any code on those values but you can also try the following
<?php
//connect to db
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("autoedi") or die(mysql_error());
//file properties
if(isset($_POST))
{
if(array_key_exists('file',$_FILES))
{
$file = $_FILES['file']['tmp_name'];
if(!isset($file))
echo "Please choose a file.";
else {
$uploadfile = addslashes(file_get_contents( $_FILES['file']['name']));
$uploadfilename = addslashes($_FILES['file']['tmp_name']);
}
}
?>

Why do I get this error when trying to upload an image?

When I go to myserver index and upload and image from there using the interface, it works fine. But as soon as I try to enter the path myself, like:
http://myserver/upload.php?image['name']=F:\Bilder\6.jpg
it gives me an error that all fields are required. But I have to upload images like this, because I plan to implement it in an app that I'm making. Thing is, that I'm not that well acquainted with php.
here is the upload.php
<?php
session_start();
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/";
$image = $_FILES['image'];
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: index.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: index.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: index.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Avatar (filename) values ('" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
exit;
}
else
{
header("Location: index.php");
exit;
}
?>
and the index.php
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>
<label>Avatar</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="submit" id="submit" value="Upload" />
</p>
the problem lies in
if ( $image['name'] == "" )
$image has no value there.
You are doing a get request so if you would like to know what the image variable is you should use
$_GET['image']
Another thing is that you are doing $image = $_FILES['image'];
$_FILES will only be available from a post request.
Uploading files can not be done in the way you are doing now by a parameter from a GET request.
If you need to POST stuff to a web form (as opposed to GETting, which is what you're doing here), you can't just specify the data to be POSTed as part of the URL.
Have a look at those HTTP methods (GET and POST) to understand the difference.
In your app, what you need to do is POST stuff to the URL. Depending on which tools you use to program, you should look into how to send data via POST.
Also, try to see if an implementation of curl (or libcurl) is available to your development platform.
That simply wont work since you cannot upload an image by sending $_GET[] variables through the url.
As you can see in the upload.php page you got, the file is retrieved in the php page through a $_FILES['image'].
If you change that to $_GET['image'] and retry to post the link with the get variable you suggest, you probably will be able to see the path to your file but it will only be as a string type and not an actual uploaded file object.

How to check if image was submitted with other form data

I have an user registration form and uploading image with other form elements is optional there. So sometimes users may not upload image along with other data.
Now the problem is even though the user has not uploaded image, the following code always echos that the file was uploaded
Could you please kindly tell me how to check if the image was submitted by the user and make it echo/display "not uploaded" if not uploaded ?
Thanks in Advance :)
In my Controller File
extract($_POST); // <<This is to retrieve all form data at once
if(isset($_FILES['userfile'])){
echo"file uploaded";
} else{
echo "Not Uploaded";
}
This is in my View File
<input type="file" class="" name="userfile" size="20" />
Per PHP documentation:
If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.
source: http://www.php.net/manual/en/features.file-upload.post-method.php
So your conditional can change to:
if(isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0){
echo"file uploaded";
} else echo "Not Uploaded" ;
You can combine both checks:
if (count($_POST) and !empty($_FILES['userfile'])) {
// uploaded
}
else {
// either is missing
}
Note that you should not use extract($_POST);. You can't control which local variables get overwritten from the outside with that. (If nothing else investigate EXTR_PREFIX.)

Categories