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
Related
i'm currently working on a small script for my Homepage but i ran into a problem.
I Try to upload an Image, but it seems like the POST data from the form is not being received. What did i do wrong?
I already changed the post_max_size and everything in the php.ini.
These are the Errors i get:
"Notice: Undefined index: image in ...." & "Notice: Undefined index:
submit in ...."
<form method="POST" action="/eye/sites/handling/post.php" enctype="multipart/form-data">
<div class="fileUpload">
<span><i class="fa fa-folder-o" aria-hidden="true"></i> Bild wählen</span>
<input type="file" class="upload" name="image"/>
</div>
<input type="submit" value="Upload It!" name="submit"/>
</form>
<?php session_start();
error_reporting(E_ALL);
if (isset($_SESSION["login_stat"])) {
date_default_timezone_set('Europe/Berlin');
$config = "$_SERVER[DOCUMENT_ROOT]/eye/more/config.xml";
$xml = simplexml_load_file($config);
$picWidth = $xml->pic->width;
$picHeight = $xml->pic->height;
$fulldate = date('dmYHis');
if(isset($_POST["submit"])) {
if (file_exists($_FILES['image']['tmp_name']) || is_uploaded_file($_FILES['image']['tmp_name'])) {
$typeCheck = $_FILES['image']['type'];
if ($typeCheck != "image/jpeg") {
$error = "Not a .jpg";
header('location: /eye/sites/post.php?stat=bad&error='.$error);
exit;
}
$file = $_SERVER['DOCUMENT_ROOT']."/uploads/".$fulldate.".jpg";
$type = "image/jpeg";
move_uploaded_file($_FILES['image']['tmp_name'], $file);
$file_thmb = $_SERVER['DOCUMENT_ROOT']."/uploads/!1A_thmb/".$fulldate.".jpg";
include "resize-class.php";
$resizeObj = new resize($file);
$resizeObj->resizeImage($picWidth, $picHeight, 'crop');
$resizeObj->saveImage($file_thmb, 100);
// header('location: /eye/sites/post.php?stat=good');
} else{
// header('location: /eye/sites/post.php?stat=bad&error=No File');
}
} else{
// header('location: /eye/sites/post.php?stat=bad&error=No Data');
echo $_SERVER['CONTENT_TYPE'];
echo "<br>";
echo $_FILES['image']['tmp_name'];
echo "<br>";
echo $_POST['submit'];
echo "<br>";
}
} else {
header('location: /eye/index.php?stat=in');
}
?>
Edit:
The problem is definitely about my Localhost.
This whole thing is working fine on my Webspace, but on my localhost it's not working.
BUT: I'm not getting errors anymore, when is click on Submit it goes to the php file that should save the image, but nothing is happening. I just see a white Page.
But like i said, it runs perfectly on my webspace..
If this is running on your local machine, do a quick check to make sure your "php.ini" file is configured to allow file uploads.
php.ini
file_uploads = On
The codes look fine. Check if your form action is posting to the correct path and if I may suggest using a simpler approach to test your file upload function before making it more complex. Use the following to start testing.
if (isset($_POST["submit"])) {
if (file_exists($_FILES['image']['tmp_name']) || is_uploaded_file($_FILES['image']['tmp_name'])) {
echo "Upload is working!";
}
}
Keep us updated on your findings.
Perhaps this general information will help someone, as it helped me: a submitted form will only include fields that have defined 'name' attributes. 'id' is not enough.
The idea is that 'id' identifies an element in the DOM for use by JavaScript (either as a global variable or for use in document.getElementById(ID)), but 'name' identifies those elements whose names and values will be sent to the destination ('action') page.
So it makes sense that there are two different identifying attributes, used in two different ways.
I am using a PHP form POST which puts data (into a Text file) into my SQL database and then the codes create a unique download link to be able to download the Text file from the SQL database. The connection to the SQL database works perfectly.
But all I`m getting is "We couldn't find the file to download."
The Form (index.php) whereby I input the data to be input into the Text File
<form action="index2.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
Index2.php (This creates the Text File and inserts the details from the Form. It also creates the unique download link to download the file.)
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
}
else {
die('no post data to process');
}
?>
<?php
//connect to the DB
$resDB = mysql_connect("xxx", "xxx", "xxx");
mysql_select_db("xxx", $resDB);
function createKey(){
//create a random key
$strKey = md5(microtime());
//check to make sure this key isnt already in use
$resCheck = mysql_query("SELECT count(*) FROM downloads WHERE downloadkey = '{$strKey}' LIMIT 1");
$arrCheck = mysql_fetch_assoc($resCheck);
if($arrCheck['count(*)']){
//key already in use
return createKey();
}else{
//key is OK
return $strKey;
}
}
//get a unique download key
$strKey = createKey();
//insert the download record into the database
mysql_query("INSERT INTO downloads (downloadkey, file, expires) VALUES ('{$strKey}', '{$ret}', '".(time()+(60*60*24*7))."')");
?>
<html>
<head>
<title>One Time Download Example</title>
</head>
<h1>One Time Download Example</h1>
<p>Your unique download URL is:</p>
<strong>download.php?key=<?=$strKey;?></strong>
<p>This link will allow you to download the source code a single time within the next 7 days.</p>
</html>
Finally, download.php that checks everything and downloads the Text File from the database.
<?php
//The directory where the download files are kept - keep outside of the web document root
$strDownloadFolder = "/downloads/";
//If you can download a file more than once
$boolAllowMultipleDownload = 0;
//connect to the DB
$resDB = mysql_connect("xxx", "xxx", "xxx");
mysql_select_db("xxx", $resDB);
if(!empty($_GET['key'])){
//check the DB for the key
$resCheck = mysql_query("SELECT * FROM downloads WHERE downloadkey = '".mysql_real_escape_string($_GET['key'])."' LIMIT 1");
$arrCheck = mysql_fetch_assoc($resCheck);
if(!empty($arrCheck['file'])){
//check that the download time hasnt expired
if($arrCheck['expires']>=time()){
if(!$arrCheck['downloads'] OR $boolAllowMultipleDownload){
//everything is hunky dory - check the file exists and then let the user download it
$strDownload = $strDownloadFolder.$arrCheck['file'];
if(file_exists($strDownload)){
//get the file content
$strFile = file_get_contents($strDownload);
//set the headers to force a download
header("Content-type: application/force-download");
header("Content-Disposition: attachment; filename=\"".str_replace(" ", "_", $arrCheck['file'])."\"");
//echo the file to the user
echo $strFile;
//update the DB to say this file has been downloaded
mysql_query("UPDATE downloads SET downloads = downloads + 1 WHERE downloadkey = '".mysql_real_escape_string($_GET['key'])."' LIMIT 1");
exit;
}else{
echo "We couldn't find the file to download.";
}
}else{
//this file has already been downloaded and multiple downloads are not allowed
echo "This file has already been downloaded.";
}
}else{
//this download has passed its expiry date
echo "This download has expired.";
}
}else{
//the download key given didnt match anything in the DB
echo "No file was found to download.";
}
}else{
//No download key wa provided to this script
echo "No download key was provided. Please return to the previous page and try again.";
}
?>
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.
I made a separate page (following this guide) so he can upload pdf files (certificates of their products). And another page to the customer's search according to the selected product.
On the file upload page, the logic is as follows:
In a form:
Select the product (from a selector), and then select the certificate (pdf) to upload.
Submit button stored in a table (created by me) the product ID and the certificate name and attribute (soon to be able to do the search.)
In the database the data is saved correctly, but in the ftp folder files are not saved.
Here I show you my code in /themes/ theme /certificados.tpl
Form:
<form method="post" action="subirconnect.php" enctype="multipart/form-data">
<select id="producto" name="producto">
<option value="default" selected>Producto</option>
...
</select>
<select id="attr" name="attr">
<option value="default" selected>Diametro</option>
...
</select>
<input type="file" name="adjunto[]" multiple="multiple">
<input type="submit" value="Subir" name="enviar_certificados" class="btn btn-primary">
</form>
Validate form:
$TamanioMaximo=5000000; // 1000000 ~~~ 1mb
$CarpetaAlojamiento='../../certificados'; // path public_html/certificados
$NombreArchivoFinal="";
$MensajeCertificados="";
if(!empty($_POST['enviar_certificados'])) {
$name_producto = $_POST['producto'];
$name_combinacion = $_POST['attr'];
$name_certificados = $_FILES['adjunto']['name'];
$cntFiles = count($name_certificados);
for ($i=0; $i< $cntFiles; $i++) { //for multiples files
if($_FILES['adjunto']['size'][$i]>$TamanioMaximo) {
$MensajeCertificados= 'El archivo debe pesar menos de 5mb';
} else {
if (!is_dir($CarpetaAlojamiento)) {
mkdir($CarpetaAlojamiento);
chmod($CarpetaAlojamiento, 0777);
}
$NombreArchivoFinal=$CarpetaAlojamiento."/".$_FILES['adjunto']['name'][$i];
if(substr($_FILES['adjunto']['type'][$i],12,3) != 'pdf') {
$MensajeCertificados= 'Solo se permiten archivos .PDF';
} else if (is_uploaded_file($_FILES['adjunto']['tmp_name'][$i])) {
move_uploaded_file($_FILES['adjunto']['tmp_name'][$i], $NombreArchivoFinal);
$name_certificados = $_FILES['adjunto']['name'][$i];
/* upload data to db - works fine*/
SubirCertificados($cntFiles, $name_producto, $name_combinacion, $name_certificados);
$MensajeCertificados = '¡Certificado Subido!';
} else {
$MensajeCertificados= 'Problemas en el envío '.$_FILES['adjunto']['name'][$i];
}
}
}
}
The folder 'certificados' is already created and has the necessary permissions (777)
You may be missing? move_uploaded_file not working in prestashop?
This same code works fine on my localhost (WAMP)
Dont use static paths rather make folder in prestashop-root/upload/certificados
$CarpetaAlojamiento = _PS_UPLOAD_DIR_.'certificados';
I am trying to create a folder with the name as the persons username when they register on a php form but it creates a folder called $username.
The form im using the now is just a small version of the form i will be using to try and get it working.
Hope someone can help me?
<body>
<form action="index.php" method="post">
enter name<input type="text" name="user">
<p>
<input type="submit" name="submit" value="Upload">
</form>
</body>
<?php
if(isset($_POST['submit']))
{
include("connect.php");
$username = $_POST['user'];
//Get current working directory
$curdir = getcwd();
include("create_folder.php");
mysql_close($con);
}
?>
<!--create folder.php-->
<?php
//Name directory after username
$uploads_dir = '/$username';
//make directory writable from everyone
if(mkdir($curdir . $uploads_dir , 0777)){
echo "$uploads_dir was made";
echo "<br>";
}else{
echo "Failed to create directory";
}
?>
Variables do not get parsed inside single quotes.
$uploads_dir = '/$username';
I needs to read as:
$uploads_dir = "/$username";
However, if it gives you trouble, you may need to add the full system path:
I.e.:
$uploads_dir = "/var/users/public_html/members/$username";
Sidenote: /var/users/public_html/members is only an example. You will need to fill the actuals.
Another sidenote: Using 0777 is not recommended and is best to use 0755.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.