I read a lot of threads here about move_uploaded_file() here, but I cannot find the answer. Im trying code from this website - https://www.simplilearn.com/tutorials/php-tutorial/image-upload-in-php but it doesnt work.
I have 3 files:
dbConfig.php
<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "****";
$dbPassword = "****";
$dbName = "image_test";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
main.php
<!DOCTYPE HTML>
<html>
<head>
<title>#tyvlasystudio</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="description" content=""/>
<meta name="keywords" content=""/>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select Image File to Upload:
<input type="file" name="file">
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
upload.php
<?php
// Include the database configuration file
include 'dbConfig.php';
$statusMsg = '';
echo $_FILES;
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
echo $targetDir ."<br>";
echo $fileName ."<br>";
echo $targetFilePath ."<br>";
echo $fileType ."<br>";
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
// Insert image file name into database
$insert = $db->query("INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
if($insert){
$statusMsg = "The file ".$fileName. " has been uploaded successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
// Display status message
echo $statusMsg;
?>
But it doesnt worked.
Here is result:
I dont know what is bad in this code. Thanks for your advice
Edit 16.2.2023 - 23:00
I figured it out, that problem maybe will be in POST metod. Ive tried now easy code with two files:
main1.php
<html>
<body>
<form method="post" action="main2.php">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</body>
</html>
main2.php
<?php
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
?>
But only with GET method I'll get right answer.
this works for me. please add required attribute to input
<input type="file" name="file" required>
and replace echo $_FILES; //get notice error to echo '<pre>'.print_r($_FILES, true).'</pre>';
result:
Array
(
[file] => Array
(
[name] => 314370969_1174754369788841_1709138246209437707_n.jpg
[type] => image/jpeg
[tmp_name] => C:\xampp_new\tmp\php6BBB.tmp
[error] => 0
[size] => 275646
)
)
uploads/
314370969_1174754369788841_1709138246209437707_n.jpg
uploads/314370969_1174754369788841_1709138246209437707_n.jpg
jpg
The file 314370969_1174754369788841_1709138246209437707_n.jpg has been uploaded successfully.
and pleease check the post_max_size and upload_max_filesize value in php.ini because the defult value is 2MB
If you're having trouble uploading photos via PHP's move_uploaded_file function, there are a few potential causes to check for:
Permissions: Check that the directory where you're trying to move the uploaded file to has the correct permissions. It should be writable by the user that PHP is running as (usually the web server user).
File size limits: PHP has several settings that can limit the size of uploaded files. Check the upload_max_filesize and post_max_size settings in your php.ini file and adjust them as needed.
Form enctype: Make sure that the form that's being used to upload the file has the enctype attribute set to "multipart/form-data". Without this, the file data won't be properly encoded and won't be able to be uploaded.
File name: Make sure that the file name doesn't contain any invalid characters (such as slashes) that could interfere with the file path when trying to move it. You can use PHP's basename function to extract just the filename part of the path.
Destination path: Check that the destination path you're trying to move the file to is correct and exists. You can use PHP's is_dir function to check if the directory exists and mkdir to create it if it doesn't.
Error messages: Check for any error messages that may be generated during the upload process. You can use PHP's $_FILES['file']['error'] variable to check for errors. Possible error codes include UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, and UPLOAD_ERR_EXTENSION.
By checking these potential causes and making any necessary adjustments, you should be able to resolve the issue and successfully upload your photos via PHP's move_uploaded_file function.
Related
I need to get this script to check if the uploaded file is a video file or not and whether the file size is too big or not over the limit. Therefore, need to replace the getimagesize with something else that gets the video file size. How can I accomplish this? Which function to use here? getvideosize function does not exist.
This is where I am stuck.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications/";
//Make Directory under $user in 'uploads/videos/id_verifications'
Folder.
if(!is_dir($directory_path . $user)) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir($directory_path . $user, "$mode", TRUE); //IS THIS LINE
CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
$file = $_FILES["id_verification_video_file"]["name"];
// in PHP 4, we can do:
$fhandle = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($fhandle,$file); // e.g. gives "video/mp4"
// in PHP 5, we can do:
$file_info = new finfo(FILEINFO_MIME); // object oriented approach!
$mime_type = $file_info->buffer(file_get_contents($file)); // e.g. gives
"video/mp4"
switch($mime_type) {
case "video/mp4":
// my actions go here...
}
// Let's assume that the name attribute of the file input field I have
used is "id_verification_video_file"
$tempFile = $_FILES['id_verification_video_file']['tmp_name']; // path of
the temp file created by PHP during upload. I MOST LIKELY GOT THIS LINE
WRONG AT THE END PART. HOW TO CORRECT THIS ?
$videoinfo_array = getimagesize($tempFile); // returns a false if not a
valid image file
if ($videoinfo_array !== false) {
$mime_type = $videoinfo_array['mime'];
switch($mime_type) {
case "video/mp4":
// your actions go here...
move_uploaded_file("$file_tmp", "$directory_path" . "$user/" .
"$file_name"); //IS THIS LINE CORRECT ?
//Notify user their Id Verification Video File was uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded successfully!";
exit();
}
}
else {
echo "This is not a valid video file";
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3></p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
Best I done so far is above. I'd appreciate if you guys can add the correct lines where they should be and add comments so I can easily spot your changes and learn from the corrections.
EDIT:
Folks, I managed to fix a lot of things on my current update. But, one new problem. The move_uploaded_file() is failing. Why is that ? Do have a look. I actually wrote my questions to you in my code's comments in CAPITAL. If you could kindly answer these questions then I'd be grateful and hopefully we could close this thread as SOLVED asap.
<?php
//Required PHP Files.
include 'header_account.php'; //Required on all webpages of the Site.
?>
<?php
if (!$conn)
{
$error = mysqli_connect_error();
$errno = mysqli_connect_errno();
print "$errno: $error\n";
exit();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications";
//Make Directory under $user in
'uploads/videos/id_verifications' Folder if it doesn't exist.
if(!is_dir("$directory_path/$user")) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir("$directory_path/$user", $mode, TRUE); //IS THIS
LINE CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]
["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
echo "File Type: $file_type<br>"; //Outputs: "". WHY $file_type SHOWS
BLANK VALUE WHEN UPLOADING VIDEO FILES ? WORKS WITH OTHER FILES, LIKE
JPEG.
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
echo "File Name: $file_name<br>"; //Outputs: "id_check.mp4"
//Grab Uploading File Extension details.
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
echo "File Extension: $file_extension<br>"; //Outputs: "mp4"
if(file_exists($directory_path . "$user/" . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE NEXT ONE ?
//if(file_exists($directory_path . $user . '/' . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE PREVIOUS ONE ?
{
$Errors[] = "Error: You have already uploaded a video
file to verify your ID!";
exit();
}
else
{
//Feed allowed File Extensions List.
$allowed_file_extensions = array("video/mp4");
//Feed allowed File Size.
$max_file_size_allowed_in_bytes = 1024*1024*1; //Allowed
limit: 100MB.
$max_file_size_allowed_in_kilobytes = 1024*1;
$max_file_size_allowed_in_megabytes = 1;
$max_file_size_allowed =
"$max_file_size_allowed_in_bytes";
//Create a fileinfo respource.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
//Apply the fileinfo resource and the finfo_file()
function to the uploading given file.
$mime = finfo_file($finfo,$file_name);
//Close the fileinfo resource.
finfo_close($finfo); echo "Mime: $mime<br>"; //exit;
//Outputs: video/mp4
//Verify File Extension.
//if(!in_array($file_extension, $allowed_file_extensions))
die("Error 1: Select a valid video file format. Select an Mp4 file.");
//Verify MIME Type of the File.
if(!in_array($mime, $allowed_file_extensions)) die("Error 2:
Select a valid video file format. Select an Mp4 file.");
elseif(!in_array($file_type, $allowed_file_extensions))
die("Error 3: There was a problem uploading your file $file_name! Make
sure your file is an MP4 video file. You may try again."); //IS THIS LINE
CORRECT ?
//Verify File Size. Allowed Max Limit: 1MB.
if($file_size>$max_file_size_allowed) die("Error 4: Your
Video File Size is larger than the allowed limit of:
$max_file_size_allowed_in_megabytes.");
//Move uploaded File to newly created directory on the
server.
if(!move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name")) die("Error 5: Your file failed to
upload! Try some other time.");
else
{
move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name"); //WHY IS NOT THIS LINE OF CODE
MOVING THE FILE TO DESTINATION ?
//Notify user their Id Verification Video File was
uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded
successfully!";
exit();
}
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3>
</p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
I get echoed when trying to upload an mp4 file:
Error 3: There was a problem uploading your file id_check.mp4! Make sure your file is an MP4 video file. You may try again.
Should I set the folder permissions to 0644 from 0777 ? I am being told I should not allow any files to be executable in the folder by users (file uploaders) and so I should set it to readable & writeable only to "0644". I need your expert opinion on this.
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.
I am using the simple script below to upload a zip file via php and then unzip it on my server.
The file will be a zipped folder. When the upload is complete I want to echo a link to the new folder.
So for instance if I upload a zip file containing a folder called "bar", after the success message I want to echo "http://foo.com/bar".
Any help much appreciated.
<?php
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed',
'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = "/home/var/foo.com/".$filename; // change this to the correct
site path
if(move_uploaded_file($source, $target_path)) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("/home/var/foo.com/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1
/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
Taking a quick glance over everything, I'd say
$message = "Your .zip file was uploaded and unpacked. Files";
from what I gather on your script your telling it to upload directly to the servers directory path of the domain. Appending $filename as the folder name to that path so it creates a folder as such accordingly. From that its hardcoding the domain like you would to any other link and then appending the same filename variable to the end of it so it shows the same folder you just uploaded to.
This is just my guess overall though again only taking a quick glance and all.
From a detailed look at your code, I would say that I can give a few comments:
1) You should use mkdir() to create a new directory in the uploads directory of your site (I assume it's the root in this case).
2) You don't need to move uploaded file before unzipping it. Simply unzip it into the newly created directory. Make sure there isn't already another directory with the same name. The uploaded file should be deleted automatically by PHP, so no need to unlink.
3) In reference to:
$name = explode(".", $filename);
What happens if the filename has more than one dot? You should really use substr() with strrpos() to get everything after the last dot.
4) After uploading, just echo the path http://www.yoursite.com/newdir - don't see the problem. If you can be more specific about what you are having difficulty with, please comment.
I have a php file that uploads images like jpegs and png onto a folder called uploads that is stored on the apache server and in the same location as the php file.
I have checked the code of both the HTML and the PHP and both seem to be perfectly fine, however whenever I try to upload a file I always get an error message and the file doesn't get uploaded.
It would be much appreciated if someone with more experience than me can look at my code and tell me why it is behaving in this manner.
Here is the HTML form:
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Your File</title>
</head>
<body>
<?php
// put your code here
?>
<form enctype="multipart/form-data" method="post" action="fileHandler.php">
Select File:
<input name="uploaded_file" type="file"/><br/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
and here is the PHP file that is executed when the form is submitted:
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* PHP file that uploads files and handles any errors that may occur
* when the file is being uploaded. Then places that file into the
* "uploads" directory. File cannot work is no "uploads" directory is created in the
* same directory as the function.
*/
$fileName = $_FILES["uploaded_file"]["name"];//the files name takes from the HTML form
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"];//file in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"];//the type of file
$fileSize = $_FILES["uploaded_file"]["size"];//file size in bytes
$fileErrorMsg = $FILES["uploaded_file"]["error"];//0 for false and 1 for true
$target_path = "uploads/" . basename( $_FILES["uploaded_file"]["name"]);
echo "file name: $fileName </br> temp file location: $fileTmpLoc<br/> file type: $fileType<br/> file size: $fileSize<br/> file upload target: $target_path<br/> file error msg: $fileErrorMsg<br/>";
//START PHP Image Upload Error Handling---------------------------------------------------------------------------------------------------
if(!$fileTmpLoc)//no file was chosen ie file = null
{
echo "ERROR: Please select a file before clicking submit button.";
exit();
}
else
if(!$fileSize > 16777215)//if file is > 16MB (Max size of MEDIUMBLOB)
{
echo "ERROR: Your file was larger than 16 Megabytes";
unlink($fileTmpLoc);//remove the uploaded file from the PHP folder
exit();
}
else
if(!preg_match("/\.(gif|jpg|jpeg|png)$/i", $fileName))//this codition allows only the type of files listed to be uploaded
{
echo "ERROR: Your image was not .gif, .jpg, .jpeg or .png";
unlink($fileTmpLoc);//remove the uploaded file from the PHP temp folder
exit();
}
else
if($fileErrorMsg == 1)//if file uploaded error key = 1 ie is true
{
echo "ERROR: An error occured while processing the file. Please try again.";
exit();
}
//END PHP Image Upload Error Handling---------------------------------------------------------------------------------------------------------------------
//Place it into your "uploads" folder using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, $target_path);
//Check to make sure the result is true before continuing
if($moveResult != true)
{
echo "ERROR: File not uploaded. Please Try again.";
unlink($fileTmpLoc);//remove the uploaded file from the PHP temp folder
}
else
{
//Display to the page so you see what is happening
echo "The file named <strong>$fileName</strong> uploaded successfully.<br/><br/>";
echo "It is <strong>$fileSize</strong> bytes.<br/><br/>";
echo "It is a <strong>$fileType</strong> type of file.<br/><br/>";
echo "The Error Message output for this upload is: $fileErrorMsg";
}
?>
make sure that the directory structure has write permissions. You can check within php by using is_writeable. By checking from within PHP you will also be making sure that the PHP user has write access.
Check the folder permissions on the server. If incorrect, you can modify your php.ini file.
Is there a way to upload a file to server using php and the filename in a parameter (instead using a submit form), something like this:
myserver/upload.php?file=c:\example.txt
Im using a local server, so i dont have problems with filesize limit or upload function, and i have a code to upload file using a form
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="fileForm" enctype="multipart/form-data">
File to upload:
<table>
<tr><td><input name="upfile" type="file"></td></tr>
<tr><td><input type="submit" name="submitBtn" value="Upload"></td></tr>
</table>
</form>
<?php
if (isset($_POST['submitBtn'])){
// Define the upload location
$target_path = "c:\\";
// Create the file name with path
$target_path = $target_path . basename( $_FILES['upfile']['name']);
// Try to move the file from the temporay directory to the defined.
if(move_uploaded_file($_FILES['upfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['upfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
?>
</body>
Thanks for the help
Image Upload Via url:
//check
$url = "http://theonlytutorials.com/wp-content/uploads/2014/05/blog-logo1.png";
$name = basename($url);
try {
$files = file_get_contents($url);
if ($files) {
$stored_name = time() . $name;
file_put_contents("assets/images/product/$stored_name", $files);
}
}catch (Exception $e){
}
If you're doing this localy do you have the need to use "upload" mechanisms? otherwise if you're sending something externaly you could use cURL to upload the file, and run the PHP script on the CLI, quick google: http://dtbaker.com.au/random-bits/uploading-a-file-using-curl-in-php.html
if you want to use url to send the name of the file like below:
www.website.com/upload.php?hilton_plaza_party.jpg
There is a script to do that. Here: http://valums.com/ajax-upload/