upload image in PHP5 - image-uploading

I have this code in PHP to upload images to directory. The problem is: It's not uploading .png files.
Error: Você não enviou nenhum arquivo!
I don't know how to fix, already tried a lot of changes.
<?php
//Upload de arquivos
// verifica se foi enviado um arquivo
if(isset($_FILES['arquivo']['name']) && $_FILES["arquivo"]["error"] == 0)
{
echo "Você enviou o arquivo: <strong>" . $_FILES['arquivo']['name'] . "</strong><br />";
echo "Este arquivo é do tipo: <strong>" . $_FILES['arquivo']['type'] . "</strong><br />";
echo "Temporáriamente foi salvo em: <strong>" . $_FILES['arquivo']['tmp_name'] . "</strong><br />";
echo "Seu tamanho é: <strong>" . $_FILES['arquivo']['size'] . "</strong> Bytes<br /><br />";
$arquivo_tmp = $_FILES['arquivo']['tmp_name'];
$nome = $_FILES['arquivo']['name'];
// Pega a extensao
$extensao = strrchr($nome, '.');
// Converte a extensao para mimusculo
$extensao = strtolower($extensao);
// Somente imagens, .jpg;.jpeg;.gif;.png
// Aqui eu enfilero as extesões permitidas e separo por ';'
// Isso server apenas para eu poder pesquisar dentro desta String
if(strstr('.jpg;.png;.gif;.jpeg', $extensao))
{
// Cria um nome único para esta imagem
// Evita que duplique as imagens no servidor.
$novoNome = md5(microtime()) . $extensao;
// Concatena a pasta com o nome
$destino = 'images/uploads/logos/' . $novoNome;
// tenta mover o arquivo para o destino
if( #move_uploaded_file( $arquivo_tmp, $destino ))
{
echo "Arquivo salvo com sucesso em : <strong>" . $destino . "</strong><br />";
echo '<img src="' . $destino . '" />';
echo '<META http-equiv="refresh" content="0;URL=/administracao">';
exit;
}
else
echo "Erro ao salvar o arquivo. Aparentemente você não tem permissão de escrita.<br />";
}
else
echo "Você poderá enviar apenas arquivos .jpg, .jpeg, .gif e .png.";
}
else
{
echo "Você não enviou nenhum arquivo!";
}
?>
Can someone help me please?

You are checking if the string after . matches your accepted extensions. Like I mentioned in the comment section a user can easily change their file's extension and upload it regardless of the content.
On PHP.net there is an article/comment about how to upload files, some safety issues are also explained briefly in code and solved. I think this part will do for you:
// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['upfile']['tmp_name']),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
),
true
)) {
throw new RuntimeException('Invalid file format.'); // You can replace this with a custom message if you want.
// Either that or catch it in higher level
}
Source to this code (PHP.net)
Also make sure that your errors are enabled, so you can spot any PHP mistakes:
error_reporting(E_ALL); // Report ALL errors once they occur
ini_set('display_errors', 1); // Once they get reported, print them as HTML on your page
One more suggestion, remove the error suppression # in the move_uploaded_file if statement. If anything fails, you won't see why.
So I think this saves you time, as well fixing your problem in a safe way.
Good luck.

some comments.
This path must have write permission.
$destino = 'images/uploads/logos/' . $novoNome;
Also check that your form has
enctype="multipart/form-data"

Related

Facebook login: url cannot be loaded

I have the following code and get the following error (it is in Dutch):
Graph returned an error: URL kan niet worden geladen: Het domein van deze URL is niet toegevoegd aan de domeinen van deze app. Voeg alle domeinen en subdomeinen van je app toe aan het veld Appdomeinen in de instellingen van je app om deze URL te kunnen laden.
What may be wrong?
ini_set('display_errors', true);
$host = "m.****.com"; // Your Sub domain
$host2 = "www.m.****.com"; // Your Sub domain
if ($_SERVER['HTTP_HOST'] == $host || $_SERVER['HTTP_HOST'] == $host2) {
$root_doc = $_SERVER['DOCUMENT_ROOT'];
$root_doc = str_replace("/m","",$root_doc);
} else {
$root_doc = $_SERVER['DOCUMENT_ROOT'];
}
include_once("$root_doc/php-graph-sdk-5.x/src/Facebook/autoload.php");
//require_once __DIR__ . '/vendor/autoload.php'; // change path as needed
$fb = new \Facebook\Facebook([
'app_id' => '*****',
'app_secret' => '****',
'default_graph_version' => 'v2.10',
//'default_access_token' => '{access-token}', // optional
]);
// Use one of the helper classes to get a Facebook\Authentication\AccessToken entity.
// $helper = $fb->getRedirectLoginHelper();
// $helper = $fb->getJavaScriptHelper();
// $helper = $fb->getCanvasHelper();
// $helper = $fb->getPageTabHelper();
//BEGIN
$helper = $fb->getRedirectLoginHelper();
//$helper = $fb->getRedirectLoginHelper();
if (isset($_GET['state'])) {
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
}
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
//echo '<h3>Metadata</h3>';
//var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId("152670682069405");
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (! $accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $e->getMessage() . "</p>\n\n";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
//END
try {
// Get the \Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$response = $fb->get('/me', '{access-token}');
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();
I hope i will get an answer.
Regards,
Jeroen
Translated from Dutch to English:
URL can not be loaded: The domain of this URL has not been added to the domains of this app. Add all domains and subdomains of your app to the App domains field in your app's settings to load this URL.

Add dynamic fields in woocommerce

I try to add an input on the woocommerce billing-form., i want to use Ajax to render it dynamique.
It goes something like this :
One select input with for example :
choice 1
choice 2
Ie, when selecting "choice 1" another list with radio-boxes appear with choices in correlation with previous menu.
The function works perfectly without wordpress but when we add it on WP, it doesn't work. The function is duplicated and is not working properly
I added it to wp in function.php using require_once();
Can you help us to do this.
Thanks a lot
Le Conseil Informatique
my function work with like this (form_livraison.php):
<script type='text/javascript'>
function getXhr(){
var xhr = null;
if(window.XMLHttpRequest) // Firefox et autres
xhr = new XMLHttpRequest();
else if(window.ActiveXObject){ // Internet Explorer
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else { // XMLHttpRequest non supporté par le navigateur
alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
xhr = false;
}
return xhr;
}
/**
* Méthode qui sera appelée sur le click du bouton
*/
function go(){
var xhr = getXhr();
// On défini ce qu'on va faire quand on aura la réponse
xhr.onreadystatechange = function(){
// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
if(xhr.readyState == 4 && xhr.status == 200){
leselect = xhr.responseText;
// On se sert de innerHTML pour rajouter les options a la liste
document.getElementById('horaires').innerHTML = leselect;
}
}
// Ici on va voir comment faire du post
xhr.open("POST",'http://XX/ajax_livraison.php',true);
// ne pas oublier ça pour le post
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// ne pas oublier de poster les arguments
// ici, l'id du site
sel = document.getElementById('site');
idsite = sel.options[sel.selectedIndex].value;
xhr.send("idSite="+idsite);
}
</script>
<label>Lieux du retrait :</label>
<select name='site' id='site' onchange='go()'>
<option value='-1'>Aucun</option>
<?php
$bdd = new PDO('mysql:host=XX', 'XX', 'XX'); //Connexion à la base
$req = $bdd->query('SELECT * FROM site ORDER BY ville');//Récupération des informations
while($row = $req->fetch()){
echo "<option value='".$row["id"]."'>".$row["ville"]."</option>";
}
?>
</select>
<div id='horaires'>
Horaires :<br/>
</div>
this one call this page (ajax_livraison.php)
<?php
setlocale (LC_TIME, 'fr_FR.utf8','fra'); //Mise en français de la date
echo "Horaires : <br/> Nous sommes le ".(strftime("%A %d %B"))."<br/>"; //Affichage de la date
$num_jour = date("N"); //Récupération du numéro du jour (Lundi 1 -> Dimanche 7)
if(isset($_POST["idSite"])){ //si un élément est sélectionné...
$bdd = new PDO('mysql:host=XX', 'XX', 'XX'); //Connexion à la base
//mysql_select_db("test");
//$res = mysql_query("SELECT * FROM horaires WHERE idSite=".$_POST["idSite"]); //Récupération des informations
$req = $bdd->prepare('SELECT * FROM horaires WHERE idSite = ?');
$req->execute(array($_POST['idSite']));
$resultfinal = array(); //Création d'un tableau
while($row = $req->fetch()){ //Boucle tant qu'il y a des résultats
$inter_jour = $num_jour - $row['id_jour']; //Calcul de l'intervalle entre le jour J et le jour de livraison
if ($inter_jour>=0){ //Si intervalle de livraison supérieur ou égale à 0
$compte_jour = date('d')+(7-$inter_jour); //Calcul jour livraison
}
else{
$compte_jour = date('d')-$inter_jour; //Sinon idem avant
}
$date_livraison = strftime("%A %d %B",mktime(0,0,0,date('m'),$compte_jour,date('Y'))); //Récupération de la date de livraison suite au calcul
$num_livraison = strftime("%d", mktime(0,0,0,date('m'),$compte_jour,date('Y'))); //Récupération numéro livraison suite au calcul
if((($num_jour+1) == $row["id_jour"]) && $row['idSite']==1){ //Si livraison = J+1 et site de livraison == Massy
$write = "<input type='radio' name='heures' id='".$row["id"]."' value='".$row["id"]."' checked><label for='".$row["id"]."'> ".$date_livraison." 16h00 - 20h00</label><br/>";
}
else{
$write = "<input type='radio' name='heures' id='".$row["id"]."' value='".$row["id"]."'><label for='".$row["id"]."'> ".$date_livraison." ".$row["am"]." ".$row["pm"]."</label><br/>";
}
$resultfinal[$num_livraison] = $write; //Ajout de la ligne en fin de tableau
}
ksort($resultfinal); //Trie du tableau par la clé
foreach ($resultfinal as $key => $value) { //Pour chaque ligne du tableau...
echo $value; //afficher le contenu
}
}
?>
so in function.php of wordpress i call it with require_once(form_livraison.php);
add_action( 'woocommerce_checkout_fields' , 'custom_store_pickup_field');
function custom_store_pickup_field($fields) {
require_once("form_livraison.php");
}
I hope you understand my function ^^
thanks for help

email not sent when trying to send as HTML

I am able to send plain text but not HTML..
Please assist as why the mail is not being recieved..
THX in advance :)
Below is the code:
$mailBody ='<table width="100%" >
<tr>
<td>
<img src="MailerImages/img_logo.gif" alt="UrMint.com"/>
<h1 style="font:bold 20px tahoma; color:#808080;">Hi #USERNAME,</h1>
<p style="font:13px tahoma; color:#666666; line-height:25px;">
Your password for xyzacccount associated with mobile no password #MOBNO is : <strong style="color:#e65786;">#PASSWORD</strong>
<br />
If you didn\'t request a new password, let us know immediately.
<br />
This message was sent from xyz.com at your request.
</p>
<strong style="font:bold 13px tahoma; color:#666666; line-height:25px;">
Happy Learning ,
<br />
The <span style="color:#42b1d6;">Ur</span><span style="color:#e65786;">urMint</span> Team
</strong>
</table>
';
echo $mailBody;
SendEMail_fun('xyz#gmail.com', $mailBody,'sub','xyzsender','xyz#rediffmail.com');
function SendEMail_fun($strEmailTo,$strEmailBody,$strSubject,$SenderName = '',$SenderEmail='')
{
global $SwiftMessage;
$SenderName = $SenderName <> ''?$SenderName:"support#xyz.com";
$SenderEmail = $SenderEmail <> ''?$SenderEmail:"support#xyz.com";
$email_from_name = $SenderName." <".$SenderEmail.">";
$email_from_mail = $SenderEmail;
$email_to_bcc= "";
$email_to= $strEmailTo;
$email_subject= $strSubject;
$emailbody =$strEmailBody;
try
{
require_once ("lib/Swift.php");
$smtp = new Swift_Connection_SMTP("localhost", 25);
$swift = new Swift($smtp);
$message = new Swift_Message($email_subject, $emailbody, "text/html");
$message->setFrom($email_from_name);
$message->setReplyTo($email_from_mail);
$message->setBcc($email_to_bcc);
if ($swift->send($message, $email_to, $email_from_mail))
{
//echo "Message sent";
echo $SwiftMessage = 'Message Sent';
return true;
}
else
{
//echo "Message failed to send";
echo $SwiftMessage = 'Message failed to send';
return false;
}
$swift->disconnect();
return true;
}
catch (Swift_ConnectionException $e)
{
// echo "There was a problem communicating with SMTP: " . $e->getMessage();
echo $SwiftMessage = "There was a problem communicating with SMTP: " . $e->getMessage();
return false;
}
catch (Swift_Message_MimeException $e)
{
// echo "There was an unexpected problem building the email:" . $e->getMessage();
echo $SwiftMessage = "There was an unexpected problem building the email:" . $e->getMessage();
return false;
}
}
I'm not sure the exact reason yours is not sending. I've included the html email script I always use. Hope it helps.
<?php
$myFile = "email.html";
$fh = fopen($myFile, 'r');
$htmlemail = fread($fh, filesize($myFile));
fclose($fh);
$to = "YOUREMAIL#gmail.com" . ",";
//$to .= "#gmail.com" . ",";
$subject = "SUBJECT";
$message = $htmlemail;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= 'From: NAME <email#email.com>' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
I'm wondering if the mail order has any effect on if it will work or not:
You have
if ($swift->send($message, $email_to, $email_from_mail))
Mine:
mail($to, $subject, $message, $headers);
Worth a shot

Cant send e-mail by php mail on first attempt

I'm trying to send an email via SMTP using PHPMailer on my site, it works the second time I try (use submit), but the first time it says it cannot authenticate, login or password is invalid. I have searched a lot and can't find the answer, can someone help me please?
By the way I'm using JSON to get the PHP response in an alert. My host doesn't have "smtp." in front because support told me to do it this way.
This is the code:
else {
$phpmail = new PHPMailer();
$phpmail->IsSMTP(); // envia por SMTP
$phpmail->Host = "velvetwebdesign.com.br"; // SMTP servers
$phpmail->Port = "587"; // Port
$phpmail->SMTPAuth = true; // Caso o servidor SMTP precise de autenticação
$phpmail->SMTPDebug = 1;
$phpmail->Username = "email#velvetwebdesign.com.br"; // SMTP username
$phpmail->Password = "xxxxxxx"; // SMTP password
$phpmail->IsHTML(true);
$phpmail->From = 'email#velvetwebdesign.com.br';
$phpmail->FromName = $_POST['nome'];
$phpmail->AddAddress("velvetwebdesign#velvetwebdesign.com.br");
$phpmail->AddAddress($_POST['email']);
$phpmail->Subject = 'Contato Velvet Web Design';
$phpmail->Body .= "<b>Cliente:</b> ".$_POST['nome']."<br />";
$phpmail->Body .= "<b>E-mail:</b> ".$_POST['email']."<br />";
$phpmail->Body .= "<b>Telefone:</b> ".$_POST['telefone']."<br />";
$phpmail->Body .= "<b>Assunto:</b> ".$_POST['assunto']."<br /><br />";
$phpmail->Body .= "<b>Mensagem:</b><br />".nl2br($_POST['mensagem'])."<br /><br />";
$phpmail->Body .= "Recebemos a sua mensagem, responderemos em breve.<br />";
$phpmail->Body .= "http://www.velvetwebdesign.com.br/";
$send = $phpmail->Send();
if($send){
echo "A Mensagem foi enviada com sucesso. Enviaremos uma copia para o seu e-mail tambem.";
exit;
}else{
echo "Tente novamente por favor. Erro: " .$phpmail->ErrorInfo;
exit;
}
}
?>

French characters not displaying correctly in PHP mail

I have a basic PHP mail form, but whatever I do, I cannot seem to get the characters to display correctly once sent, if the language is written with French accents.
The example sentence I am using is:
Bonjour, ceci est un message de test envoyé avec PHP pour analyser si
oui ou non la mise en forme est correcte ou fausse. Les personnages ne
devraient être rendus de manière appropriée comme prévu dans le
lexique français.
But it comes out as:
Bonjour, ceci est un message de test envoyé avec PHP pour analyser si
oui ou non la mise en forme est correcte ou fausse. Les personnages ne
devraient être rendus de manière appropriée comme prévu dans le
lexique français.
As you can see, the characters with accents are screwed up, once they are received in the email.
I am processing my message variable as such:
$fieldenquiry = utf8_encode($_POST['fieldenquiry']);
I am then, sending it like so:
$cc = "example#example.com";
$subject = "Website Enquiry";
$message = '<html><body>';
$message .= "<p><strong>Enquiry</strong><br />" . nl2br($fieldenquiry) . "</p>";
$message .= "</body></html>";
$headers = "From: " . $fieldemail . "\r\n";
$headers .= "Cc: " . $cc . "\r\n";
$headers .= "Reply-To: ". $fieldemail . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
mail($to, $subject, $message, $headers);
I'm not a PHP developer by any means. The form works in the sense that it sends etc, but I cannot figure out why the characters mess up. I am encoding the POST variable and I am sending the HTML format with a UTF-8 charset.
Help and guidance appreciated.
Michael.
EDIT:
I figured this out. See my answer below.
I figured it out if anyone is in need of a similar piece of help:
I changed this line:
$fieldenquiry = utf8_encode($_POST['fieldenquiry']);
To this:
$fieldenquiry = utf8_encode(htmlentities($_POST['fieldenquiry'], ENT_QUOTES, "UTF-8"));
I use the htmlentities() function with UTF-8 specified in the arguments.
This fixed the issue completely. Hope it helps someone.