error upon uploading image no such path or directory - php

Good day, I have been following a tutorial and have worked really hard to make this script work, I have managed to fix many things however the one constant problem I'm getting is:
No such file or directory in /home/xxxxxxx/public_html/regForm.php on line 93
What I am trying to acomplish is get user to upload a profile pic to my live server / website upon registration, here is part of my form and the code below:
I would greatly appreciate it if a more experienced user can give it a scan and advise to where I am going wrong, thanx in advance
HTML FORM
<form ENCTYPE="multipart/form-data" name="registration-form" id="regForm" method="post" action="regForm.php">
:
:
Upload Picture: <INPUT NAME="file_up" TYPE="file">
<input type="submit" value="Register" name="register" class="buttono" />
</form>
UPLOAD SCRIPT
$file_upload="true";
$file_up_size=$_FILES['file_up']['size'];
echo $_FILES['file_up']['name'];
if ($_FILES['file_up']['size']>250000){
$msg=$msg."Your uploaded file size is more than 250KB
so please reduce the file size and then upload.<BR>";
$file_upload="false";
}
if (!($_FILES['file_up']['type'] =="image/jpeg" OR $_FILES['file_up']['type'] =="image/gif"))
{
$msg=$msg."Your uploaded file must be of JPG or GIF. Other file types are not allowed<BR>";
$file_upload="false";
}
$file_name=$_FILES['file_up']['name'];
if($file_upload=="true"){
$ftp_server = "xxxxxx";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$ftp_username='xxxxxx';
$ftp_userpass='xxxxxx';
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
$file = $file_name;
// upload file
if (ftp_put($ftp_conn, "public_html/img/userPics", $file, FTP_ASCII)) //here is the problem with the path I suspect
{
echo "Successfully uploaded $file.";
}
else
{
echo "Error uploading $file.";
}
// close connection
ftp_close($ftp_conn);
}

When dealing with images, you need to use a binary format.
FTP_BINARY instead of FTP_ASCII.
As per the manual:
http://php.net/manual/en/function.ftp-put.php
Make sure the path is correct. This can differ from different servers.
You also need a trailing slash here:
public_html/img/userPics/
^
Otherwise, your system will interpret that as:
userPicsIMAGE.JPG rather than the intended userPics/IMAGE.JPG
Yet, you may need to play around with the path itself. FTP is a bit tricky that way.
I.e.:
/home/xxxxxxx/public_html/userPics/
img/userPics/
../img/userPics/
Depending on the file's area of execution.
Root > ftp_file.php
-img
-userPics
The folder also needs to have proper permissions to be written to.
Usually 755.
Use error reporting if your system isn't already setup to catch and display error/notices:
http://php.net/manual/en/function.error-reporting.php
An example from the FTP manual:
<?php
ftp_chdir($conn, '/www/site/');
ftp_put($conn,'file.html', 'c:/wamp/www/site/file.html', FTP_BINARY );
?>
Another thing though, the use of of "true" and "false". You're most likely wanting to check for truthness
$file_upload=true;
rather than a string literal $file_upload="true";
same thing for
if($file_upload=="true")
to
if($file_upload==true)
and for $file_upload="false"; to check for falseness
to $file_upload=false;
Read the manual on this:
http://php.net/manual/en/language.types.boolean.php
This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Test your FTP connection, pulled from https://stackoverflow.com/a/3729769/
try {
$con = ftp_connect($server);
if (false === $con) {
throw new Exception('Unable to connect');
}
$loggedIn = ftp_login($con, $username, $password);
if (true === $loggedIn) {
echo 'Success!';
} else {
throw new Exception('Unable to log in');
}
print_r(ftp_nlist($con, "."));
ftp_close($con);
} catch (Exception $e) {
echo "Failure: " . $e->getMessage();
}
Naming conventions:
I also need to note that on LINUX, userPics is not the same as userpics, should your folder name be in lowercase letters.
Unlike Windows, which is case-insensitive.

Related

ftp_put(): Opening data channel for file upload to server of "/xxx.txt"

I am working on to upload the file to FTP using PHP FTP. while putting the file to the server, its throw error.
what I did:
$ftp_conn = ftp_connect(SAP_SERVER_HOST, SAP_SERVER_PORT, 60);
if (!ftp_login($ftp_conn, SAP_SERVER_USER, SAP_SERVER_PASSWORD)) {
echo 'not connected<br/>';
} else {
$localfile = '/abc/txt/15375127769260.txt';
$serverfile = '/folder/15375127769260.txt';
// echo ftp_pwd($ftp_conn);
if (ftp_put($ftp_conn, $serverfile, $localfile, FTP_BINARY)) {
echo "Successfully uploaded $localfile.";
} else {
echo "Error uploading $localfile.";
}
// close connection
ftp_close($ftp_conn);
}
Suggest Me, what I miss in this code.
For anyone stumbling upon this:
my file was sent correctly after adding ftp_pasv($conn_id, true);
Note that it must be added after ftp_login().
ftp-pasv on php.net
are you using right folders and ports ?
$ftp_conn = ftp_connect(SAP_SERVER_HOST, SAP_SERVER_PORT, 60);
it should be port 21
and in local file you must get get the realpath of the file whit realpath() function
and for remote server the path is based on ftp base folder
Take a look of realpath http://php.net/manual/pt_BR/function.realpath.php

How to check if files exists on a folder? [duplicate]

How can I check if a specific file exists on a remote server using PHP via FTP connections?
Some suggestions:
Use ftp_size, which returns -1 if it doesn't exist: http://www.php.net/manual/en/function.ftp-size.php
Use fopen, e.g. fopen("ftp://user:password#example.com/somefile.txt", "r")
Use ftp_nlist, check to see if the filename you want is in the list: http://www.php.net/manual/en/function.ftp-nlist.php
I used this, a bit easier:
// the server you wish to connect to - you can also use the server ip ex. 107.23.17.20
$ftp_server = "ftp.example.com";
// set up a connection to the server we chose or die and show an error
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
ftp_login($conn_id,"ftpserver_username","ftpserver_password");
// check if a file exist
$path = "/SERVER_FOLDER/"; //the path where the file is located
$file = "file.html"; //the file you are looking for
$check_file_exist = $path.$file; //combine string for easy use
$contents_on_server = ftp_nlist($conn_id, $path); //Returns an array of filenames from the specified directory on success or FALSE on error.
// Test if file is in the ftp_nlist array
if (in_array($check_file_exist, $contents_on_server))
{
echo "<br>";
echo "I found ".$check_file_exist." in directory : ".$path;
}
else
{
echo "<br>";
echo $check_file_exist." not found in directory : ".$path;
};
// output $contents_on_server, shows all the files it found, helps for debugging, you can use print_r() as well
var_dump($contents_on_server);
// remember to always close your ftp connection
ftp_close($conn_id);
Functions used: (thanks to middaparka)
Login using ftp_connect
Get the remote file list via ftp_nlist
Use in_array to see if the file was present in the array
Just check the size of a file. If the size is -1, it doesn't exist, so:
$file_size = ftp_size($ftp_connection, "example.txt");
if ($file_size != -1) {
echo "File exists";
} else {
echo "File does not exist";
}
If the size is 0, the file does exist, it's just 0 bytes.
Source
A general solution would be to:
Login using ftp_connect
Navigate to the relevant directory via ftp_chdir
Get the remote file list via ftp_nlist or ftp_rawlist
Use in_array to see if the file was present in the array returned by ftp_rawlist
That said, you could potentially simply use file_exists if you have the relevant URL wrappers available. (See the PHP FTP and FTPS protocols and wrappers manual page for more information.)
This is an optimization of #JohanPretorius solution, and an answer for comments about "slow and inefficient for large dirs" of #Andrew and other: if you need more than one "file_exist checking", this function is a optimal solution.
ftp_file_exists() caching last folder
function ftp_file_exists(
$file, // the file that you looking for
$path = "SERVER_FOLDER", // the remote folder where it is
$ftp_server = "ftp.example.com", //Server to connect to
$ftp_user = "ftpserver_username", //Server username
$ftp_pwd = "ftpserver_password", //Server password
$useCache = 1 // ALERT: do not $useCache when changing the remote folder $path.
){
static $cache_ftp_nlist = array();
static $cache_signature = '';
$new_signature = "$ftp_server/$path";
if(!$useCache || $new_signature!=$cache_signature)
{
$useCache = 0;
//$new_signature = $cache_signature;
$cache_signature = $new_signature;
// setup the connection
$conn_id = ftp_connect($ftp_server) or die("Error connecting $ftp_server");
$ftp_login = ftp_login($conn_id, $ftp_user, $ftp_pwd);
$cache_ftp_nlist = ftp_nlist($conn_id, $path);
if ($cache_ftp_nlist===FALSE)die("erro no ftp_nlist");
}
//$check_file_exist = "$path/$file";
$check_file_exist = "$file";
if(in_array($check_file_exist, $cache_ftp_nlist))
{
echo "Found: ".$check_file_exist." in folder: ".$path;
}
else
{
echo "Not Found: ".$check_file_exist." in folder: ".$path;
};
// use for debuging: var_dump($cache_ftp_nlist);
if(!$useCache) ftp_close($conn_id);
} //function end
//Output messages
echo ftp_file_exists("file1-to-find.ext"); // do FTP
echo ftp_file_exists("file2-to-find.ext"); // using cache
echo ftp_file_exists("file3-to-find.ext"); // using cache
echo ftp_file_exists("file-to-find.ext","OTHER_FOLDER"); // do FTP
You can use ftp_nlist to list all the files on the remote server. Then you should search into the result array to check if the file what you was looking for exists.
http://www.php.net/manual/en/function.ftp-nlist.php
The code has been written by: #Drmzindec should be change a little:
if (in_array($check_file_exist, $contents_on_server))
to
if (in_array($file, $contents_on_server))

images are not uploading into FTP files while using PHP cmds

I have tried files upload to server using ftp connection in php and its not working, its connecting and and telling uploaded successfully but no image will be upload in the directories....i have tried following code please help by correcting it
image.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Welcome</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile_1" type="file" /><br />
Choose a file to upload: <input name="uploadedfile_2" type="file" /><br />
<input type="submit" value="Upload Files" />
</form>
</body>
</html>
upload.php
<?php
$ftp_server = "XXXXXX";
$ftp_username = "XXXXX";
$ftp_password = "XXXX";
$conn_id = ftp_connect($ftp_server) or die("could not connect to $ftp_server");
if(#ftp_login($conn_id, $ftp_username, $ftp_password))
{
echo "connected as $ftp_username#$ftp_server\n";
}
else {
echo "could not connect as $ftp_username\n";
}
$file = $_FILES["uploadedfile_1"]["name"];
$file2 = $_FILES["uploadedfile_2"]["name"];
$remote_file_path = "/imagetest/123/".$file;
$remote_file_path2 = "/imagetest/123/".$file2;
ftp_put($conn_id, $remote_file_path, $_FILES["uploadedfile_1"]["tmp_name"],FTP_ASCII);
ftp_put($conn_id, $remote_file_path2, $_FILES["uploadedfile_2"]["tmp_name"],FTP_ASCII);
ftp_close($conn_id);
echo "\n\nconnection closed";
?>
try..
$remote_file_path = "./imagetest/123/".$file;
or simply...
$remote_file_path = "imagetest/123/".$file;
try this...
$uploaddir = "./temp/";
$uploadfile = $uploaddir . basename($_FILES['uploadedfile_1']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['uploadedfile_1']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
First, make sure paths of the files are fine (syntactically and are actually pointing to the file initended) and secondly, the ftp_put function returns a boolean. You could check it's value to see if the upload is happening successfully or not.
I think another problem in this case might also be that the server's firewall is hindering establishing a data channel between the client (i.e you) and the server. Try turning the passive mode on before uploading files. Just add the following line before ftp_put and see if it works:
// turn passive mode on
ftp_pasv($conn_id, true);
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);
You will also have to use Binary mode for images as rightly pointed out.
Relevant documentation. Hope it gets you started in the right direction.
$_FILES["uploadedfile_1"]["tmp_name"] is just a string with temporary file name(such as 'aaaaa.jpg' but not '/tmp/upload/aaa.jpg'). You should use move_uploaded_file to move files uploaded with a form since $_FILES["uploadedfile_1"]["tmp_name"] doesn't contain the actual file path.
http://php.net/manual/en/function.move-uploaded-file.php
Since I haven't experience to move uploaded file directly to another server, here's what will work, I suppose.
1.First move the uploaded file to a local folder.
$localPath = '/xxxx/upload/' //confirm your web server user have the right to write in this folder
$tmp_name = $_FILES["uploadedfile_1"]["tmp_name"] // confirm you got a filename here.
move_uploaded_file($tmp_name, "$localPath/$tmp_name"); // You should have a new file in /xxxx/upload/
in your webserver.
2.Then move the file from local folder to remote server.
ftp_put($conn_id, $remote_file_path, "$localPath/$tmp_name" ,FTP_ASCII);// If this goes wrong, you should test this with a local file created mannually and upload it to your remote server. If it fails, there must be something wrong in your remote connection or permission.
3.Then delete the file in local folder.
unlink("$localPath/$tmp_name");// The file in local host should be deleted.
Please give it a shot.

PHP Upload Script not Functioning Properly with New Host

I have set up a php script which creates a directory and uploads a file to that directory. My issue is that when I use the script to create the directory, the file will not upload entirely. I ran the exact same script on a different host and the upload process works just fine. Plus, if I manually create the upload directory and apply chmod 777 via ftp then the transfer works just fine. Could there be some sort of a setting with the hosting provider that needs to be altered to allow the function to work just right?
Here is the upload form:
<form action="/uploadFile.php" method="post"
enctype="multipart/form-data">
<label for="img_preview">Preview Image:</label>
<input type="file" name="img_preview" id="img_preview" />
<br />
<input type="hidden" name="id" value="newDirectory" />
<input type="submit" name="submit" value="Upload Flyer" />
</form>
Here is my PHP script (uploadFile.php):
$thisdir = getcwd();
$new_dir = $_POST['id'];
$full_dir = $thisdir . "/upload/" . $new_dir;
function chk_dir($full_dir) {
if(is_dir($full_dir)) {
echo 'welcome back';
} else {
return mkdir($full_dir);
}
}
chk_dir($full_dir);
chmod($full_dir, 0777);
?>
<?php
//upload image
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
}
//set image restrictions
?>
<?php
if ((($_FILES["img_preview"]["type"] == "image/gif")
|| ($_FILES["img_preview"]["type"] == "image/jpeg")
|| ($_FILES["img_preview"]["type"] == "image/pjpeg"))
&& ($_FILES["img_preview"]["size"] < 80000))
{
if ($_FILES["img_preview"]["error"] > 0)
{
echo "Please only upload an image for previewing (jpg or gif)...<br>
Also, check to make sure the filesize is less than 8MB" . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
//check the image into new directory
if (file_exists("upload/". $new_dir ."/". $_FILES["img_preview"]["name"]))
{
echo "It seems that " . $_FILES["img_preview"]["name"] . " already exists.";
}
else
{
move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_POST['id'] . "/" . $_FILES["img_preview"]["name"]);
echo "image file has transferred successfully!";
}
}
}
else
{
echo "Invalid file please contact for assistance.";
}
?>
Also, when I run the script no errors are produced and the file echos "image file has transferred successfully!" but then when I check for the file in the new location it is completely void. Thank you for your time in this issue.
First of all, your script has a security hole. Never use passed $_POST data to create system directories. And never use 0777 for anything.
The move_uploaded_file() returns false on a failure and you would still get your success message even if it failed (in your code)
Turn on display_errors and error logging and try again.
Looks like your question already contains the answer(the upload works when you create the directory via FTP).
I guess the new server has safe_mode enabled, so it will check the UID of the fileowners on file-operations.
What happens:
your script creates a directory, owner will be the webserver
your script(owner of the script usually is the ftp-user) tries to chmod the directory
the script(owner:ftp) cannot chmod the directory(owner:webserver) , because the UIDs are different.
solution: use ftp_mkdir() for creation of directories.
you have used move_uploaded_file() independently. If it returns false then also sucsess message will be printed.
Try
if ( move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_POST['id'] . "/" . $_FILES["img_preview"]["name"])) {
echo "sucess";
}else{
echo "fail";
}
After that you will get what is the main problem. Also use debugging point by
print_r($_FILES) before move_uploaded_file().
This may not be the answer to your question, but still it's worth your attention, I hope. Don't rely on the type of the file sent via $_FILES, this is just the mime-type sent by the browser as far as I remember, it can be easily compromized. Use getimagesize() function to get true image type as well as height/width.
Same goes for the source file name, but that shouldn't pose a security hole.

How can I check if a file exists on a remote server using PHP?

How can I check if a specific file exists on a remote server using PHP via FTP connections?
Some suggestions:
Use ftp_size, which returns -1 if it doesn't exist: http://www.php.net/manual/en/function.ftp-size.php
Use fopen, e.g. fopen("ftp://user:password#example.com/somefile.txt", "r")
Use ftp_nlist, check to see if the filename you want is in the list: http://www.php.net/manual/en/function.ftp-nlist.php
I used this, a bit easier:
// the server you wish to connect to - you can also use the server ip ex. 107.23.17.20
$ftp_server = "ftp.example.com";
// set up a connection to the server we chose or die and show an error
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
ftp_login($conn_id,"ftpserver_username","ftpserver_password");
// check if a file exist
$path = "/SERVER_FOLDER/"; //the path where the file is located
$file = "file.html"; //the file you are looking for
$check_file_exist = $path.$file; //combine string for easy use
$contents_on_server = ftp_nlist($conn_id, $path); //Returns an array of filenames from the specified directory on success or FALSE on error.
// Test if file is in the ftp_nlist array
if (in_array($check_file_exist, $contents_on_server))
{
echo "<br>";
echo "I found ".$check_file_exist." in directory : ".$path;
}
else
{
echo "<br>";
echo $check_file_exist." not found in directory : ".$path;
};
// output $contents_on_server, shows all the files it found, helps for debugging, you can use print_r() as well
var_dump($contents_on_server);
// remember to always close your ftp connection
ftp_close($conn_id);
Functions used: (thanks to middaparka)
Login using ftp_connect
Get the remote file list via ftp_nlist
Use in_array to see if the file was present in the array
Just check the size of a file. If the size is -1, it doesn't exist, so:
$file_size = ftp_size($ftp_connection, "example.txt");
if ($file_size != -1) {
echo "File exists";
} else {
echo "File does not exist";
}
If the size is 0, the file does exist, it's just 0 bytes.
Source
A general solution would be to:
Login using ftp_connect
Navigate to the relevant directory via ftp_chdir
Get the remote file list via ftp_nlist or ftp_rawlist
Use in_array to see if the file was present in the array returned by ftp_rawlist
That said, you could potentially simply use file_exists if you have the relevant URL wrappers available. (See the PHP FTP and FTPS protocols and wrappers manual page for more information.)
This is an optimization of #JohanPretorius solution, and an answer for comments about "slow and inefficient for large dirs" of #Andrew and other: if you need more than one "file_exist checking", this function is a optimal solution.
ftp_file_exists() caching last folder
function ftp_file_exists(
$file, // the file that you looking for
$path = "SERVER_FOLDER", // the remote folder where it is
$ftp_server = "ftp.example.com", //Server to connect to
$ftp_user = "ftpserver_username", //Server username
$ftp_pwd = "ftpserver_password", //Server password
$useCache = 1 // ALERT: do not $useCache when changing the remote folder $path.
){
static $cache_ftp_nlist = array();
static $cache_signature = '';
$new_signature = "$ftp_server/$path";
if(!$useCache || $new_signature!=$cache_signature)
{
$useCache = 0;
//$new_signature = $cache_signature;
$cache_signature = $new_signature;
// setup the connection
$conn_id = ftp_connect($ftp_server) or die("Error connecting $ftp_server");
$ftp_login = ftp_login($conn_id, $ftp_user, $ftp_pwd);
$cache_ftp_nlist = ftp_nlist($conn_id, $path);
if ($cache_ftp_nlist===FALSE)die("erro no ftp_nlist");
}
//$check_file_exist = "$path/$file";
$check_file_exist = "$file";
if(in_array($check_file_exist, $cache_ftp_nlist))
{
echo "Found: ".$check_file_exist." in folder: ".$path;
}
else
{
echo "Not Found: ".$check_file_exist." in folder: ".$path;
};
// use for debuging: var_dump($cache_ftp_nlist);
if(!$useCache) ftp_close($conn_id);
} //function end
//Output messages
echo ftp_file_exists("file1-to-find.ext"); // do FTP
echo ftp_file_exists("file2-to-find.ext"); // using cache
echo ftp_file_exists("file3-to-find.ext"); // using cache
echo ftp_file_exists("file-to-find.ext","OTHER_FOLDER"); // do FTP
You can use ftp_nlist to list all the files on the remote server. Then you should search into the result array to check if the file what you was looking for exists.
http://www.php.net/manual/en/function.ftp-nlist.php
The code has been written by: #Drmzindec should be change a little:
if (in_array($check_file_exist, $contents_on_server))
to
if (in_array($file, $contents_on_server))

Categories