Downloading file to server from url - php

I have a laravel application where I download files to my server from given URLs. I am using the following code to do this.
$file_name = $files_directory . str_replace( " ", "-", $_POST['file_name'] ) . $_POST['file_extension'];
if ( file_put_contents( $file_name, fopen( $file_url, 'r' ) ) !== false ) {
$success = true;
$msg = "File Downloaded Successfully";
}
I am using user input to create a filename and extension. Is there a way to get the filename and extension from the URL response? Or is there a better way to approach this problem?

I think, you will have problems with the solution . Because you havn't put try/catch cases and you hasn't validated file extensions. And these can bring security issuses in future. You have to change your script like this:
$file_name = $files_directory . str_replace( " ", "-", $_POST['file_name'] ) . $_POST['file_extension'];
try {
if(in_array(mb_strtolower($_POST['file_extension']), ['jpg','png','...permitted_extenions.....'])){
if ( file_put_contents( $file_name, fopen( $file_url, 'r' ) ) !== false ) {
$success = true;
$msg = "File Downloaded Successfully";
}
}else throw new Exception('Errors with extention');
}catch(\Exception $e){
echo $e->getMessage();
}

Related

PHP Script doesn't create XML file

I am having some trouble with a PHP script. I am trying to do two things:
Create an XML file in /usr/local/ezreplay/data/XML/ directory and add contents to it using inputs passed to it from a HTML form;
Upload a PCAP file which is included in the submitted HTML form.
Here is my PHP (apologies it is a little long but I believe all of it is relevant here):
<?php
// Check if the 'expirydate' input is set
if (isset($_POST['expirydate'])) {
// Convert the input string to a timestamp using 'strtotime'
$timestamp = strtotime($_POST['expirydate']);
// Format the timestamp as a 'mm/dd/yyyy' string using 'date'
$expirydate = date('m/d/Y', $timestamp);
}
// Check if all required POST variables are set
if ( isset($_POST['destinationip']) && isset($_POST['destinationport']) && isset($expirydate) && isset($_POST['multiplier']) && isset($_POST['pcap']) ) {
// Set the path for the XML file
$path = '/usr/local/ezreplay/data/XML/' . trim($_POST['destinationip']) . ':' . trim($_POST['destinationport']) . ':' . $expirydate . ':' . trim($_POST['multiplier']) . ':' . trim($_POST['pcap']) . '.xml';
// Initialize the contents of the XML file
$contents = "";
// Open the XML file in append mode
if ( $fh = fopen($path,"a+") ) {
// Add the opening 'config' tag to the XML file
$contents .= '<config>';
// If the 'destinationip' and 'destinationport' POST variables are not empty, add a 'destination' tag to the XML file
if ( trim( $_POST['destinationip'] ) != "" && trim( $_POST['destinationport'] ) != "" ) {
$contents .= "\n" . '<destination>' . $_POST['destinationip'] . ':' . $_POST['destinationport'] . '</destination>';
}
// If the 'multiplier' POST variable is not empty, add a 'multiplier' tag to the XML file
if ( trim( $_POST['multiplier'] ) != "" ) {
$contents .= "\n" . '<multiplier>' . $_POST['multiplier'] . '</multiplier>';
}
// If the 'pcap' POST variable is not empty, add a 'pcap' tag to the XML file
if ( trim( $_POST['pcap'] ) != "" ) {
$contents .= "\n" . '<pcap>/usr/local/ezreplay/data/PCAP/' . $_POST['pcap'] . '</pcap>';
// Add default tags to XML config file to ensure the pcap does not fail and loops continuously until expiration date hits
$contents .= "\n" . '<loop>0</loop>';
$contents .= "\n" . '<nofail>true</nofail>';
}
// Add the closing 'config' tag to the XML file
$contents .= "\n" . '</config>';
// Write the contents to the file
if ( fwrite( $fh, $contents ) ) {
// Success
} else {
echo "The XML config could not be created";
}
// Close the file
fclose($fh);
}
}
// Set the target directory and file name
$target_dir = "/usr/local/ezreplay/data/PCAP/";
$basename = basename($_FILES["pcap"]["name"]);
$target_file = $target_dir . $basename;
// Check if the file has a pcap extension
$allowedExtensions = array('pcap');
$basenameWithoutExt = null;
foreach ($allowedExtensions as $allowedExtension) {
if (preg_match('#\\.' . $allowedExtension . '$#',$basename)) {
$basenameWithoutExt = substr($basename,0,-1 - strlen($allowedExtension));
break;
}
}
// Accept only .pcap files
if (is_null($basenameWithoutExt)) {
echo "Sorry, only .pcap files are allowed. Please try creating your Packet Replay again using a .pcap file.";
exit;
}
// Check if the file already exists
if (file_exists($target_file)) {
echo "The Packet Replay could not be started, the PCAP is already running.";
exit;
}
// Try to upload the file
if (move_uploaded_file($_FILES["pcap"]["tmp_name"], $target_file)) {
// Success
} else {
echo "Sorry, there was an error uploading your file.";
exit;
}
// Start the Packet Replay
$command = '/usr/local/ezreplay/bin/startreplay.sh ' . $path;
system($command);
echo "The Packet Replay has been started.";
?>
Now the file upload is working and I can see the final echo message being returned in my browser however the XML file is never created. I have changed the directory ownership to the apache user and even chmod 777 to eliminate any permissions issues but it still doesn't create the file.
Any ideas why this is not working? The PHP and apache error logs don't show any issues and as I mentioned the script seems to be working to a degree as the file upload takes place perfectly.
Thanks!
I think the file is not being created due to "/" in the filename. As mentioned at Allowed characters in filename
I managed to fix this with the following edits.
<?php
// Set the target directory and file name
$target_dir = "/usr/local/ezreplay/data/PCAP/";
$basename = basename($_FILES["pcap"]["name"]);
$target_file = $target_dir . $basename;
// Check if the file has a pcap extension
$allowedExtensions = array('pcap');
$basenameWithoutExt = null;
foreach ($allowedExtensions as $allowedExtension) {
if (preg_match('#\\.' . $allowedExtension . '$#',$basename)) {
$basenameWithoutExt = substr($basename,0,-1 - strlen($allowedExtension));
break;
}
}
// Accept only .pcap files
if (is_null($basenameWithoutExt)) {
echo "Sorry, only .pcap files are allowed. Please try creating your Packet Replay again using a .pcap file.";
exit;
}
// Check if the file already exists
if (file_exists($target_file)) {
echo "The Packet Replay could not be started, the PCAP is already running.";
exit;
}
// Try to upload the file
if (move_uploaded_file($_FILES["pcap"]["tmp_name"], $target_file)) {
//Success
} else {
echo "Sorry, there was an error uploading your file.";
exit;
}
// Check if the 'expirydate' input is set
if (isset($_POST['expirydate'])) {
// Convert the input string to a timestamp using 'strtotime'
$timestamp = strtotime($_POST['expirydate']);
// Format the timestamp as a 'mm-dd-yyyy' string using 'date'
$expirydate = date('m-d-Y', $timestamp);
}
// Check if 'destinationip', 'destinationport', 'multiplier' and 'pcap' required POST variables are set
if (isset($_POST['destinationip']) && isset($_POST['destinationport']) && isset($_POST['multiplier'])) {
// Set the filename and path for the XML file
$file = '/usr/local/ezreplay/data/XML/' . trim($_POST['destinationip']) . ':' . trim($_POST['destinationport']) . ':' . trim($_POST['multiplier']) . ':' . $expirydate . ':' . $_FILES["pcap"]["name"] . '.xml';
// Initialize the contents of the XML file
$contents = "";
// Add the opening 'config' tag to the XML file
$contents .= '<config>';
// If the 'destinationip' and 'destinationport' POST variables are not empty, add a 'destination' tag to the XML file
if (trim($_POST['destinationip']) != "" && trim($_POST['destinationport']) != "") {
$contents .= "\n" . '<destination>' . $_POST['destinationip'] . ':' . $_POST['destinationport'] . '</destination>';
}
// If the 'multiplier' POST variable is not empty, add a 'multiplier' tag to the XML file
if (trim($_POST['multiplier']) != "") {
$contents .= "\n" . '<multiplier>' . $_POST['multiplier'] . '</multiplier>';
}
// If the 'pcap' POST variable is not empty, add a 'pcap' tag to the XML file
if (trim($_FILES["pcap"]["name"]) != "") {
$contents .= "\n" . '<pcap>/usr/local/ezreplay/data/PCAP/' . $_FILES["pcap"]["name"] . '</pcap>';
}
// Add default tags to XML config file to ensure the pcap does not fail and loops continuously until expiration date hits
$contents .= "\n" . '<loop>0</loop>';
$contents .= "\n" . '<nofail>true</nofail>';
// Add the closing 'config' tag to the XML file
$contents .= "\n" . '</config>';
// Write the contents to the file
if (file_put_contents($file, $contents)) {
// Success
} else {
echo "The XML config could not be created";
}
}
// Start the Packet Replay
$command = '/usr/local/ezreplay/bin/startreplay.sh ' . $path;
system($command);
echo "The Packet Replay has been started.";
?>

Edit PHP file in Wordpress programmatically

I am trying to edit a few PHP codes lines in my Wordpress theme files with a snippet of PHP code, though I am stuck and have been struggling to do this for a while with this code.
I have been trying to tweak this piece of code to do the job but unfortunately without luck.
function update_GTour_theme_files()
{
$new_update = file_get_contents(__DIR__ . "/../../themes/grandtour/header.php");
$new_update = preg_replace('/$page_menu_transparent = 1/','$page_menu_transparent = 0',$new_update);
$new_update = preg_replace('/$grandtour_page_menu_transparent = 1/','$grandtour_page_menu_transparent = 0',$new_update);
file_put_contents (__DIR__ . "/../../themes/grandtour/header.php", $new_update);
if ( file_exists (__DIR__ . "/../../themes/grandtour/header.php") && is_writable (__DIR__ . "/../../themes/grandtour/header.php") ){
update_GTour_theme_files();
echo '</br><span style="color:green;font-weight:bold;">Changes were applied successfully.</span>';
}
else {
echo '</br><span style="color:red;font-weight:bold;">Error occured while applying the changes.</span>';
}
}
I am expecting that this code should replace some text as illustrated in the file with the described path but it doesn't work.
Where do I start... let me count the ways.
function update_GTour_theme_files()
{
$new_update = file_get_contents(__DIR__ . "/../../themes/grandtour/header.php");
$new_update = preg_replace('/$page_menu_transparent = 1/','$page_menu_transparent = 0',$new_update);
$new_update = preg_replace('/$grandtour_page_menu_transparent = 1/','$grandtour_page_menu_transparent = 0',$new_update);
file_put_contents (__DIR__ . "/../../themes/grandtour/header.php", $new_update);
if ( file_exists (__DIR__ . "/../../themes/grandtour/header.php") && is_writable (__DIR__ . "/../../themes/grandtour/header.php") ){
update_GTour_theme_files();
echo '</br><span style="color:green;font-weight:bold;">Changes were applied successfully.</span>';
}
else {
echo '</br><span style="color:red;font-weight:bold;">Error occured while applying the changes.</span>';
}
}
Lets see when you run this it does:
file_put_contents (__DIR__ . "/../../themes/grandtour/header.php", $new_update);
Then it checks:
if ( file_exists (__DIR__ . "/../../themes/grandtour/header.php") && is_writable (__DIR__ . "/../../themes/grandtour/header.php") ){
update_GTour_theme_files();
echo '</br><span style="color:green;font-weight:bold;">Changes were applied successfully.</span>';
}
Which is obviously true, or we would have gotten some errors already. So that is basically always true. Which means you call this update_GTour_theme_files(); itself again. Repeat the above steps a infinite number of times.
So that is obviously wrong. If you are calling this I would expect your browser to lockup.
So lets fix this up (single file):
function update_GTour_theme_files($file)
{
//fail early
if (!file_exists ($file) || !is_writable ($file) ) die("File $file Does not exists or is not writable");
$new_update = file_get_contents($file);
$new_update = preg_replace('/\$page_menu_transparent\s*=\s*1;/','$page_menu_transparent = 0;',$new_update);
$new_update = preg_replace('/\$grandtour_page_menu_transparent\s*=\s*1;/','$grandtour_page_menu_transparent = 0;',$new_update);
if(file_put_contents ($file, $new_update)){
echo '</br><span style="color:green;font-weight:bold;">Changes were applied successfully.</span>';
}else{
echo '</br><span style="color:red;font-weight:bold;">Error occured while applying the changes.</span>';
}
}
update_GTour_theme_files(__DIR__ . "/../../themes/grandtour/header.php");
This will only update the one file, to do more then that you need to use scandir, glob or SPL DirectoryIterator / FilesystemIterator.
PS your "main" or "big" problem (besides the recursion) is right here:
$new_update = preg_replace('/$page_menu_transparent = 1/','$page_menu_transparent = 0',$new_update);
$new_update = preg_replace('/$grandtour_page_menu_transparent = 1/','$grandtour_page_menu_transparent = 0',$new_update);
These $ in /$page_menu_transparent are not escaped so the are treated as REGEX. Which means they match the end of the string, which makes no sense. I also added some vaiable space \s*=\s* and the ; semi-colon otherwise $page_menu_transparent = 1345; will become $page_menu_transparent = 0;. This may have some impact if it's in () or an array etc. (anything without the ;)
For all files in a given folder and it's subfolders
function update_GTour_theme_files($dir)
{
if (!file_dir($dir) || is_writable ($dir) ) die("Dir $dir Does not exists or is not writable");
$Iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$dir,
RecursiveDirectoryIterator::SKIP_DOTS|RecursiveDirectoryIterator::UNIX_PATHS
)
);
foreach($Iterator as $fileInfo){
if($fileInfo->isDir() || $fileInfo->getExtension() != 'php') continue;
$file = $fileInfo->getPathname();
$new_update = file_get_contents($file);
$new_update = preg_replace('/\$page_menu_transparent\s*=\s*1;/','$page_menu_transparent = 0;',$new_update);
$new_update = preg_replace('/\$grandtour_page_menu_transparent\s*=\s*1;/','$grandtour_page_menu_transparent = 0;',$new_update);
if(file_put_contents ($file, $new_update)){
echo '</br><span style="color:green;font-weight:bold;">Changes were applied successfully.</span>';
}else{
echo '</br><span style="color:red;font-weight:bold;">Error occured while applying the changes.</span>';
}
}
}
update_GTour_theme_files(__DIR__ . "/../../themes/grandtour/");
This uses RecursiveDirectoryIterator so it should look through all sub folders.
But this is all untested so be very careful. If you mess your files up don't come blaming me, you were warned.
That said Enjoy~

Magento send PDF attachment

I try to send Mail in a Magento CE 1.8.0.0,
I can send pictures et text files, but when i try to send pdf, it's always fail, my attachment size is 0 Ko and i can't open it ...
This is how i work :
if($filename != '')
{
$mailTemplate
->getMail()
->createAttachment(
file_get_contents(Mage::getBaseDir('tmp').'/pjcontact/'.$filename),
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
basename($filename)
);
}
On server, the pdf file is correct.
With this code, only PDF fails ... I'm on it since this morning and i find nothing, someone had an idea ?
My suspicion is that file_get_contents returns false. Try debugging it with:
if ( $filename != '' )
{
$path = Mage::getBaseDir( 'tmp' ) . '/pjcontact/' . $filename;
Mage::log("File found in {$path}? ".(file_exists($path)?"Yes":"No").". Is it readable? ".(is_readable($path)?"Yes":"No"));
$mailTemplate
->getMail()
->createAttachment(
file_get_contents( $path ),
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
basename( $filename )
);
}

Backup Entire Website Using PHP

Using PHP, I am developing a CMS. This needs to support website backups.
Musts:
Compressed ZIP Folders
Must work on at least Linux and Windows
Must work on PHP 5.0, PHP 4 would be nice
I just need a function/class, don't link me open-source software as I need to do this my self
CMS does not need MySQL backups as it is XML powered
I've already checked into ZipArchive in PHP. Here is all I got so far. However when I try to go to the ZIP file on the server that it says it created, I get a 404? It isn't working and I don't know why.
<?php
$filename = CONTENT_DIR . 'backups/' . date( 'm-d-Y_H-i-s' ) . '.zip';
if ( $handle = opendir( ABS_PATH ) ) {
$zip = new ZipArchive();
if ( $zip->open( $filename, ZIPARCHIVE::CREATE ) !== true ) {
exit( "cannot open <$filename>\n" );
}
$string = '';
while ( ( $file = readdir( $handle ) ) !== false ) {
$zip->addFile( $file );
$string .= "$file\n<br>";
}
closedir( $handle );
$string .= "Status of the Zip Archive: " . $zip->status;
$string .= "<br>System status of the Zip Archive: " . $zip->statusSys;
$string .= "<br>Number of files in archive: " . $zip->numFiles;
$string .= "<br>File name in the file system: " . $zip->filename;
$string .= "<br>Comment for the archive: " . $zip->comment;
$zip->close();
echo $string;
}
?>

Mercury mail and php email creation script

I need help creating a script or program that can add users to my mercury mail server when they sign up on a form. I'm using a basic php post form, it does create all the necessary files to run the account but when I open mercury mail the new user account has not been added to the accounts list. And the new account cannot sign in.
Please assist me in creating a client email signup script or program so that my clients can easily create an email on my server for free.
Link to the form code: http://pastebin.com/bEtv4eck
Link to the php post code: http://pastebin.com/rwBJatap
P.S. I have the script working to where it can create the new user and everything, but it won't allow a login unless the email server is restarted. Any way to fix this?
Try using the RELOAD USERS after making the changes to the pmail.usr and mail, directories.
You need to also add user in the PMAIL.USR file
Try
const MERCURY_PATH = 'C:\Apache\xampp\MercuryMail';
$userFile = MERCURY_PATH . DIRECTORY_SEPARATOR . "PMAIL.USR";
$mailDir = MERCURY_PATH . DIRECTORY_SEPARATOR . "MAIL";
$newName = "Baba Konko";
$newUsername = "baba";
$newPassword = "pass";
$host = "localhost";
if (! is_writeable ( $userFile )) {
die ( "You don't have permission to Create new User" );
}
if (! is_writeable ( $mailDir )) {
die ( "You don't have permission to add mail folder" );
}
// Check if user exist
if (is_file ( $userFile )) {
$users = file ( $userFile );
foreach ( $users as $user ) {
list ( $status, $username, $name ) = explode ( ";", strtolower ( $user ) );
if (strtolower ( $newUsername ) == $username) {
die ( "User Already Exist" );
}
}
}
$userData = "U;$newUsername;$newName";
$fp = fopen ( $userFile, "a" );
if ($fp) {
fwrite ( $fp, $userData . chr ( 10 ) );
fclose ( $fp );
}
$folder = $mailDir . DIRECTORY_SEPARATOR . $newUsername;
if (! mkdir ( $folder )) {
die ( "Error Creating Folder" );
}
$pm = '# Mercury/32 User Information File' . chr ( 10 );
$pm .= 'POP3_access: ' . $newPassword . chr ( 10 );
$pm .= 'APOP_secret: ' . $newPassword . chr ( 10 );
$pmFile = $folder . DIRECTORY_SEPARATOR . 'PASSWD.PM';
file_put_contents ( $pmFile, $pm );

Categories