when i do a direct input feild as text the input comes through fine but when i change the input feild type to "FILE" and then read the temp contents stored on the server it adds extra characters that are "unknown"
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, $fileSize);
fclose($fp);
echo $content;
Its most probably to do with secuirty but how do i change the content so it reads normal? In firefox it comes up with square boxes for most characters with the letters:
Here is an example:
Its meant to say:
"Dirty Rocker" but instead comes out like this: "D�i�r�t�y� �R�o�c�k�e�r"
Hope you can help!
Set data type in form to multipart/form-data. Set encoding of output page to utf-8 through header and meta tag.
Check real contents of uploaded file. Compair original file and its copy on the server. Try to upload file manually (though ftp, for example) and read it by php.
Related
I'm uploading files to my PHP webservice by encoding them to Base64 and sending them via Json.
I'm decoding the data on the server using this code: $file_content = base64_decode($file,true);
Now I want to extract file name and extension from the $file_content variable.
How can I do that?
UPDATE: here is the code I used to decode the file:
include '../conn.php';
include '../functions.php';
$entityBody = file_get_contents('php://input');
$decodedJson = json_decode($entityBody);
$user_email = $decodedJson->{'email'};
$user_token = $decodedJson->{'token'};
$file = $decodedJson->{'file'}; //This is the encoded content of the file from JSON
$file_content = base64_decode($file,true);
if(!checkStudentAuthorizationOrHigher($user_email,$user_token,$conn))
{
die();
}
//now I want to get $file_content type (extension or MIME type) and
//file name from the $file_content
//I tried the below code but it only gets file path as input parameter and doesn't work this way
echo mime_content_type($file_content);
Only the file content is given to my PHP webservice through JSON (file name or extension is not sent to my service). If it helps, the client side of my application is both a C# Windows Forms app and an Android app.
I want to save the file on the server with the same file name as the client side. Also I have to check the file type to make sure it is allowed on the server. (the file can be .pdf , .jpg , .jpeg or .zip)
Now is there a way to extract file info from $file_content variable?
I used thw Intervention/image library https://github.com/Intervention/image
to deal with base64 encoded images. THis library got many other features as well.
$imageManager = new Intervention\Image\ImageManager();
$imageObject = $imageManager->make($base64EncodedImageSource);
$imageInfo = getimagesize($base64EncodedImageSource);
$this->mimeType = $imageInfo[2];
$extension = image_type_to_extension($this->mimeType);
$width = $imageInfo[0];
$height = $imageInfo[1];
$tempFilePath = '/path/to/file';
$imageObject->save($tempFilePath, 100);
Alternatively, if you have mime type of the file, you can use function image_type_to_extension to get file extension
I want to retrieve a ZIP file with PHP from a MSSQL database wich is stored in a IMAGE field.
In this part i make a connection using sqlsrv, send a query, and move to the first row and get the first field in BINARY encoding.
$conn = sqlsrv_connect($sql['s'],array('Database'=>$sql['db'],'UID'=>$sql['usr'],'PWD'=>$sql['pwd']));
$q = 'SELECT TOP 1 FileContent
FROM dbo.tblDocumentContent
WHERE FileContent IS NOT NULL
ORDER BY CreateDate DESC';
$res = sqlsrv_query($conn, $q);
sqlsrv_fetch($res);
$zip = sqlsrv_get_field($res,0,SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY));
At this point the zip is retrieved as a resource stream and here i get stuck.
When i set the headers and output the content, the browser downloads the zip.
header("Content-type: application/zip, application/octet-stream");
header("Content-Disposition: attachment; filename=test.zip;");
fpassthru($zip);
This works like a charm, the zip works perfect.
But what i want is to open the zip serverside without the user having to dowload it.
So when i just try to write the content to a file:
$file = fopen('test.zip', 'a');
fwrite($file, fpassthru($zip));
fclose($file);
It can't be opened. I figured that when the browser downloads the given content, it encodes it someway. Alltrough i can not figure out how to do that while writing it to a file.
If someone has any solutions to write the resource stream to a file on the server side in the proper way, that would be great.
This should solve the problem:
$file = fopen('test.zip', 'w');
while (!feof($img)) {
$chunk = fread($img, 1024);
fwrite($file, $chunk);
}
fclose($img);
fclose($file);
The file in the file path contains no JavaScript; it's just plain HTML or PHP scripts. They are also local. I'm trying to convert any file in the main path to UTF-8 before it is stored as a link in a menu. I have no control of the files that are uploaded except that they are either PHP or HTML.
An example is that the file size of one file is changed from 6,808 to 572 with the following:
$filesize = filesize($filepath);
$filecontent = file_get_contents($filepath,FALSE,NULL,0,$filesize);
$utf8content = iconv(mb_detect_encoding($filecontent, mb_detect_order(),
true), "UTF-8", $filecontent);
$fp = fopen($filepath, 'w');
fwrite($fp, $utf8content);
fclose($fp);
I have a problem in saving file data and retrieving content in original form using SQL Server.
To save content, I have used this code
$size = filesize($file);
$fp = fopen($file, 'rb');
$content = fread($fp, $size);
$content = addslashes($content);
fclose($fp);
and database to store its content is of type image.
Never do addslashes to binary files.addslashes should only be done on text data.
Image files,audio video files and executable all are binary files.
Try removing addslashes and try again.If it still doesn't get inserted into your database then you should check if the datatype of the column in your database is set to blob.Only blob datatype can hold binary data.
If still you have problems inserting to database then try inserting smaller images of size smaller than 1mb. php has a default post and file upload limit of 2mb.
I have this simple script which works fine, but currently overwrites files with duplicate names. How can I avoid this?
<?php
// Configuration - Your Options
$allowed_filetypes = array('.mp3'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = './uploads/'; // The place the files will be uploaded to (currently a 'files' directory).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
if(!in_array($ext,$allowed_filetypes))
header('Location: http://www.website.com/five/error');
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
header('Location: http://www.website.com/five/error');
if(!is_writable($upload_path))
header('Location: http://www.website.com/five/error');
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
// echo 'Your file upload was successful, view the file here'; // It worked.
header('Location: http://www.website.com/five/sent');
else
header('Location: http://www.website.com/five/error');
?>
Add an if (file_exists($upload_path.$filename)) before you upload, and set $filename to something else if it does.
One option is to use a database to store the original names, along with a unique id.
Then you can save the file as whatever unique name you want.
Use just the id... file = 1
Use the id and extension = 1.mp3
Use a combination of the id and name = 1_name_of_file.mp3
Or any other unique naming option.
Then you use php to serve the files. Setting the header with the original file name.
Users would not be aware of how you are storing the file. Multiple files with the same name could be uploaded and downloaded with that name, but stored uniquely on the server.
<?php
$actualFile = './uploads/'.$id;
// Can use some smarts to determine the mime type here
header('Content-type: application/force-download');
// The user will be prompted to save it as the filename given here.
header('Content-Disposition: attachment; filename="'.$originalName.'"');
header("Content-Length: ".filesize($actualFile));
// The actual file on the server
readfile($actualFile);
?>
There are also a number of other header options you can set for caching and so on.
http://php.net/manual/en/function.header.php
Fileinfo is a good extension for determining mimetypes
http://www.php.net/manual/en/function.finfo-file.php
Use your own filename instead of the original.
This could for example be generated via uniqid()
store the file with a hash as the name, and store the original filename in a database/flat file along with the hash.
if you want to use flat files it could just be that the user file gets stored as .dat and the info about the file is stored as either .json or .xml or even just a serialized PHP object if you prefer.
also, your file-extension detecting logic fails as soon as the filename has more than one dot (period) in the name.