PHP get file content without saving - php

I have the following php code that runs when someone uploads a file:
if ($_FILES['files']['error'] === UPLOAD_ERR_OK) {
die("Upload failed with error " . $_FILES['file']['error']);
}
$namme = $_FILES['files']['name'][0];
$namme = substr($namme, strpos($namme,"."), strlen($namme));
$ok = false;
switch ($namme) {
case '.docx':
case '.txt':
case '.pdf':
break;
default:
die("Unknown/not permitted file type");
}
$filename = $_FILES['files']['tmp_name'][0];
$file = _file_get_contents('./'.$_FILES['files']['name'][0], true);
I want to print all of the content out but i don't wish to save the file first and then open it.
My question is: Is it possible to open the text file print the content without saving the file first?

When the user uploads a file, it gets saved in a temp location. That's just how the HTTP server works, before your PHP script ever gets called. It would be bad if the server held all uploaded files in memory; what if the user is uploading a dozen files that are all 10 MB?
The only way to avoid that is to not use file upload (for example, have the user paste the file contents into a text area that gets submitted), or write your own HTTP server and don't use PHP (not a practical solution, most likely).

Related

hello I wanna use php_move_upload_file in order to move image from my temp folder to a permanent folder

hi this is the function that upload image inside temp location and save location to session for forther use
function uploadPhoto()
{
$rawImage = $_FILES['advPhoto'];
$uploader = new ImageUploader($rawImage);
$uploader->moveToProjectTempFolder();
//1 save the current image in sassion (save the attachment class inside seesion)
$uploader->saveInSession();
// $temperrary = $uploader->CurrentImgTemperraryLocation();
//2 send reponse the current image location
AjaxHelper::sendAjaxResponse("images/temp/" . $uploader->CurrentImgTemperraryLocation());
//create image tag and set the image source the "temp uploaded image path"
// done
//when the mail form is submitted
//loop through session array
//move the user uploaded/approved images to permanent folder
//save image information inside DB
}
here is the function that cause problem I wanna move the picture from temp folder to permanent location but the php_move_uploaded_file() doesn't work in my case I don't really know what is the problem please help me if you know what is the problem thnks .
function saveAdv()
{
$advTitle = $_POST['advTitle'];
$advContent = $_POST['advContent'];
if (!empty($advTitle) && !empty($advContent)) {
if (DataValidation::isOnlyPersianOrEnglish($advTitle) &&
DataValidation::isOnlyPersianOrEnglish($advContent)) {
DBconnection::insertRow('ADVERTISEMENT', ['title', 'Advertisement', 'advDate'],
[$advTitle, $advContent, date('y/m/d h:i:s')]);
// AjaxHelper::sendAjaxResponse("success");
$projectTemp = $_SESSION['ADVERTISEMENT']['Img'];
move_uploaded_file(
$projectTemp,
DOC_ROOT . "/images/advertisementImg/"
);
AjaxHelper::sendAjaxResponse($projectTemp);
}
} else {
AjaxHelper::sendErrorMessage(AjaxHelper::EMPTY_EMAIL_OR_PASSWORD);
}
}
I don't get any error I've already debuged many times but no warning and no errors at all and the location of the folders are completely correct and also there is no permission problems.
The move_uploaded_file() works pretty well at first step that I move image from system temp location to my project temp location, but doesn't work when I wanna move the image from project temp location to permanent location.
move_uploaded_file() is only for moving files which have just been uploaded in a POST request and are stored in the system temp location. As the documentation (https://php.net/manual/en/function.move-uploaded-file.php) states, it first checks whether the file is a valid upload file meaning that it was uploaded via PHP's HTTP POST upload mechanism (that's a direct quote from the docs). If it's not valid by that definition, it fails.
So, if you're trying to use move_uploaded_file() to copy files from other locations (not the system temp location) which have not been directly uploaded to that location in the current request, then it won't work. Use PHP's general file manipulation functionality for moving other files around, using the rename() function (see https://www.php.net/manual/en/function.rename.php for details).

Renaming Server File Error (http wrapper does not support renaming) [PHP]

On my page users can upload documents, which will be saved in a user specific folder. the directories are stored in a url: http://localhost/folder/user/documentA_user_timestamp.ext inside a database.
Users can also delete a file, which deletes the file's entry inside the database but i want the file to be moved to a specified archive folder. However i always get this error message when the php rename() tries to do its work:
http wrapper does not support renaming in...
I can't seem to get my head around the error message and figure out whats the cause for it
$filepath = $_POST['file'];
$archivePath = FILESYS_DOCS_ARCHIVE . basename($filepath);
if (!file_exists(FILESYS_DOCS_ARCHIVE)){
mkdir(FILESYS_DOCS_ARCHIVE, 0777);
}
$success = rename($filepath, $archivePath);
if ($success){
echo "SUCCess";
} else {
echo $archivePath;
}
use this
$dir = str_replace('http://','',base_url());
rename($dir.'older filename', $dir.'/new filename' )

Save a file to a different folder using php?

I want to know if it is possible to save a file to a different folder once it is opened. My current logic is -
$myfile = $_POST['file']; // gets path of (in this case an image)
$size = getimagesize($myfile); //for some reason I get an error message when this fails
// I'm assuming there is a better way of determining if the file is an image file or not.
if($size)
{
//save file to said file path
}
Try:
if($size)
{
copy($myfile, $newfile); //$newfile - with full path!
}

PHP - upload and overwrite a file (or upload and rename it)?

I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);

PHP move_uploaded_file to directory and create file

I have a script that uploads a file and then moves it to a directory. However the script does not know the name of the file its creating because it hasn't created it yet and cannot find the file to update.
So either one requires a way to make the file first or there is another way of doing this. The code.
<?php
$filename = '/home/divethe1/public_html/update/z-images/admin/upload/test/';
if ($_FILES['thumbfile']['error'] === UPLOAD_ERR_OK) {
$info = getimagesize($_FILES['thumbfile']['tmp_name']);
if (($info[2] !== IMG_GIF) && ($info[2] !== IMG_JPEG)) {
die("not a gif/jpg");
}
if (filesize($_FILES['thumbfile']['tmp_name']) > 100000) {
die("larger than 100000");
}
move_uploaded_file($_FILES['thumbfile']['tmp_name'], $filename . $_FILES['thumbfile']['name']);
echo '<script type="text/javascript">
parent.document.getElementById("thumbprogress").innerHTML = "Archiving"</script>Archiving';
}
else
{
echo '<script type="text/javascript">
parent.document.getElementById("thumbprogress").innerHTML = "Invalid File Format"</script>Invalid File Format';
}
?>
Any ideas?
I think you're misunderstanding how move_uploaded_file() works. It doesn't create a file for you. It:
Takes the temporary filethat PHP created for you to hold the upload (the filename/path for which is in $_FILES['thumbfile']['tmp_name'])
does a few security checks to make sure no one's tampered with the file between the time the upload completed and the move_uploaded_file call was issued
then MOVES the file to the location you specify.
It doesn't handle the upload, or receive the file - by the time your upload-handling script gets fired up, the upload has already been completed and the file is waiting in that tmp_name location.
If the move can't be completed for any reason, move_uploaded_file() returns false. It won't warn you if you're overwriting a file in the destination, on the assumption that you know what you're doing.
My mistake. I left the directory test in place. That should have gone. Thanks anyway for all help.

Categories